text
stringlengths
7
1.01M
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos.Rpc.proto package POGOProtos.Rpc; /** * Protobuf type {@code POGOProtos.Rpc.OnboardingTelemetry} */ public final class OnboardingTelemetry extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:POGOProtos.Rpc.OnboardingTelemetry) OnboardingTelemetryOrBuilder { private static final long serialVersionUID = 0L; // Use OnboardingTelemetry.newBuilder() to construct. private OnboardingTelemetry(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private OnboardingTelemetry() { onboardingPath_ = 0; eventId_ = 0; conversation_ = ""; arStatus_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new OnboardingTelemetry(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private OnboardingTelemetry( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { int rawValue = input.readEnum(); onboardingPath_ = rawValue; break; } case 16: { int rawValue = input.readEnum(); eventId_ = rawValue; break; } case 24: { data_ = input.readInt32(); break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); conversation_ = s; break; } case 40: { int rawValue = input.readEnum(); arStatus_ = rawValue; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return POGOProtos.Rpc.POGOProtosRpc.internal_static_POGOProtos_Rpc_OnboardingTelemetry_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return POGOProtos.Rpc.POGOProtosRpc.internal_static_POGOProtos_Rpc_OnboardingTelemetry_fieldAccessorTable .ensureFieldAccessorsInitialized( POGOProtos.Rpc.OnboardingTelemetry.class, POGOProtos.Rpc.OnboardingTelemetry.Builder.class); } public static final int ONBOARDING_PATH_FIELD_NUMBER = 1; private int onboardingPath_; /** * <code>.POGOProtos.Rpc.OnboardingPathIds onboarding_path = 1;</code> * @return The enum numeric value on the wire for onboardingPath. */ @java.lang.Override public int getOnboardingPathValue() { return onboardingPath_; } /** * <code>.POGOProtos.Rpc.OnboardingPathIds onboarding_path = 1;</code> * @return The onboardingPath. */ @java.lang.Override public POGOProtos.Rpc.OnboardingPathIds getOnboardingPath() { @SuppressWarnings("deprecation") POGOProtos.Rpc.OnboardingPathIds result = POGOProtos.Rpc.OnboardingPathIds.valueOf(onboardingPath_); return result == null ? POGOProtos.Rpc.OnboardingPathIds.UNRECOGNIZED : result; } public static final int EVENT_ID_FIELD_NUMBER = 2; private int eventId_; /** * <code>.POGOProtos.Rpc.OnboardingEventIds event_id = 2;</code> * @return The enum numeric value on the wire for eventId. */ @java.lang.Override public int getEventIdValue() { return eventId_; } /** * <code>.POGOProtos.Rpc.OnboardingEventIds event_id = 2;</code> * @return The eventId. */ @java.lang.Override public POGOProtos.Rpc.OnboardingEventIds getEventId() { @SuppressWarnings("deprecation") POGOProtos.Rpc.OnboardingEventIds result = POGOProtos.Rpc.OnboardingEventIds.valueOf(eventId_); return result == null ? POGOProtos.Rpc.OnboardingEventIds.UNRECOGNIZED : result; } public static final int DATA_FIELD_NUMBER = 3; private int data_; /** * <code>int32 data = 3;</code> * @return The data. */ @java.lang.Override public int getData() { return data_; } public static final int CONVERSATION_FIELD_NUMBER = 4; private volatile java.lang.Object conversation_; /** * <code>string conversation = 4;</code> * @return The conversation. */ @java.lang.Override public java.lang.String getConversation() { java.lang.Object ref = conversation_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); conversation_ = s; return s; } } /** * <code>string conversation = 4;</code> * @return The bytes for conversation. */ @java.lang.Override public com.google.protobuf.ByteString getConversationBytes() { java.lang.Object ref = conversation_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); conversation_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AR_STATUS_FIELD_NUMBER = 5; private int arStatus_; /** * <code>.POGOProtos.Rpc.OnboardingArStatus ar_status = 5;</code> * @return The enum numeric value on the wire for arStatus. */ @java.lang.Override public int getArStatusValue() { return arStatus_; } /** * <code>.POGOProtos.Rpc.OnboardingArStatus ar_status = 5;</code> * @return The arStatus. */ @java.lang.Override public POGOProtos.Rpc.OnboardingArStatus getArStatus() { @SuppressWarnings("deprecation") POGOProtos.Rpc.OnboardingArStatus result = POGOProtos.Rpc.OnboardingArStatus.valueOf(arStatus_); return result == null ? POGOProtos.Rpc.OnboardingArStatus.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (onboardingPath_ != POGOProtos.Rpc.OnboardingPathIds.ONBOARDING_PATH_IDS_V1.getNumber()) { output.writeEnum(1, onboardingPath_); } if (eventId_ != POGOProtos.Rpc.OnboardingEventIds.ONBOARDING_EVENT_IDS_TOS_ACCEPTED.getNumber()) { output.writeEnum(2, eventId_); } if (data_ != 0) { output.writeInt32(3, data_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(conversation_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, conversation_); } if (arStatus_ != POGOProtos.Rpc.OnboardingArStatus.ONBOARDING_AR_STATUS_UNSET.getNumber()) { output.writeEnum(5, arStatus_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (onboardingPath_ != POGOProtos.Rpc.OnboardingPathIds.ONBOARDING_PATH_IDS_V1.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, onboardingPath_); } if (eventId_ != POGOProtos.Rpc.OnboardingEventIds.ONBOARDING_EVENT_IDS_TOS_ACCEPTED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, eventId_); } if (data_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(3, data_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(conversation_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, conversation_); } if (arStatus_ != POGOProtos.Rpc.OnboardingArStatus.ONBOARDING_AR_STATUS_UNSET.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(5, arStatus_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof POGOProtos.Rpc.OnboardingTelemetry)) { return super.equals(obj); } POGOProtos.Rpc.OnboardingTelemetry other = (POGOProtos.Rpc.OnboardingTelemetry) obj; if (onboardingPath_ != other.onboardingPath_) return false; if (eventId_ != other.eventId_) return false; if (getData() != other.getData()) return false; if (!getConversation() .equals(other.getConversation())) return false; if (arStatus_ != other.arStatus_) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ONBOARDING_PATH_FIELD_NUMBER; hash = (53 * hash) + onboardingPath_; hash = (37 * hash) + EVENT_ID_FIELD_NUMBER; hash = (53 * hash) + eventId_; hash = (37 * hash) + DATA_FIELD_NUMBER; hash = (53 * hash) + getData(); hash = (37 * hash) + CONVERSATION_FIELD_NUMBER; hash = (53 * hash) + getConversation().hashCode(); hash = (37 * hash) + AR_STATUS_FIELD_NUMBER; hash = (53 * hash) + arStatus_; hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static POGOProtos.Rpc.OnboardingTelemetry parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static POGOProtos.Rpc.OnboardingTelemetry parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static POGOProtos.Rpc.OnboardingTelemetry parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static POGOProtos.Rpc.OnboardingTelemetry parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static POGOProtos.Rpc.OnboardingTelemetry parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static POGOProtos.Rpc.OnboardingTelemetry parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static POGOProtos.Rpc.OnboardingTelemetry parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static POGOProtos.Rpc.OnboardingTelemetry parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static POGOProtos.Rpc.OnboardingTelemetry parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static POGOProtos.Rpc.OnboardingTelemetry parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static POGOProtos.Rpc.OnboardingTelemetry parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static POGOProtos.Rpc.OnboardingTelemetry parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(POGOProtos.Rpc.OnboardingTelemetry prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code POGOProtos.Rpc.OnboardingTelemetry} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:POGOProtos.Rpc.OnboardingTelemetry) POGOProtos.Rpc.OnboardingTelemetryOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return POGOProtos.Rpc.POGOProtosRpc.internal_static_POGOProtos_Rpc_OnboardingTelemetry_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return POGOProtos.Rpc.POGOProtosRpc.internal_static_POGOProtos_Rpc_OnboardingTelemetry_fieldAccessorTable .ensureFieldAccessorsInitialized( POGOProtos.Rpc.OnboardingTelemetry.class, POGOProtos.Rpc.OnboardingTelemetry.Builder.class); } // Construct using POGOProtos.Rpc.OnboardingTelemetry.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); onboardingPath_ = 0; eventId_ = 0; data_ = 0; conversation_ = ""; arStatus_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return POGOProtos.Rpc.POGOProtosRpc.internal_static_POGOProtos_Rpc_OnboardingTelemetry_descriptor; } @java.lang.Override public POGOProtos.Rpc.OnboardingTelemetry getDefaultInstanceForType() { return POGOProtos.Rpc.OnboardingTelemetry.getDefaultInstance(); } @java.lang.Override public POGOProtos.Rpc.OnboardingTelemetry build() { POGOProtos.Rpc.OnboardingTelemetry result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public POGOProtos.Rpc.OnboardingTelemetry buildPartial() { POGOProtos.Rpc.OnboardingTelemetry result = new POGOProtos.Rpc.OnboardingTelemetry(this); result.onboardingPath_ = onboardingPath_; result.eventId_ = eventId_; result.data_ = data_; result.conversation_ = conversation_; result.arStatus_ = arStatus_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof POGOProtos.Rpc.OnboardingTelemetry) { return mergeFrom((POGOProtos.Rpc.OnboardingTelemetry)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(POGOProtos.Rpc.OnboardingTelemetry other) { if (other == POGOProtos.Rpc.OnboardingTelemetry.getDefaultInstance()) return this; if (other.onboardingPath_ != 0) { setOnboardingPathValue(other.getOnboardingPathValue()); } if (other.eventId_ != 0) { setEventIdValue(other.getEventIdValue()); } if (other.getData() != 0) { setData(other.getData()); } if (!other.getConversation().isEmpty()) { conversation_ = other.conversation_; onChanged(); } if (other.arStatus_ != 0) { setArStatusValue(other.getArStatusValue()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { POGOProtos.Rpc.OnboardingTelemetry parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (POGOProtos.Rpc.OnboardingTelemetry) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int onboardingPath_ = 0; /** * <code>.POGOProtos.Rpc.OnboardingPathIds onboarding_path = 1;</code> * @return The enum numeric value on the wire for onboardingPath. */ @java.lang.Override public int getOnboardingPathValue() { return onboardingPath_; } /** * <code>.POGOProtos.Rpc.OnboardingPathIds onboarding_path = 1;</code> * @param value The enum numeric value on the wire for onboardingPath to set. * @return This builder for chaining. */ public Builder setOnboardingPathValue(int value) { onboardingPath_ = value; onChanged(); return this; } /** * <code>.POGOProtos.Rpc.OnboardingPathIds onboarding_path = 1;</code> * @return The onboardingPath. */ @java.lang.Override public POGOProtos.Rpc.OnboardingPathIds getOnboardingPath() { @SuppressWarnings("deprecation") POGOProtos.Rpc.OnboardingPathIds result = POGOProtos.Rpc.OnboardingPathIds.valueOf(onboardingPath_); return result == null ? POGOProtos.Rpc.OnboardingPathIds.UNRECOGNIZED : result; } /** * <code>.POGOProtos.Rpc.OnboardingPathIds onboarding_path = 1;</code> * @param value The onboardingPath to set. * @return This builder for chaining. */ public Builder setOnboardingPath(POGOProtos.Rpc.OnboardingPathIds value) { if (value == null) { throw new NullPointerException(); } onboardingPath_ = value.getNumber(); onChanged(); return this; } /** * <code>.POGOProtos.Rpc.OnboardingPathIds onboarding_path = 1;</code> * @return This builder for chaining. */ public Builder clearOnboardingPath() { onboardingPath_ = 0; onChanged(); return this; } private int eventId_ = 0; /** * <code>.POGOProtos.Rpc.OnboardingEventIds event_id = 2;</code> * @return The enum numeric value on the wire for eventId. */ @java.lang.Override public int getEventIdValue() { return eventId_; } /** * <code>.POGOProtos.Rpc.OnboardingEventIds event_id = 2;</code> * @param value The enum numeric value on the wire for eventId to set. * @return This builder for chaining. */ public Builder setEventIdValue(int value) { eventId_ = value; onChanged(); return this; } /** * <code>.POGOProtos.Rpc.OnboardingEventIds event_id = 2;</code> * @return The eventId. */ @java.lang.Override public POGOProtos.Rpc.OnboardingEventIds getEventId() { @SuppressWarnings("deprecation") POGOProtos.Rpc.OnboardingEventIds result = POGOProtos.Rpc.OnboardingEventIds.valueOf(eventId_); return result == null ? POGOProtos.Rpc.OnboardingEventIds.UNRECOGNIZED : result; } /** * <code>.POGOProtos.Rpc.OnboardingEventIds event_id = 2;</code> * @param value The eventId to set. * @return This builder for chaining. */ public Builder setEventId(POGOProtos.Rpc.OnboardingEventIds value) { if (value == null) { throw new NullPointerException(); } eventId_ = value.getNumber(); onChanged(); return this; } /** * <code>.POGOProtos.Rpc.OnboardingEventIds event_id = 2;</code> * @return This builder for chaining. */ public Builder clearEventId() { eventId_ = 0; onChanged(); return this; } private int data_ ; /** * <code>int32 data = 3;</code> * @return The data. */ @java.lang.Override public int getData() { return data_; } /** * <code>int32 data = 3;</code> * @param value The data to set. * @return This builder for chaining. */ public Builder setData(int value) { data_ = value; onChanged(); return this; } /** * <code>int32 data = 3;</code> * @return This builder for chaining. */ public Builder clearData() { data_ = 0; onChanged(); return this; } private java.lang.Object conversation_ = ""; /** * <code>string conversation = 4;</code> * @return The conversation. */ public java.lang.String getConversation() { java.lang.Object ref = conversation_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); conversation_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string conversation = 4;</code> * @return The bytes for conversation. */ public com.google.protobuf.ByteString getConversationBytes() { java.lang.Object ref = conversation_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); conversation_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string conversation = 4;</code> * @param value The conversation to set. * @return This builder for chaining. */ public Builder setConversation( java.lang.String value) { if (value == null) { throw new NullPointerException(); } conversation_ = value; onChanged(); return this; } /** * <code>string conversation = 4;</code> * @return This builder for chaining. */ public Builder clearConversation() { conversation_ = getDefaultInstance().getConversation(); onChanged(); return this; } /** * <code>string conversation = 4;</code> * @param value The bytes for conversation to set. * @return This builder for chaining. */ public Builder setConversationBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); conversation_ = value; onChanged(); return this; } private int arStatus_ = 0; /** * <code>.POGOProtos.Rpc.OnboardingArStatus ar_status = 5;</code> * @return The enum numeric value on the wire for arStatus. */ @java.lang.Override public int getArStatusValue() { return arStatus_; } /** * <code>.POGOProtos.Rpc.OnboardingArStatus ar_status = 5;</code> * @param value The enum numeric value on the wire for arStatus to set. * @return This builder for chaining. */ public Builder setArStatusValue(int value) { arStatus_ = value; onChanged(); return this; } /** * <code>.POGOProtos.Rpc.OnboardingArStatus ar_status = 5;</code> * @return The arStatus. */ @java.lang.Override public POGOProtos.Rpc.OnboardingArStatus getArStatus() { @SuppressWarnings("deprecation") POGOProtos.Rpc.OnboardingArStatus result = POGOProtos.Rpc.OnboardingArStatus.valueOf(arStatus_); return result == null ? POGOProtos.Rpc.OnboardingArStatus.UNRECOGNIZED : result; } /** * <code>.POGOProtos.Rpc.OnboardingArStatus ar_status = 5;</code> * @param value The arStatus to set. * @return This builder for chaining. */ public Builder setArStatus(POGOProtos.Rpc.OnboardingArStatus value) { if (value == null) { throw new NullPointerException(); } arStatus_ = value.getNumber(); onChanged(); return this; } /** * <code>.POGOProtos.Rpc.OnboardingArStatus ar_status = 5;</code> * @return This builder for chaining. */ public Builder clearArStatus() { arStatus_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:POGOProtos.Rpc.OnboardingTelemetry) } // @@protoc_insertion_point(class_scope:POGOProtos.Rpc.OnboardingTelemetry) private static final POGOProtos.Rpc.OnboardingTelemetry DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new POGOProtos.Rpc.OnboardingTelemetry(); } public static POGOProtos.Rpc.OnboardingTelemetry getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<OnboardingTelemetry> PARSER = new com.google.protobuf.AbstractParser<OnboardingTelemetry>() { @java.lang.Override public OnboardingTelemetry parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new OnboardingTelemetry(input, extensionRegistry); } }; public static com.google.protobuf.Parser<OnboardingTelemetry> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<OnboardingTelemetry> getParserForType() { return PARSER; } @java.lang.Override public POGOProtos.Rpc.OnboardingTelemetry getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
import java.util.*; public class A{ public static void main(String args[]){ System.out.println("hello friends"); }}
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. /* * @author Eugene Zhuravlev */ package com.intellij.debugger.jdi; import com.intellij.Patches; import com.intellij.debugger.engine.DebugProcess; import com.intellij.debugger.engine.DebugProcessImpl; import com.intellij.debugger.engine.DebuggerManagerThreadImpl; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.jdi.VirtualMachineProxy; import com.intellij.debugger.impl.attach.SAJDWPRemoteConnection; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ReflectionUtil; import com.intellij.util.ThreeState; import com.sun.jdi.*; import com.sun.jdi.event.EventQueue; import com.sun.jdi.request.EventRequestManager; import one.util.streamex.StreamEx; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class VirtualMachineProxyImpl implements JdiTimer, VirtualMachineProxy { private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.jdi.VirtualMachineProxyImpl"); private final DebugProcessImpl myDebugProcess; private final VirtualMachine myVirtualMachine; private int myTimeStamp = 0; private int myPausePressedCount = 0; // cached data private final Map<ObjectReference, ObjectReferenceProxyImpl> myObjectReferenceProxies = new HashMap<>(); private final Map<String, StringReference> myStringLiteralCache = new HashMap<>(); @NotNull private final Map<ThreadReference, ThreadReferenceProxyImpl> myAllThreads = new ConcurrentHashMap<>(); private final Map<ThreadGroupReference, ThreadGroupReferenceProxyImpl> myThreadGroups = new HashMap<>(); private boolean myAllThreadsDirty = true; private List<ReferenceType> myAllClasses; private Map<ReferenceType, List<ReferenceType>> myNestedClassesCache = new HashMap<>(); public final Throwable mySuspendLogger = new Throwable(); private final boolean myVersionHigher_15; private final boolean myVersionHigher_14; public VirtualMachineProxyImpl(DebugProcessImpl debugProcess, @NotNull VirtualMachine virtualMachine) { myVirtualMachine = virtualMachine; myDebugProcess = debugProcess; myVersionHigher_15 = versionHigher("1.5"); myVersionHigher_14 = myVersionHigher_15 || versionHigher("1.4"); // avoid lazy-init for some properties: the following will pre-calculate values canRedefineClasses(); canWatchFieldModification(); canPopFrames(); try { // this will cache classes inside JDI and enable faster search of classes later virtualMachine.allClasses(); } catch (VMDisconnectedException e) { throw e; } catch (Throwable e) { // catch all exceptions in order not to break vm attach process // Example: // java.lang.IllegalArgumentException: Invalid JNI signature character ';' // caused by some bytecode "optimizers" which break type signatures as a side effect. // solution if you are using JAX-WS: add -Dcom.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize=true to JVM args LOG.info(e); } virtualMachine.topLevelThreadGroups().forEach(this::threadGroupCreated); } @NotNull public VirtualMachine getVirtualMachine() { return myVirtualMachine; } static final class JNITypeParserReflect { static final Method typeNameToSignatureMethod; static { Method method = null; try { method = ReflectionUtil.getDeclaredMethod(Class.forName("com.sun.tools.jdi.JNITypeParser"), "typeNameToSignature", String.class); } catch (ClassNotFoundException e) { LOG.warn(e); } typeNameToSignatureMethod = method; if (typeNameToSignatureMethod == null) { LOG.warn("Unable to find JNITypeParser.typeNameToSignature method"); } } @Nullable static String typeNameToSignature(@NotNull String name) { if (typeNameToSignatureMethod != null) { try { return (String)typeNameToSignatureMethod.invoke(null, name); } catch (Exception ignored) { } } return null; } } public ClassesByNameProvider getClassesByNameProvider() { return this::classesByName; } @Override public List<ReferenceType> classesByName(@NotNull String s) { return myVirtualMachine.classesByName(s); } @Override public List<ReferenceType> nestedTypes(ReferenceType refType) { List<ReferenceType> nestedTypes = myNestedClassesCache.get(refType); if (nestedTypes == null) { List<ReferenceType> list = Collections.emptyList(); try { list = refType.nestedTypes(); } catch (Throwable e) { // sometimes some strange errors are thrown from JDI. Do not crash debugger because of this. // Example: //java.lang.StringIndexOutOfBoundsException: String index out of range: 487700285 // at java.lang.String.checkBounds(String.java:375) // at java.lang.String.<init>(String.java:415) // at com.sun.tools.jdi.PacketStream.readString(PacketStream.java:392) // at com.sun.tools.jdi.JDWP$VirtualMachine$AllClassesWithGeneric$ClassInfo.<init>(JDWP.java:1644) LOG.info(e); } if (!list.isEmpty()) { final Set<ReferenceType> candidates = new HashSet<>(); final ClassLoaderReference outerLoader = refType.classLoader(); for (ReferenceType nested : list) { try { if (outerLoader == null? nested.classLoader() == null : outerLoader.equals(nested.classLoader())) { candidates.add(nested); } } catch (ObjectCollectedException ignored) { } } if (!candidates.isEmpty()) { // keep only direct nested types final Set<ReferenceType> nested2 = new HashSet<>(); for (final ReferenceType candidate : candidates) { nested2.addAll(nestedTypes(candidate)); } candidates.removeAll(nested2); } nestedTypes = candidates.isEmpty() ? Collections.emptyList() : new ArrayList<>(candidates); } else { nestedTypes = Collections.emptyList(); } myNestedClassesCache.put(refType, nestedTypes); } return nestedTypes; } @Override public List<ReferenceType> allClasses() { List<ReferenceType> allClasses = myAllClasses; if (allClasses == null) { myAllClasses = allClasses = myVirtualMachine.allClasses(); } return allClasses; } public String toString() { return myVirtualMachine.toString(); } public void redefineClasses(Map<ReferenceType, byte[]> map) { DebuggerManagerThreadImpl.assertIsManagerThread(); try { myVirtualMachine.redefineClasses(map); } finally { clearCaches(); } } /** * @return a list of all ThreadReferenceProxies */ public Collection<ThreadReferenceProxyImpl> allThreads() { DebuggerManagerThreadImpl.assertIsManagerThread(); if (myAllThreadsDirty) { myAllThreadsDirty = false; for (ThreadReference threadReference : myVirtualMachine.allThreads()) { getThreadReferenceProxy(threadReference); // add a proxy } } return new ArrayList<>(myAllThreads.values()); } public void threadStarted(ThreadReference thread) { DebuggerManagerThreadImpl.assertIsManagerThread(); getThreadReferenceProxy(thread); // add a proxy } public void threadStopped(ThreadReference thread) { DebuggerManagerThreadImpl.assertIsManagerThread(); myAllThreads.remove(thread); } public void suspend() { if (!canBeModified()) { return; } DebuggerManagerThreadImpl.assertIsManagerThread(); myPausePressedCount++; myVirtualMachine.suspend(); clearCaches(); } public void resume() { if (!canBeModified()) { return; } DebuggerManagerThreadImpl.assertIsManagerThread(); if (myPausePressedCount > 0) { myPausePressedCount--; } clearCaches(); LOG.debug("before resume VM"); try { myVirtualMachine.resume(); } catch (InternalException e) { // ok to ignore. Although documentation says it is safe to invoke resume() on running VM, // sometimes this leads to com.sun.jdi.InternalException: Unexpected JDWP Error: 13 (THREAD_NOT_SUSPENDED) LOG.info(e); } LOG.debug("VM resumed"); //logThreads(); } /** * @return a list of threadGroupProxies */ public List<ThreadGroupReferenceProxyImpl> topLevelThreadGroups() { return StreamEx.of(getVirtualMachine().topLevelThreadGroups()).map(this::getThreadGroupReferenceProxy).toList(); } public void threadGroupCreated(ThreadGroupReference threadGroupReference){ DebuggerManagerThreadImpl.assertIsManagerThread(); if(!isJ2ME()) { ThreadGroupReferenceProxyImpl proxy = new ThreadGroupReferenceProxyImpl(this, threadGroupReference); myThreadGroups.put(threadGroupReference, proxy); } } public boolean isJ2ME() { return isJ2ME(getVirtualMachine()); } private static boolean isJ2ME(VirtualMachine virtualMachine) { return virtualMachine.version().startsWith("1.0"); } public void threadGroupRemoved(ThreadGroupReference threadGroupReference){ DebuggerManagerThreadImpl.assertIsManagerThread(); myThreadGroups.remove(threadGroupReference); } public EventQueue eventQueue() { return myVirtualMachine.eventQueue(); } public EventRequestManager eventRequestManager() { return myVirtualMachine.eventRequestManager(); } /** * @deprecated use {@link #mirrorOfVoid()} instead */ @Deprecated public VoidValue mirrorOf() throws EvaluateException { return mirrorOfVoid(); } public VoidValue mirrorOfVoid() { return myVirtualMachine.mirrorOfVoid(); } public BooleanValue mirrorOf(boolean b) { return myVirtualMachine.mirrorOf(b); } public ByteValue mirrorOf(byte b) { return myVirtualMachine.mirrorOf(b); } public CharValue mirrorOf(char c) { return myVirtualMachine.mirrorOf(c); } public ShortValue mirrorOf(short i) { return myVirtualMachine.mirrorOf(i); } public IntegerValue mirrorOf(int i) { return myVirtualMachine.mirrorOf(i); } public LongValue mirrorOf(long l) { return myVirtualMachine.mirrorOf(l); } public FloatValue mirrorOf(float v) { return myVirtualMachine.mirrorOf(v); } public DoubleValue mirrorOf(double v) { return myVirtualMachine.mirrorOf(v); } public StringReference mirrorOf(String s) { return myVirtualMachine.mirrorOf(s); } public StringReference mirrorOfStringLiteral(String s, ThrowableComputable<StringReference, EvaluateException> generator) throws EvaluateException { StringReference reference = myStringLiteralCache.get(s); if (reference != null && !reference.isCollected()) { return reference; } reference = generator.compute(); myStringLiteralCache.put(s, reference); return reference; } public Process process() { return myVirtualMachine.process(); } public void dispose() { try { myVirtualMachine.dispose(); } catch (UnsupportedOperationException e) { LOG.info(e); } finally { if (Patches.JDK_BUG_EVENT_CONTROLLER_LEAK) { // Memory leak workaround, see IDEA-163334 Object target = ReflectionUtil.getField(myVirtualMachine.getClass(), myVirtualMachine, null, "target"); if (target != null) { Thread controller = ReflectionUtil.getField(target.getClass(), target, Thread.class, "eventController"); if (controller != null) { controller.stop(); } } } } } public void exit(int i) { myVirtualMachine.exit(i); } private final Capability myWatchFielsModification = new Capability() { @Override protected boolean calcValue() { return myVirtualMachine.canWatchFieldModification(); } }; @Override public boolean canWatchFieldModification() { return myWatchFielsModification.isAvailable(); } private final Capability myWatchFieldAccess = new Capability() { @Override protected boolean calcValue() { return myVirtualMachine.canWatchFieldAccess(); } }; @Override public boolean canWatchFieldAccess() { return myWatchFieldAccess.isAvailable(); } private final Capability myIsJ2ME = new Capability() { @Override protected boolean calcValue() { return isJ2ME(); } }; @Override public boolean canInvokeMethods() { return !myIsJ2ME.isAvailable(); } private final Capability myGetBytecodes = new Capability() { @Override protected boolean calcValue() { return myVirtualMachine.canGetBytecodes(); } }; @Override public boolean canGetBytecodes() { return myGetBytecodes.isAvailable(); } private final Capability myGetConstantPool = new Capability() { @Override protected boolean calcValue() { return myVirtualMachine.canGetConstantPool(); } }; public boolean canGetConstantPool() { return myGetConstantPool.isAvailable(); } private final Capability myGetSyntheticAttribute = new Capability() { @Override protected boolean calcValue() { return myVirtualMachine.canGetSyntheticAttribute(); } }; public boolean canGetSyntheticAttribute() { return myGetSyntheticAttribute.isAvailable(); } private final Capability myGetOwnedMonitorInfo = new Capability() { @Override protected boolean calcValue() { return myVirtualMachine.canGetOwnedMonitorInfo(); } }; public boolean canGetOwnedMonitorInfo() { return myGetOwnedMonitorInfo.isAvailable(); } private final Capability myGetMonitorFrameInfo = new Capability() { @Override protected boolean calcValue() { return myVirtualMachine.canGetMonitorFrameInfo(); } }; public boolean canGetMonitorFrameInfo() { return myGetMonitorFrameInfo.isAvailable(); } private final Capability myGetCurrentContendedMonitor = new Capability() { @Override protected boolean calcValue() { return myVirtualMachine.canGetCurrentContendedMonitor(); } }; public boolean canGetCurrentContendedMonitor() { return myGetCurrentContendedMonitor.isAvailable(); } private final Capability myGetMonitorInfo = new Capability() { @Override protected boolean calcValue() { return myVirtualMachine.canGetMonitorInfo(); } }; public boolean canGetMonitorInfo() { return myGetMonitorInfo.isAvailable(); } private final Capability myUseInstanceFilters = new Capability() { @Override protected boolean calcValue() { return myVersionHigher_14 && myVirtualMachine.canUseInstanceFilters(); } }; public boolean canUseInstanceFilters() { return myUseInstanceFilters.isAvailable(); } private final Capability myRedefineClasses = new Capability() { @Override protected boolean calcValue() { return myVersionHigher_14 && myVirtualMachine.canRedefineClasses(); } }; public boolean canRedefineClasses() { return myRedefineClasses.isAvailable(); } private final Capability myAddMethod = new Capability() { @Override protected boolean calcValue() { return myVersionHigher_14 && myVirtualMachine.canAddMethod(); } }; public boolean canAddMethod() { return myAddMethod.isAvailable(); } private final Capability myUnrestrictedlyRedefineClasses = new Capability() { @Override protected boolean calcValue() { return myVersionHigher_14 && myVirtualMachine.canUnrestrictedlyRedefineClasses(); } }; public boolean canUnrestrictedlyRedefineClasses() { return myUnrestrictedlyRedefineClasses.isAvailable(); } private final Capability myPopFrames = new Capability() { @Override protected boolean calcValue() { return myVersionHigher_14 && myVirtualMachine.canPopFrames(); } }; public boolean canPopFrames() { return myPopFrames.isAvailable(); } private final Capability myForceEarlyReturn = new Capability() { @Override protected boolean calcValue() { return myVirtualMachine.canForceEarlyReturn(); } }; public boolean canForceEarlyReturn() { return myForceEarlyReturn.isAvailable(); } private final Capability myCanGetInstanceInfo = new Capability() { @Override protected boolean calcValue() { if (!myVersionHigher_15) { return false; } try { final Method method = VirtualMachine.class.getMethod("canGetInstanceInfo"); return (Boolean)method.invoke(myVirtualMachine); } catch (NoSuchMethodException ignored) { } catch (IllegalAccessException | InvocationTargetException e) { LOG.error(e); } return false; } }; public boolean canGetInstanceInfo() { return myCanGetInstanceInfo.isAvailable(); } public boolean canBeModified() { return !(myDebugProcess.getConnection() instanceof SAJDWPRemoteConnection) && myVirtualMachine.canBeModified(); } @Override public final boolean versionHigher(String version) { return myVirtualMachine.version().compareTo(version) >= 0; } private final Capability myGetSourceDebugExtension = new Capability() { @Override protected boolean calcValue() { return myVersionHigher_14 && myVirtualMachine.canGetSourceDebugExtension(); } }; public boolean canGetSourceDebugExtension() { return myGetSourceDebugExtension.isAvailable(); } private final Capability myRequestVMDeathEvent = new Capability() { @Override protected boolean calcValue() { return myVersionHigher_14 && myVirtualMachine.canRequestVMDeathEvent(); } }; public boolean canRequestVMDeathEvent() { return myRequestVMDeathEvent.isAvailable(); } private final Capability myGetMethodReturnValues = new Capability() { @Override protected boolean calcValue() { if (myVersionHigher_15) { //return myVirtualMachine.canGetMethodReturnValues(); try { //noinspection HardCodedStringLiteral final Method method = VirtualMachine.class.getDeclaredMethod("canGetMethodReturnValues"); final Boolean rv = (Boolean)method.invoke(myVirtualMachine); return rv.booleanValue(); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { } } return false; } }; public boolean canGetMethodReturnValues() { return myGetMethodReturnValues.isAvailable(); } public String getDefaultStratum() { return myVersionHigher_14 ? myVirtualMachine.getDefaultStratum() : null; } public String description() { return myVirtualMachine.description(); } public String version() { return myVirtualMachine.version(); } public String name() { return myVirtualMachine.name(); } public void setDebugTraceMode(int i) { myVirtualMachine.setDebugTraceMode(i); } @Nullable @Contract("null -> null; !null -> !null") public ThreadReferenceProxyImpl getThreadReferenceProxy(@Nullable ThreadReference thread) { DebuggerManagerThreadImpl.assertIsManagerThread(); if (thread == null) { return null; } return myAllThreads.computeIfAbsent(thread, t -> new ThreadReferenceProxyImpl(this, t)); } public ThreadGroupReferenceProxyImpl getThreadGroupReferenceProxy(ThreadGroupReference group) { DebuggerManagerThreadImpl.assertIsManagerThread(); if(group == null) { return null; } ThreadGroupReferenceProxyImpl proxy = myThreadGroups.get(group); if(proxy == null) { if(!myIsJ2ME.isAvailable()) { proxy = new ThreadGroupReferenceProxyImpl(this, group); myThreadGroups.put(group, proxy); } } return proxy; } public ObjectReferenceProxyImpl getObjectReferenceProxy(ObjectReference objectReference) { if (objectReference != null) { if (objectReference instanceof ThreadReference) { return getThreadReferenceProxy((ThreadReference)objectReference); } else if (objectReference instanceof ThreadGroupReference) { return getThreadGroupReferenceProxy((ThreadGroupReference)objectReference); } else { ObjectReferenceProxyImpl proxy = myObjectReferenceProxies.get(objectReference); if (proxy == null) { if (objectReference instanceof StringReference) { proxy = new StringReferenceProxy(this, (StringReference)objectReference); } else { proxy = new ObjectReferenceProxyImpl(this, objectReference); } myObjectReferenceProxies.put(objectReference, proxy); } return proxy; } } return null; } public boolean equals(Object obj) { LOG.assertTrue(obj instanceof VirtualMachineProxyImpl); return myVirtualMachine.equals(((VirtualMachineProxyImpl)obj).getVirtualMachine()); } public int hashCode() { return myVirtualMachine.hashCode(); } public void clearCaches() { LOG.debug("VM cleared"); myAllClasses = null; if (!myNestedClassesCache.isEmpty()) { myNestedClassesCache = new HashMap<>(myNestedClassesCache.size()); } //myAllThreadsDirty = true; myTimeStamp++; } @Override public int getCurrentTime() { return myTimeStamp; } @Override public DebugProcess getDebugProcess() { return myDebugProcess; } public static boolean isCollected(ObjectReference reference) { try { return !isJ2ME(reference.virtualMachine()) && reference.isCollected(); } catch (UnsupportedOperationException e) { LOG.info(e); } return false; } public String getResumeStack() { return StringUtil.getThrowableText(mySuspendLogger); } public boolean isPausePressed() { return myPausePressedCount > 0; } public boolean isSuspended() { return allThreads().stream().anyMatch(thread -> thread.getSuspendCount() != 0); } public void logThreads() { if (LOG.isDebugEnabled()) { for (ThreadReferenceProxyImpl thread : allThreads()) { if (!thread.isCollected()) { LOG.debug("suspends " + thread + " " + thread.getSuspendCount() + " " + thread.isSuspended()); } } } } private abstract static class Capability { private ThreeState myValue = ThreeState.UNSURE; public final boolean isAvailable() { if (myValue == ThreeState.UNSURE) { try { myValue = ThreeState.fromBoolean(calcValue()); } catch (VMDisconnectedException e) { LOG.info(e); myValue = ThreeState.NO; } } return myValue.toBoolean(); } protected abstract boolean calcValue(); } }
/* * Copyright 2016 Hippo Seven * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blackman.ehviewer.ui.scene; import android.util.Log; import com.blackman.ehviewer.client.data.GalleryInfo; import java.util.Arrays; import java.util.List; // TODO GridLayoutManager do not work at all ! SpaceGroupIndex is useless for layout! I need to create one by myself public class ThumbSpanHelper { private static final int MIN_ARRAY_LENGTH = 50; private static final int MAX_ROW_INTERVAL = 3; private final List<GalleryInfo> mData; // true for occupied, false for free private boolean[] mCells = new boolean[MIN_ARRAY_LENGTH]; private int mNextIndex; private int mNextGroupIndex; private int mNearSpaceIndex; private int mNearSpaceGroupIndex; private int mAttachedCount; private int mSpanCount; private boolean mEnable; public ThumbSpanHelper(List<GalleryInfo> data) { mData = data; } public void setEnable(boolean enable) { if (enable == mEnable) { return; } mEnable = enable; if (!enable) { clear(); mSpanCount = 0; } else { if (mSpanCount > 0) { rebuild(); } } } public void setSpanCount(int spanCount) { if (!mEnable) { return; } if (spanCount == mSpanCount) { return; } mSpanCount = spanCount; if (spanCount > 0) { rebuild(); } } public void notifyDataSetChanged() { if (!mEnable || mSpanCount <= 0) { return; } rebuild(); } public void notifyItemRangeRemoved(int positionStart, int itemCount) { if (!mEnable || mSpanCount <= 0) { return; } rebuild(); } protected void notifyItemRangeInserted(int positionStart, int itemCount) { if (!mEnable || mSpanCount <= 0) { return; } if (mAttachedCount == positionStart) { append(); } else { rebuild(); } } private void clear() { Log.d("TAG", "=======================clear======================="); if (mSpanCount > 0) { if (mNextGroupIndex > 0 || mNextIndex > 0) { Arrays.fill(mCells, 0, mNextGroupIndex * mSpanCount + mNextIndex, false); } } else { Arrays.fill(mCells, false); } mNextIndex = 0; mNextGroupIndex = 0; mNearSpaceIndex = 0; mNearSpaceGroupIndex = 0; mAttachedCount = 0; } private void rebuild() { clear(); append(); } private void append() { if (1 == mSpanCount) { for (int i = mAttachedCount, n = mData.size(); i < n; i++) { GalleryInfo gi = mData.get(i); gi.spanSize = 1; gi.spanGroupIndex = i; gi.spanIndex = 0; } mAttachedCount = mData.size(); } else if (mSpanCount >= 2) { for (int i = mAttachedCount, n = mData.size(); i < n; i++) { GalleryInfo gi = mData.get(i); int spanSize = gi.thumbWidth <= gi.thumbHeight ? 1 : 2; gi.spanSize = spanSize; if (1 == spanSize) { // Update near space updateNearSpace(); Log.d("TAG", "Update mNearSpaceGroupIndex = " + mNearSpaceGroupIndex + ", mNearSpaceIndex = " + mNearSpaceIndex); if (mNextIndex == mNearSpaceIndex && mNextGroupIndex == mNearSpaceGroupIndex) { // No space, just append gi.spanIndex = mNextIndex; gi.spanGroupIndex = mNextGroupIndex; // Update cell int start = gi.spanGroupIndex * mSpanCount + gi.spanIndex; fillCell(start, start + 1); // Update field mNextIndex++; if (mSpanCount == mNextIndex) { mNextIndex = 0; mNextGroupIndex++; } mNearSpaceIndex = mNextIndex; mNearSpaceGroupIndex = mNextGroupIndex; Log.d("TAG", "type 0"); Log.d("TAG", "i = " + i + ", spanSize = " + spanSize + ", spanGroupIndex = " + gi.spanGroupIndex + ", spanIndex = " + gi.spanIndex); Log.d("TAG", "mNextGroupIndex = " + mNextGroupIndex + ", mNextIndex = " + mNextIndex); Log.d("TAG", "mNearSpaceGroupIndex = " + mNearSpaceGroupIndex + ", mNearSpaceIndex = " + mNearSpaceIndex); } else { // Found space gi.spanIndex = mNearSpaceIndex; gi.spanGroupIndex = mNearSpaceGroupIndex; // Update cell int start = gi.spanGroupIndex * mSpanCount + gi.spanIndex; fillCell(start, start + 1); // Find near space findNearSpace(start + 1); Log.d("TAG", "type 1"); Log.d("TAG", "i = " + i + ", spanSize = " + spanSize + ", spanGroupIndex = " + gi.spanGroupIndex + ", spanIndex = " + gi.spanIndex); Log.d("TAG", "mNextGroupIndex = " + mNextGroupIndex + ", mNextIndex = " + mNextIndex); Log.d("TAG", "mNearSpaceGroupIndex = " + mNearSpaceGroupIndex + ", mNearSpaceIndex = " + mNearSpaceIndex); } } else { boolean syncNear = mNextIndex == mNearSpaceIndex && mNextGroupIndex == mNearSpaceGroupIndex; // false for old, true for new boolean oldOrNew; if (mSpanCount - mNextIndex >= 2) { gi.spanIndex = mNextIndex; gi.spanGroupIndex = mNextGroupIndex; oldOrNew = true; } else { // Go to next row gi.spanIndex = 0; gi.spanGroupIndex = mNextGroupIndex + 1; oldOrNew = false; } // Update cell int start = gi.spanGroupIndex * mSpanCount + gi.spanIndex; fillCell(start, start + 2); // Update field if (syncNear && !oldOrNew) { mNearSpaceIndex = mNextIndex; mNearSpaceGroupIndex = mNextGroupIndex; } mNextIndex = gi.spanIndex + 2; mNextGroupIndex = gi.spanGroupIndex; if (mSpanCount == mNextIndex) { mNextIndex = 0; mNextGroupIndex++; } if (syncNear && oldOrNew) { mNearSpaceIndex = mNextIndex; mNearSpaceGroupIndex = mNextGroupIndex; } Log.d("TAG", "type 2"); Log.d("TAG", "i = " + i + ", spanSize = " + spanSize + ", spanGroupIndex = " + gi.spanGroupIndex + ", spanIndex = " + gi.spanIndex); Log.d("TAG", "mNextGroupIndex = " + mNextGroupIndex + ", mNextIndex = " + mNextIndex); Log.d("TAG", "mNearSpaceGroupIndex = " + mNearSpaceGroupIndex + ", mNearSpaceIndex = " + mNearSpaceIndex); } } mAttachedCount = mData.size(); } } private void updateNearSpace() { // Check is space is near enough if (mNextGroupIndex - mNearSpaceGroupIndex <= MAX_ROW_INTERVAL) { return; } // The space is too far, find a near one int start = Math.max(0, mNextGroupIndex - MAX_ROW_INTERVAL) * mSpanCount; findNearSpace(start); } private void findNearSpace(int start) { int end = mNextGroupIndex * mSpanCount + mNextIndex; boolean[] cells = mCells; for (int i = start; i < end; i++) { if (!cells[i]) { // Find space ! mNearSpaceIndex = i % mSpanCount; mNearSpaceGroupIndex = i / mSpanCount; return; } } // Can't find space mNearSpaceIndex = mNextIndex; mNearSpaceGroupIndex = mNextGroupIndex; } private void fillCell(int start, int end) { boolean[] array = mCells; // Avoid IndexOutOfBoundsException if (end >= array.length) { boolean[] newArray = new boolean[end + (end < (MIN_ARRAY_LENGTH / 2) ? MIN_ARRAY_LENGTH : end >> 1)]; System.arraycopy(array, 0, newArray, 0, array.length); mCells = array = newArray; } Arrays.fill(array, start, end, true); } }
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.tests.java.lang; import junit.framework.TestCase; public class Character_UnicodeBlockTest extends TestCase { public void test_ofC() { assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of((char) 0x0)); assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of((char) 0x7f)); assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of((char) 0x80)); assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of((char) 0xff)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of((char) 0x100)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of((char) 0x17f)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of((char) 0x180)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of((char) 0x24f)); assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of((char) 0x250)); assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of((char) 0x2af)); assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of((char) 0x2b0)); assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of((char) 0x2ff)); assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of((char) 0x300)); assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of((char) 0x36f)); assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of((char) 0x370)); assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of((char) 0x3ff)); assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of((char) 0x400)); assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of((char) 0x4ff)); assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of((char) 0x500)); assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of((char) 0x52f)); assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of((char) 0x530)); assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of((char) 0x58f)); assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of((char) 0x590)); assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of((char) 0x5ff)); assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of((char) 0x600)); assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of((char) 0x6ff)); assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of((char) 0x700)); assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of((char) 0x74f)); assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of((char) 0x780)); assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of((char) 0x7bf)); assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of((char) 0x900)); assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of((char) 0x97f)); assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of((char) 0x980)); assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of((char) 0x9ff)); assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of((char) 0xa00)); assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of((char) 0xa7f)); assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of((char) 0xa80)); assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of((char) 0xaff)); assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of((char) 0xb00)); assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of((char) 0xb7f)); assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of((char) 0xb80)); assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of((char) 0xbff)); assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of((char) 0xc00)); assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of((char) 0xc7f)); assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of((char) 0xc80)); assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of((char) 0xcff)); assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of((char) 0xd00)); assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of((char) 0xd7f)); assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of((char) 0xd80)); assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of((char) 0xdff)); assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of((char) 0xe00)); assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of((char) 0xe7f)); assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of((char) 0xe80)); assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of((char) 0xeff)); assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of((char) 0xf00)); assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of((char) 0xfff)); assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of((char) 0x1000)); assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of((char) 0x109f)); assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of((char) 0x10a0)); assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of((char) 0x10ff)); assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of((char) 0x1100)); assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of((char) 0x11ff)); assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of((char) 0x1200)); assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of((char) 0x137f)); assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of((char) 0x13a0)); assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of((char) 0x13ff)); assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of((char) 0x1400)); assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of((char) 0x167f)); assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of((char) 0x1680)); assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of((char) 0x169f)); assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of((char) 0x16a0)); assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of((char) 0x16ff)); assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of((char) 0x1700)); assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of((char) 0x171f)); assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of((char) 0x1720)); assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of((char) 0x173f)); assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of((char) 0x1740)); assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of((char) 0x175f)); assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of((char) 0x1760)); assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of((char) 0x177f)); assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of((char) 0x1780)); assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of((char) 0x17ff)); assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of((char) 0x1800)); assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of((char) 0x18af)); assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of((char) 0x1900)); assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of((char) 0x194f)); assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of((char) 0x1950)); assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of((char) 0x197f)); assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of((char) 0x19e0)); assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of((char) 0x19ff)); assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char) 0x1d00)); assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char) 0x1d7f)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of((char) 0x1e00)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of((char) 0x1eff)); assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of((char) 0x1f00)); assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of((char) 0x1fff)); assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of((char) 0x2000)); assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of((char) 0x206f)); assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of((char) 0x2070)); assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of((char) 0x209f)); assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of((char) 0x20a0)); assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of((char) 0x20cf)); assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of((char) 0x20d0)); assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of((char) 0x20ff)); assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of((char) 0x2100)); assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of((char) 0x214f)); assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of((char) 0x2150)); assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of((char) 0x218f)); assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of((char) 0x2190)); assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of((char) 0x21ff)); assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char) 0x2200)); assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char) 0x22ff)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of((char) 0x2300)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of((char) 0x23ff)); assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of((char) 0x2400)); assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of((char) 0x243f)); assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of((char) 0x2440)); assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of((char) 0x245f)); assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of((char) 0x2460)); assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of((char) 0x24ff)); assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of((char) 0x2500)); assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of((char) 0x257f)); assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of((char) 0x2580)); assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of((char) 0x259f)); assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of((char) 0x25a0)); assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of((char) 0x25ff)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of((char) 0x2600)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of((char) 0x26ff)); assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of((char) 0x2700)); assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of((char) 0x27bf)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of((char) 0x27c0)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of((char) 0x27ef)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of((char) 0x27f0)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of((char) 0x27ff)); assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of((char) 0x2800)); assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of((char) 0x28ff)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of((char) 0x2900)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of((char) 0x297f)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of((char) 0x2980)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of((char) 0x29ff)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char) 0x2a00)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char) 0x2aff)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of((char) 0x2b00)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of((char) 0x2bff)); assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of((char) 0x2e80)); assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of((char) 0x2eff)); assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of((char) 0x2f00)); assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of((char) 0x2fdf)); assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of((char) 0x2ff0)); assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of((char) 0x2fff)); assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of((char) 0x3000)); assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of((char) 0x303f)); assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of((char) 0x3040)); assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of((char) 0x309f)); assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of((char) 0x30a0)); assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of((char) 0x30ff)); assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of((char) 0x3100)); assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of((char) 0x312f)); assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of((char) 0x3130)); assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of((char) 0x318f)); assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of((char) 0x3190)); assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of((char) 0x319f)); assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of((char) 0x31a0)); assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of((char) 0x31bf)); assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char) 0x31f0)); assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char) 0x31ff)); assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of((char) 0x3200)); assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of((char) 0x32ff)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of((char) 0x3300)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of((char) 0x33ff)); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of((char) 0x3400)); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of((char) 0x4dbf)); assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of((char) 0x4dc0)); assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of((char) 0x4dff)); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of((char) 0x4e00)); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of((char) 0x9fff)); assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of((char) 0xa000)); assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of((char) 0xa48f)); assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of((char) 0xa490)); assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of((char) 0xa4cf)); assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of((char) 0xac00)); assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of((char) 0xd7af)); assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of((char) 0xd800)); assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of((char) 0xdb7f)); assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of((char) 0xdb80)); assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of((char) 0xdbff)); assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of((char) 0xdc00)); assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of((char) 0xdfff)); assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of((char) 0xe000)); assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of((char) 0xf8ff)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of((char) 0xf900)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of((char) 0xfaff)); assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of((char) 0xfb00)); assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of((char) 0xfb4f)); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of((char) 0xfb50)); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of((char) 0xfdff)); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of((char) 0xfe00)); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of((char) 0xfe0f)); assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of((char) 0xfe20)); assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of((char) 0xfe2f)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of((char) 0xfe30)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of((char) 0xfe4f)); assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of((char) 0xfe50)); assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of((char) 0xfe6f)); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of((char) 0xfe70)); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of((char) 0xfeff)); assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of((char) 0xff00)); assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of((char) 0xffef)); assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of((char) 0xfff0)); assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of((char) 0xffff)); // Negative test: The range [0x0860, 0x08A0) is currently unassigned. assertEquals(null, Character.UnicodeBlock.of((char) 0x0860)); assertEquals(null, Character.UnicodeBlock.of((char) 0x089F)); } public void test_ofI() { assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of(0x0)); assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of(0x7f)); assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of(0x80)); assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of(0xff)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of(0x100)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of(0x17f)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of(0x180)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of(0x24f)); assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of(0x250)); assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of(0x2af)); assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of(0x2b0)); assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of(0x2ff)); assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of(0x300)); assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of(0x36f)); assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of(0x370)); assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of(0x3ff)); assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of(0x400)); assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of(0x4ff)); assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of(0x500)); assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of(0x52f)); assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of(0x530)); assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of(0x58f)); assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of(0x590)); assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of(0x5ff)); assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of(0x600)); assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of(0x6ff)); assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of(0x700)); assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of(0x74f)); assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of(0x780)); assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of(0x7bf)); assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of(0x900)); assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of(0x97f)); assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of(0x980)); assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of(0x9ff)); assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of(0xa00)); assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of(0xa7f)); assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of(0xa80)); assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of(0xaff)); assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of(0xb00)); assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of(0xb7f)); assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of(0xb80)); assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of(0xbff)); assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of(0xc00)); assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of(0xc7f)); assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of(0xc80)); assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of(0xcff)); assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of(0xd00)); assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of(0xd7f)); assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of(0xd80)); assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of(0xdff)); assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of(0xe00)); assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of(0xe7f)); assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of(0xe80)); assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of(0xeff)); assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of(0xf00)); assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of(0xfff)); assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of(0x1000)); assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of(0x109f)); assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of(0x10a0)); assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of(0x10ff)); assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of(0x1100)); assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of(0x11ff)); assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of(0x1200)); assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of(0x137f)); assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of(0x13a0)); assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of(0x13ff)); assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of(0x1400)); assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of(0x167f)); assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of(0x1680)); assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of(0x169f)); assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of(0x16a0)); assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of(0x16ff)); assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of(0x1700)); assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of(0x171f)); assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of(0x1720)); assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of(0x173f)); assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of(0x1740)); assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of(0x175f)); assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of(0x1760)); assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of(0x177f)); assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of(0x1780)); assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of(0x17ff)); assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of(0x1800)); assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of(0x18af)); assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of(0x1900)); assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of(0x194f)); assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of(0x1950)); assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of(0x197f)); assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of(0x19e0)); assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of(0x19ff)); assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x1d00)); assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x1d7f)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of(0x1e00)); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of(0x1eff)); assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of(0x1f00)); assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of(0x1fff)); assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of(0x2000)); assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of(0x206f)); assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of(0x2070)); assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of(0x209f)); assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of(0x20a0)); assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of(0x20cf)); assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of(0x20d0)); assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of(0x20ff)); assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of(0x2100)); assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of(0x214f)); assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of(0x2150)); assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of(0x218f)); assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of(0x2190)); assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of(0x21ff)); assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x2200)); assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x22ff)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of(0x2300)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of(0x23ff)); assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of(0x2400)); assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of(0x243f)); assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of(0x2440)); assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of(0x245f)); assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of(0x2460)); assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of(0x24ff)); assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of(0x2500)); assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of(0x257f)); assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of(0x2580)); assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of(0x259f)); assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of(0x25a0)); assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of(0x25ff)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of(0x2600)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of(0x26ff)); assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of(0x2700)); assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of(0x27bf)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of(0x27c0)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of(0x27ef)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of(0x27f0)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of(0x27ff)); assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of(0x2800)); assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of(0x28ff)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of(0x2900)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of(0x297f)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of(0x2980)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of(0x29ff)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x2a00)); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x2aff)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of(0x2b00)); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of(0x2bff)); assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of(0x2e80)); assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of(0x2eff)); assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of(0x2f00)); assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of(0x2fdf)); assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of(0x2ff0)); assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of(0x2fff)); assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of(0x3000)); assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of(0x303f)); assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of(0x3040)); assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of(0x309f)); assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of(0x30a0)); assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of(0x30ff)); assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of(0x3100)); assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of(0x312f)); assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of(0x3130)); assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of(0x318f)); assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of(0x3190)); assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of(0x319f)); assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of(0x31a0)); assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of(0x31bf)); assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x31f0)); assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x31ff)); assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of(0x3200)); assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of(0x32ff)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of(0x3300)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of(0x33ff)); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of(0x3400)); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of(0x4dbf)); assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of(0x4dc0)); assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of(0x4dff)); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of(0x4e00)); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of(0x9fff)); assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of(0xa000)); assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of(0xa48f)); assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of(0xa490)); assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of(0xa4cf)); assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of(0xac00)); assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of(0xd7af)); assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of(0xd800)); assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of(0xdb7f)); assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of(0xdb80)); assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of(0xdbff)); assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of(0xdc00)); assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of(0xdfff)); assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of(0xe000)); assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of(0xf8ff)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of(0xf900)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of(0xfaff)); assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of(0xfb00)); assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of(0xfb4f)); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of(0xfb50)); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of(0xfdff)); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of(0xfe00)); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of(0xfe0f)); assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of(0xfe20)); assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of(0xfe2f)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of(0xfe30)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of(0xfe4f)); assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of(0xfe50)); assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of(0xfe6f)); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of(0xfe70)); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of(0xfeff)); assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of(0xff00)); assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of(0xffef)); assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of(0xfff0)); assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of(0xffff)); assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.of(0x10000)); assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.of(0x1007f)); assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.of(0x10080)); assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.of(0x100ff)); assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.of(0x10100)); assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.of(0x1013f)); assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.of(0x10300)); assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.of(0x1032f)); assertEquals(Character.UnicodeBlock.GOTHIC, Character.UnicodeBlock.of(0x10330)); assertEquals(Character.UnicodeBlock.GOTHIC, Character.UnicodeBlock.of(0x1034f)); assertEquals(Character.UnicodeBlock.UGARITIC, Character.UnicodeBlock.of(0x10380)); assertEquals(Character.UnicodeBlock.UGARITIC, Character.UnicodeBlock.of(0x1039f)); assertEquals(Character.UnicodeBlock.DESERET, Character.UnicodeBlock.of(0x10400)); assertEquals(Character.UnicodeBlock.DESERET, Character.UnicodeBlock.of(0x1044f)); assertEquals(Character.UnicodeBlock.SHAVIAN, Character.UnicodeBlock.of(0x10450)); assertEquals(Character.UnicodeBlock.SHAVIAN, Character.UnicodeBlock.of(0x1047f)); assertEquals(Character.UnicodeBlock.OSMANYA, Character.UnicodeBlock.of(0x10480)); assertEquals(Character.UnicodeBlock.OSMANYA, Character.UnicodeBlock.of(0x104af)); assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.of(0x10800)); assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.of(0x1083f)); assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d000)); assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d0ff)); assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d100)); assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d1ff)); assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.of(0x1d300)); assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.of(0x1d35f)); assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.of(0x1d400)); assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.of(0x1d7ff)); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.of(0x20000)); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.of(0x2a6df)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.of(0x2f800)); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.of(0x2fa1f)); assertEquals(Character.UnicodeBlock.TAGS, Character.UnicodeBlock.of(0xe0000)); assertEquals(Character.UnicodeBlock.TAGS, Character.UnicodeBlock.of(0xe007f)); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.of(0xe0100)); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.of(0xe01ef)); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.of(0xf0000)); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.of(0xfffff)); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.of(0x100000)); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.of(0x10ffff)); // Negative test: The range [0x0860, 0x08A0) is currently unassigned. assertEquals(null, Character.UnicodeBlock.of((char) 0x0860)); assertEquals(null, Character.UnicodeBlock.of((char) 0x089F)); } public void test_ofIExceptions() { try { Character.UnicodeBlock.of(Character.MAX_CODE_POINT + 1); fail("No illegal argument exception"); } catch (IllegalArgumentException e) { } } @SuppressWarnings("deprecation") public void test_forNameLjava_lang_String() { assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.forName("BASIC_LATIN")); assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.forName("Basic Latin")); assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.forName("BasicLatin")); assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.forName("LATIN_1_SUPPLEMENT")); assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.forName("Latin-1 Supplement")); assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.forName("Latin-1Supplement")); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.forName("LATIN_EXTENDED_A")); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.forName("Latin Extended-A")); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.forName("LatinExtended-A")); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.forName("LATIN_EXTENDED_B")); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.forName("Latin Extended-B")); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.forName("LatinExtended-B")); assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.forName("IPA_EXTENSIONS")); assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.forName("IPA Extensions")); assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.forName("IPAExtensions")); assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.forName("SPACING_MODIFIER_LETTERS")); assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.forName("Spacing Modifier Letters")); assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.forName("SpacingModifierLetters")); assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.forName("COMBINING_DIACRITICAL_MARKS")); assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.forName("Combining Diacritical Marks")); assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.forName("CombiningDiacriticalMarks")); assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("GREEK")); assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("Greek and Coptic")); assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("GreekandCoptic")); assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("Greek")); assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("Greek")); assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.forName("CYRILLIC")); assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.forName("CYRILLIC_SUPPLEMENTARY")); assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.forName("Cyrillic Supplementary")); assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.forName("CyrillicSupplementary")); assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.forName("ARMENIAN")); assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.forName("HEBREW")); assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.forName("ARABIC")); assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.forName("SYRIAC")); assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.forName("THAANA")); assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.forName("DEVANAGARI")); assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.forName("BENGALI")); assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.forName("GURMUKHI")); assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.forName("GUJARATI")); assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.forName("ORIYA")); assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.forName("TAMIL")); assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.forName("TELUGU")); assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.forName("KANNADA")); assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.forName("MALAYALAM")); assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.forName("SINHALA")); assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.forName("THAI")); assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.forName("LAO")); assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.forName("TIBETAN")); assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.forName("MYANMAR")); assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.forName("GEORGIAN")); assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.forName("HANGUL_JAMO")); assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.forName("Hangul Jamo")); assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.forName("HangulJamo")); assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.forName("ETHIOPIC")); assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.forName("CHEROKEE")); assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.forName("UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS")); assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.forName("Unified Canadian Aboriginal Syllabics")); assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.forName("UnifiedCanadianAboriginalSyllabics")); assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.forName("OGHAM")); assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.forName("RUNIC")); assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.forName("TAGALOG")); assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.forName("HANUNOO")); assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.forName("BUHID")); assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.forName("TAGBANWA")); assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.forName("KHMER")); assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.forName("MONGOLIAN")); assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.forName("LIMBU")); assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.forName("TAI_LE")); assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.forName("Tai Le")); assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.forName("TaiLe")); assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.forName("KHMER_SYMBOLS")); assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.forName("Khmer Symbols")); assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.forName("KhmerSymbols")); assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("PHONETIC_EXTENSIONS")); assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("Phonetic Extensions")); assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("PhoneticExtensions")); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.forName("LATIN_EXTENDED_ADDITIONAL")); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.forName("Latin Extended Additional")); assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.forName("LatinExtendedAdditional")); assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.forName("GREEK_EXTENDED")); assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.forName("Greek Extended")); assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.forName("GreekExtended")); assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.forName("GENERAL_PUNCTUATION")); assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.forName("General Punctuation")); assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.forName("GeneralPunctuation")); assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.forName("SUPERSCRIPTS_AND_SUBSCRIPTS")); assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.forName("Superscripts and Subscripts")); assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.forName("SuperscriptsandSubscripts")); assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.forName("CURRENCY_SYMBOLS")); assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.forName("Currency Symbols")); assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.forName("CurrencySymbols")); assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("COMBINING_MARKS_FOR_SYMBOLS")); assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("Combining Diacritical Marks for Symbols")); assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("CombiningDiacriticalMarksforSymbols")); assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("Combining Marks for Symbols")); assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("CombiningMarksforSymbols")); assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.forName("LETTERLIKE_SYMBOLS")); assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.forName("Letterlike Symbols")); assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.forName("LetterlikeSymbols")); assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.forName("NUMBER_FORMS")); assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.forName("Number Forms")); assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.forName("NumberForms")); assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.forName("ARROWS")); assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("MATHEMATICAL_OPERATORS")); assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("Mathematical Operators")); assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("MathematicalOperators")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.forName("MISCELLANEOUS_TECHNICAL")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.forName("Miscellaneous Technical")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.forName("MiscellaneousTechnical")); assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.forName("CONTROL_PICTURES")); assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.forName("Control Pictures")); assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.forName("ControlPictures")); assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.forName("OPTICAL_CHARACTER_RECOGNITION")); assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.forName("Optical Character Recognition")); assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.forName("OpticalCharacterRecognition")); assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.forName("ENCLOSED_ALPHANUMERICS")); assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.forName("Enclosed Alphanumerics")); assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.forName("EnclosedAlphanumerics")); assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.forName("BOX_DRAWING")); assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.forName("Box Drawing")); assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.forName("BoxDrawing")); assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.forName("BLOCK_ELEMENTS")); assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.forName("Block Elements")); assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.forName("BlockElements")); assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.forName("GEOMETRIC_SHAPES")); assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.forName("Geometric Shapes")); assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.forName("GeometricShapes")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.forName("MISCELLANEOUS_SYMBOLS")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.forName("Miscellaneous Symbols")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.forName("MiscellaneousSymbols")); assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.forName("DINGBATS")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.forName("MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.forName("Miscellaneous Mathematical Symbols-A")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.forName("MiscellaneousMathematicalSymbols-A")); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.forName("SUPPLEMENTAL_ARROWS_A")); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.forName("Supplemental Arrows-A")); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.forName("SupplementalArrows-A")); assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.forName("BRAILLE_PATTERNS")); assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.forName("Braille Patterns")); assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.forName("BraillePatterns")); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.forName("SUPPLEMENTAL_ARROWS_B")); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.forName("Supplemental Arrows-B")); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.forName("SupplementalArrows-B")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.forName("MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.forName("Miscellaneous Mathematical Symbols-B")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.forName("MiscellaneousMathematicalSymbols-B")); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("SUPPLEMENTAL_MATHEMATICAL_OPERATORS")); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("Supplemental Mathematical Operators")); assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("SupplementalMathematicalOperators")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.forName("MISCELLANEOUS_SYMBOLS_AND_ARROWS")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.forName("Miscellaneous Symbols and Arrows")); assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.forName("MiscellaneousSymbolsandArrows")); assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK_RADICALS_SUPPLEMENT")); assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK Radicals Supplement")); assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.forName("CJKRadicalsSupplement")); assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.forName("KANGXI_RADICALS")); assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.forName("Kangxi Radicals")); assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.forName("KangxiRadicals")); assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.forName("IDEOGRAPHIC_DESCRIPTION_CHARACTERS")); assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.forName("Ideographic Description Characters")); assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.forName("IdeographicDescriptionCharacters")); assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.forName("CJK_SYMBOLS_AND_PUNCTUATION")); assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.forName("CJK Symbols and Punctuation")); assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.forName("CJKSymbolsandPunctuation")); assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.forName("HIRAGANA")); assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.forName("KATAKANA")); assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.forName("BOPOMOFO")); assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.forName("HANGUL_COMPATIBILITY_JAMO")); assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.forName("Hangul Compatibility Jamo")); assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.forName("HangulCompatibilityJamo")); assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.forName("KANBUN")); assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.forName("BOPOMOFO_EXTENDED")); assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.forName("Bopomofo Extended")); assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.forName("BopomofoExtended")); assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("KATAKANA_PHONETIC_EXTENSIONS")); assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("Katakana Phonetic Extensions")); assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("KatakanaPhoneticExtensions")); assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.forName("ENCLOSED_CJK_LETTERS_AND_MONTHS")); assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.forName("Enclosed CJK Letters and Months")); assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.forName("EnclosedCJKLettersandMonths")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.forName("CJK_COMPATIBILITY")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.forName("CJK Compatibility")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.forName("CJKCompatibility")); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.forName("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A")); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.forName("CJK Unified Ideographs Extension A")); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.forName("CJKUnifiedIdeographsExtensionA")); assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.forName("YIJING_HEXAGRAM_SYMBOLS")); assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.forName("Yijing Hexagram Symbols")); assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.forName("YijingHexagramSymbols")); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK_UNIFIED_IDEOGRAPHS")); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK Unified Ideographs")); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.forName("CJKUnifiedIdeographs")); assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.forName("YI_SYLLABLES")); assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.forName("Yi Syllables")); assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.forName("YiSyllables")); assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.forName("YI_RADICALS")); assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.forName("Yi Radicals")); assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.forName("YiRadicals")); assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.forName("HANGUL_SYLLABLES")); assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.forName("Hangul Syllables")); assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.forName("HangulSyllables")); assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.forName("HIGH_SURROGATES")); assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.forName("High Surrogates")); assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.forName("HighSurrogates")); assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.forName("HIGH_PRIVATE_USE_SURROGATES")); assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.forName("High Private Use Surrogates")); assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.forName("HighPrivateUseSurrogates")); assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.forName("LOW_SURROGATES")); assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.forName("Low Surrogates")); assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.forName("LowSurrogates")); assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.forName("PRIVATE_USE_AREA")); assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.forName("Private Use Area")); assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.forName("PrivateUseArea")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK_COMPATIBILITY_IDEOGRAPHS")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK Compatibility Ideographs")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.forName("CJKCompatibilityIdeographs")); assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.forName("ALPHABETIC_PRESENTATION_FORMS")); assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.forName("Alphabetic Presentation Forms")); assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.forName("AlphabeticPresentationForms")); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.forName("ARABIC_PRESENTATION_FORMS_A")); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.forName("Arabic Presentation Forms-A")); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.forName("ArabicPresentationForms-A")); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.forName("VARIATION_SELECTORS")); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.forName("Variation Selectors")); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.forName("VariationSelectors")); assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.forName("COMBINING_HALF_MARKS")); assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.forName("Combining Half Marks")); assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.forName("CombiningHalfMarks")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.forName("CJK_COMPATIBILITY_FORMS")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.forName("CJK Compatibility Forms")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.forName("CJKCompatibilityForms")); assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.forName("SMALL_FORM_VARIANTS")); assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.forName("Small Form Variants")); assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.forName("SmallFormVariants")); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.forName("ARABIC_PRESENTATION_FORMS_B")); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.forName("Arabic Presentation Forms-B")); assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.forName("ArabicPresentationForms-B")); assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.forName("HALFWIDTH_AND_FULLWIDTH_FORMS")); assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.forName("Halfwidth and Fullwidth Forms")); assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.forName("HalfwidthandFullwidthForms")); assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.forName("SPECIALS")); assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.forName("LINEAR_B_SYLLABARY")); assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.forName("Linear B Syllabary")); assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.forName("LinearBSyllabary")); assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.forName("LINEAR_B_IDEOGRAMS")); assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.forName("Linear B Ideograms")); assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.forName("LinearBIdeograms")); assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.forName("AEGEAN_NUMBERS")); assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.forName("Aegean Numbers")); assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.forName("AegeanNumbers")); assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.forName("OLD_ITALIC")); assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.forName("Old Italic")); assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.forName("OldItalic")); assertEquals(Character.UnicodeBlock.GOTHIC, Character.UnicodeBlock.forName("GOTHIC")); assertEquals(Character.UnicodeBlock.UGARITIC, Character.UnicodeBlock.forName("UGARITIC")); assertEquals(Character.UnicodeBlock.DESERET, Character.UnicodeBlock.forName("DESERET")); assertEquals(Character.UnicodeBlock.SHAVIAN, Character.UnicodeBlock.forName("SHAVIAN")); assertEquals(Character.UnicodeBlock.OSMANYA, Character.UnicodeBlock.forName("OSMANYA")); assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.forName("CYPRIOT_SYLLABARY")); assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.forName("Cypriot Syllabary")); assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.forName("CypriotSyllabary")); assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("BYZANTINE_MUSICAL_SYMBOLS")); assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("Byzantine Musical Symbols")); assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("ByzantineMusicalSymbols")); assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("MUSICAL_SYMBOLS")); assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("Musical Symbols")); assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("MusicalSymbols")); assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.forName("TAI_XUAN_JING_SYMBOLS")); assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.forName("Tai Xuan Jing Symbols")); assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.forName("TaiXuanJingSymbols")); assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.forName("MATHEMATICAL_ALPHANUMERIC_SYMBOLS")); assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.forName("Mathematical Alphanumeric Symbols")); assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.forName("MathematicalAlphanumericSymbols")); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.forName("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B")); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.forName("CJK Unified Ideographs Extension B")); assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.forName("CJKUnifiedIdeographsExtensionB")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK Compatibility Ideographs Supplement")); assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.forName("CJKCompatibilityIdeographsSupplement")); assertEquals(Character.UnicodeBlock.TAGS, Character.UnicodeBlock.forName("TAGS")); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.forName("VARIATION_SELECTORS_SUPPLEMENT")); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.forName("Variation Selectors Supplement")); assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.forName("VariationSelectorsSupplement")); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.forName("SUPPLEMENTARY_PRIVATE_USE_AREA_A")); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.forName("Supplementary Private Use Area-A")); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.forName("SupplementaryPrivateUseArea-A")); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.forName("SUPPLEMENTARY_PRIVATE_USE_AREA_B")); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.forName("Supplementary Private Use Area-B")); assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.forName("SupplementaryPrivateUseArea-B")); } public void test_forNameLjava_lang_StringExceptions() { try { Character.UnicodeBlock.forName(null); fail(); } catch (NullPointerException expected) { } try { Character.UnicodeBlock.forName("INVALID_NAME"); fail(); } catch (IllegalArgumentException expected) { } // We don't map "SURROGATES_AREA" to the deprecated SURROGATES_AREA // enum value. ICU doesn't have any block corresponding to this since it's // now split into low surrogates and the high (normal/private use) // surrogates. Also, the only API that makes any reference to this goes // directly to ICU anyway. try { Character.UnicodeBlock.forName("SURROGATES_AREA"); fail(); } catch (IllegalArgumentException expected) { } } }
package org.checkerframework.checker.guieffect; import org.checkerframework.checker.guieffect.qual.AlwaysSafe; import org.checkerframework.checker.guieffect.qual.PolyUI; import org.checkerframework.checker.guieffect.qual.PolyUIEffect; import org.checkerframework.checker.guieffect.qual.PolyUIType; import org.checkerframework.checker.guieffect.qual.SafeEffect; import org.checkerframework.checker.guieffect.qual.SafeType; import org.checkerframework.checker.guieffect.qual.UI; import org.checkerframework.checker.guieffect.qual.UIEffect; import org.checkerframework.checker.guieffect.qual.UIPackage; import org.checkerframework.checker.guieffect.qual.UIType; import org.checkerframework.common.basetype.BaseAnnotatedTypeFactory; import org.checkerframework.common.basetype.BaseTypeChecker; import org.checkerframework.framework.source.Result; import org.checkerframework.framework.type.AnnotatedTypeMirror; import org.checkerframework.framework.type.treeannotator.ListTreeAnnotator; import org.checkerframework.framework.type.treeannotator.TreeAnnotator; import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.ElementUtils; import org.checkerframework.javacutil.TypesUtils; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; /** * Annotated type factory for the GUI Effect Checker. */ public class GuiEffectTypeFactory extends BaseAnnotatedTypeFactory { protected final boolean debugSpew; public GuiEffectTypeFactory(BaseTypeChecker checker, boolean spew) { // use true to enable flow inference, false to disable it super(checker, false); debugSpew = spew; this.postInit(); } // Could move this to a public method on the checker class public ExecutableElement findJavaOverride(ExecutableElement overrider, TypeMirror parentType) { if (parentType.getKind() != TypeKind.NONE) { if (debugSpew) { System.err.println("Searching for overridden methods from " + parentType); } TypeElement overriderClass = (TypeElement) overrider.getEnclosingElement(); TypeElement elem = (TypeElement) ((DeclaredType) parentType).asElement(); if (debugSpew) { System.err.println("necessary TypeElements acquired: " + elem); } for (Element e : elem.getEnclosedElements()) { if (debugSpew) { System.err.println("Considering element " + e); } if (e.getKind() == ElementKind.METHOD || e.getKind() == ElementKind.CONSTRUCTOR) { ExecutableElement ex = (ExecutableElement) e; boolean overrides = elements.overrides(overrider, ex, overriderClass); if (overrides) { return ex; } } } if (debugSpew) { System.err.println("Done considering elements of " + parentType); } } return null; } public boolean isPolymorphicType(TypeElement cls) { assert (cls != null); return getDeclAnnotation(cls, PolyUIType.class) != null || fromElement(cls).hasAnnotation(PolyUI.class); } public boolean isUIType(TypeElement cls) { if (debugSpew) { System.err.println(" isUIType(" + cls + ")"); } boolean targetClassUIP = fromElement(cls).hasAnnotation(UI.class); AnnotationMirror targetClassUITypeP = getDeclAnnotation(cls, UIType.class); AnnotationMirror targetClassSafeTypeP = getDeclAnnotation(cls, SafeType.class); if (targetClassSafeTypeP != null) { return false; // explicitly marked not a UI type } boolean hasUITypeDirectly = (targetClassUIP || targetClassUITypeP != null); if (hasUITypeDirectly) { return true; } // Anon inner classes should not inherit the package annotation, since // they're so often used for closures to run async on background // threads. if (isAnonymousType(cls)) { return false; } // We don't check polymorphic annos so we can make a couple methods of // an @UIType polymorphic explicitly // AnnotationMirror targetClassPolyP = getDeclAnnotation(cls, PolyUI.class); // AnnotationMirror targetClassPolyTypeP = getDeclAnnotation(cls, PolyUIType.class); boolean targetClassSafeP = fromElement(cls).hasAnnotation(AlwaysSafe.class); if (targetClassSafeP) { return false; // explicitly annotated otherwise } // Look for the package Element packageP = ElementUtils.enclosingPackage(cls); if (packageP != null) { if (debugSpew) { System.err.println("Found package " + packageP); } if (getDeclAnnotation(packageP, UIPackage.class) != null) { if (debugSpew) { System.err.println("Package " + packageP + " is annotated @UIPackage"); } return true; } } return false; } // TODO: is there a framework method for this? private static boolean isAnonymousType(TypeElement elem) { return elem.getSimpleName().length() == 0; } /* * Calling context annotations To make anon-inner-classes work, I need to climb the inheritance DAG, until I: - find the class/interface that declares this calling method (an anon inner class is a separate class that implements an interface) - check whether *that* declaration specifies @UI on either the type or method A method has the UI effect when: 1. A method is UI if annotated @UIEffect 2. A method is UI if the enclosing class is annotated @UI or @UIType and the method is not annotated @AlwaysSafe 3. A method is UI if the corresponding method in the super-class/interface is UI, and this method is not annotated @AlwaysSafe, and this method resides in an anonymous inner class (named classes still require a package/class/method annotation to make it UI, only anon inner classes have this inheritance-by-default) + A method must be *annotated* UI if the method it overrides is *annotated* UI + A method must be *annotated* UI if it overrides a UI method and the enclosing class is not UI 4. It is an error if a method is UI but the same method in a super-type is not UI 5. It is an error if two super-types specify the same method, where one type says it's UI and one says it's not (it's possible to simply enforce the weaker (safe) effect, but this seems more principled, it's easier --- backwards-compatible --- to change our minds about this later) */ public Effect getDeclaredEffect(ExecutableElement methodElt) { if (debugSpew) { System.err.println("begin mayHaveUIEffect(" + methodElt + ")"); } AnnotationMirror targetUIP = getDeclAnnotation(methodElt, UIEffect.class); AnnotationMirror targetSafeP = getDeclAnnotation(methodElt, SafeEffect.class); AnnotationMirror targetPolyP = getDeclAnnotation(methodElt, PolyUIEffect.class); TypeElement targetClassElt = (TypeElement) methodElt.getEnclosingElement(); if (debugSpew) { System.err.println("targetClassElt found"); } // Short-circuit if the method is explicitly annotated if (targetSafeP != null) { if (debugSpew) { System.err.println("Method marked @SafeEffect"); } return new Effect(SafeEffect.class); } else if (targetUIP != null) { if (debugSpew) { System.err.println("Method marked @UIEffect"); } return new Effect(UIEffect.class); } else if (targetPolyP != null) { if (debugSpew) { System.err.println("Method marked @PolyUIEffect"); } return new Effect(PolyUIEffect.class); } // The method is not explicitly annotated, so check class and package annotations, // and supertype effects if in an anonymous inner class if (isUIType(targetClassElt)) { // Already checked, no explicit @SafeEffect annotation return new Effect(UIEffect.class); } // Anonymous inner types should just get the effect of the parent by // default, rather than annotating every instance. Unless it's // implementing a polymorphic supertype, in which case we still want the // developer to be explicit. if (isAnonymousType(targetClassElt)) { boolean canInheritParentEffects = true; // Refine this for polymorphic parents DeclaredType directSuper = (DeclaredType) targetClassElt.getSuperclass(); TypeElement superElt = (TypeElement) directSuper.asElement(); // Anonymous subtypes of polymorphic classes other than object can't inherit if (getDeclAnnotation(superElt, PolyUIType.class) != null && !TypesUtils.isObject(directSuper)) { canInheritParentEffects = false; } else { for (TypeMirror ifaceM : targetClassElt.getInterfaces()) { DeclaredType iface = (DeclaredType) ifaceM; TypeElement ifaceElt = (TypeElement) iface.asElement(); if (getDeclAnnotation(ifaceElt, PolyUIType.class) != null) { canInheritParentEffects = false; } } } if (canInheritParentEffects) { Effect.EffectRange r = findInheritedEffectRange(targetClassElt, methodElt); return (r != null ? Effect.min(r.min, r.max) : new Effect(SafeEffect.class)); } } return new Effect(SafeEffect.class); } // Only the visitMethod call should pass true for warnings public Effect.EffectRange findInheritedEffectRange( TypeElement declaringType, ExecutableElement overridingMethod) { return findInheritedEffectRange(declaringType, overridingMethod, false, null); } public Effect.EffectRange findInheritedEffectRange( TypeElement declaringType, ExecutableElement overridingMethod, boolean issueConflictWarning, Tree errorNode) { assert (declaringType != null); ExecutableElement ui_override = null; ExecutableElement safe_override = null; ExecutableElement poly_override = null; // We must account for explicit annotation, type declaration annotations, and package annotations boolean isUI = (getDeclAnnotation(overridingMethod, UIEffect.class) != null || isUIType(declaringType)) && getDeclAnnotation(overridingMethod, SafeEffect.class) == null; boolean isPolyUI = getDeclAnnotation(overridingMethod, PolyUIEffect.class) != null; // TODO: We must account for @UI and @AlwaysSafe annotations for extends // and implements clauses, and do the proper substitution of @Poly effects and quals! // List<? extends TypeMirror> interfaces = declaringType.getInterfaces(); TypeMirror superclass = declaringType.getSuperclass(); while (superclass != null && superclass.getKind() != TypeKind.NONE) { ExecutableElement overrides = findJavaOverride(overridingMethod, superclass); if (overrides != null) { Effect eff = getDeclaredEffect(overrides); assert (eff != null); if (eff.isSafe()) { // found a safe override safe_override = overrides; if (isUI && issueConflictWarning) { checker.report( Result.failure( "override.effect.invalid", overridingMethod, declaringType, safe_override, superclass), errorNode); } if (isPolyUI && issueConflictWarning) { checker.report( Result.failure( "override.effect.invalid.polymorphic", overridingMethod, declaringType, safe_override, superclass), errorNode); } } else if (eff.isUI()) { // found a ui override ui_override = overrides; } else { assert (eff.isPoly()); poly_override = overrides; // TODO: Is this right? is the supertype covered by the // directSuperTypes() method all I need? Or should I be // using that utility method that returns a set of // annodecl-method pairs given a method that overrides stuff // if (isUI && issueConflictWarning) { // AnnotatedTypeMirror.AnnotatedDeclaredType supdecl = fromElement((TypeElement)(((DeclaredType)superclass).asElement()));//((DeclaredType)superclass).asElement()); // // Need to special case an anonymous class with @UI on the decl, because "new @UI Runnable {...}" parses as @UI on an anon class decl extending Runnable // boolean isAnonInstantiation = TypesUtils.isAnonymousType(ElementUtils.getType(declaringType)) && getDeclAnnotation(declaringType, UI.class) != null; // if (!isAnonInstantiation && !hasAnnotationByName(supdecl, UI.class)) { // checker.report(Result.failure("override.effect.invalid", "non-UI instantiation of "+supdecl), errorNode); // If uncommenting this, change the above line to match other calls of Result.failure("override.effect.invalid", ...) // } //} } } DeclaredType decl = (DeclaredType) superclass; superclass = ((TypeElement) decl.asElement()).getSuperclass(); } AnnotatedTypeMirror.AnnotatedDeclaredType annoDecl = fromElement(declaringType); for (AnnotatedTypeMirror.AnnotatedDeclaredType ty : annoDecl.directSuperTypes()) { ExecutableElement overrides = findJavaOverride(overridingMethod, ty.getUnderlyingType()); if (overrides != null) { Effect eff = getDeclaredEffect(overrides); if (eff.isSafe()) { // found a safe override safe_override = overrides; if (isUI && issueConflictWarning) { checker.report( Result.failure( "override.effect.invalid", overridingMethod, declaringType, safe_override, ty), errorNode); } if (isPolyUI && issueConflictWarning) { checker.report( Result.failure( "override.effect.invalid.polymorphic", overridingMethod, declaringType, safe_override, ty), errorNode); } } else if (eff.isUI()) { // found a ui override ui_override = overrides; } else { assert (eff.isPoly()); poly_override = overrides; if (isUI && issueConflictWarning) { AnnotatedTypeMirror.AnnotatedDeclaredType supdecl = ty; // Need to special case an anonymous class with @UI on // the decl, because "new @UI Runnable {...}" parses as // @UI on an anon class decl extending Runnable boolean isAnonInstantiation = isAnonymousType(declaringType) && fromElement(declaringType).hasAnnotation(UI.class); if (!isAnonInstantiation && !supdecl.hasAnnotation(UI.class)) { checker.report( Result.failure( "override.effect.invalid.nonui", overridingMethod, declaringType, poly_override, supdecl), errorNode); } } } } } // We don't need to issue warnings for inheriting from poly and a concrete effect. if (ui_override != null && safe_override != null && issueConflictWarning) { // There may be more than two parent methods, but for now it's // enough to know there are at least 2 in conflict checker.report( Result.warning( "override.effect.warning.inheritance", overridingMethod, declaringType, ui_override.toString(), ui_override.getEnclosingElement().asType().toString(), safe_override.toString(), safe_override.getEnclosingElement().asType().toString()), errorNode); } Effect min = (safe_override != null ? new Effect(SafeEffect.class) : (poly_override != null ? new Effect(PolyUIEffect.class) : (ui_override != null ? new Effect(UIEffect.class) : null))); Effect max = (ui_override != null ? new Effect(UIEffect.class) : (poly_override != null ? new Effect(PolyUIEffect.class) : (safe_override != null ? new Effect(SafeEffect.class) : null))); if (debugSpew) { System.err.println( "Found " + declaringType + "." + overridingMethod + " to have inheritance pair (" + min + "," + max + ")"); } if (min == null && max == null) { return null; } else { return new Effect.EffectRange(min, max); } } @Override protected TreeAnnotator createTreeAnnotator() { return new ListTreeAnnotator(super.createTreeAnnotator(), new GuiEffectTreeAnnotator()); } /** * A class for adding annotations based on tree. */ private class GuiEffectTreeAnnotator extends TreeAnnotator { GuiEffectTreeAnnotator() { super(GuiEffectTypeFactory.this); } public boolean hasExplicitUIEffect(ExecutableElement methElt) { return GuiEffectTypeFactory.this.getDeclAnnotation(methElt, UIEffect.class) != null; } public boolean hasExplicitSafeEffect(ExecutableElement methElt) { return GuiEffectTypeFactory.this.getDeclAnnotation(methElt, SafeEffect.class) != null; } public boolean hasExplicitPolyUIEffect(ExecutableElement methElt) { return GuiEffectTypeFactory.this.getDeclAnnotation(methElt, PolyUIEffect.class) != null; } public boolean hasExplicitEffect(ExecutableElement methElt) { return hasExplicitUIEffect(methElt) || hasExplicitSafeEffect(methElt) || hasExplicitPolyUIEffect(methElt); } @Override public Void visitMethod(MethodTree node, AnnotatedTypeMirror type) { AnnotatedTypeMirror.AnnotatedExecutableType methType = (AnnotatedTypeMirror.AnnotatedExecutableType) type; Effect e = getDeclaredEffect(methType.getElement()); TypeElement cls = (TypeElement) methType.getElement().getEnclosingElement(); // STEP 1: Get the method effect annotation if (!hasExplicitEffect(methType.getElement())) { // TODO: This line does nothing! // AnnotatedTypeMirror.addAnnotation silently ignores non-qualifier annotations! // We should be digging up the /declaration/ of the method, and annotating that. methType.addAnnotation(e.getAnnot()); } // STEP 2: Fix up the method receiver annotation AnnotatedTypeMirror.AnnotatedDeclaredType receiverType = methType.getReceiverType(); if (receiverType != null && !receiverType.isAnnotatedInHierarchy( AnnotationUtils.fromClass(elements, UI.class))) { receiverType.addAnnotation( isPolymorphicType(cls) ? PolyUI.class : fromElement(cls).hasAnnotation(UI.class) ? UI.class : AlwaysSafe.class); } return super.visitMethod(node, type); } } }
package com.codepath.flixster.models; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by abharath on 1/23/17. */ public class Movie { private String posterPath; private String backdropPath; private String originalTitle; private String overView; private int id; public Movie (JSONObject jsonObject) throws JSONException { this.posterPath = jsonObject.getString("poster_path"); this.backdropPath = jsonObject.getString("backdrop_path"); this.originalTitle = jsonObject.getString("original_title"); this.overView = jsonObject.getString("overview"); this.id = jsonObject.getInt("id"); } public static ArrayList<Movie> fromJsonArray (JSONArray array) { ArrayList<Movie> results = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { try { results.add(new Movie(array.getJSONObject(i))); } catch (JSONException e) { e.printStackTrace(); } } return results; } public String getPosterPath () { return String.format("https://image.tmdb.org/t/p/w342/%s", posterPath); } public String getBackdropPath () { return String.format("https://image.tmdb.org/t/p/w780/%s", backdropPath); } public String getOriginalTitle() { return originalTitle; } public String getOverView() { return overView; } public int getId() { return id;} }
package janken.step4.logic; import org.junit.Test; import static org.assertj.core.api.Assertions.*; public class HandNumberTest { @Test public void 対応する出し手に変換できる_グー() throws Exception { assertThat(HandNumber.ROCK.toHand()).isEqualTo(Hand.ROCK); } @Test public void 対応する出し手に変換できる_チョキ() throws Exception { assertThat(HandNumber.SCISSORS.toHand()).isEqualTo(Hand.SCISSORS); } @Test public void 対応する出し手に変換できる_パー() throws Exception { assertThat(HandNumber.PAPER.toHand()).isEqualTo(Hand.PAPER); } @Test public void _1は数値表現として有効() throws Exception { assertThat(HandNumber.isValid("1")).isTrue(); } @Test public void _2は数値表現として有効() throws Exception { assertThat(HandNumber.isValid("2")).isTrue(); } @Test public void _3は数値表現として有効() throws Exception { assertThat(HandNumber.isValid("3")).isTrue(); } @Test public void _4は数値表現として無効() throws Exception { assertThat(HandNumber.isValid("4")).isFalse(); } @Test public void aは数値表現として無効() throws Exception { assertThat(HandNumber.isValid("a")).isFalse(); } @Test public void _1を指定するとグーが取得できる() throws Exception { assertThat(HandNumber.of(1)).isEqualTo(HandNumber.ROCK); } @Test public void _2を指定するとチョキが取得できる() throws Exception { assertThat(HandNumber.of(2)).isEqualTo(HandNumber.SCISSORS); } @Test public void _3を指定するとパーが取得できる() throws Exception { assertThat(HandNumber.of(3)).isEqualTo(HandNumber.PAPER); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.fetcher; import java.io.File; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.nutch.crawl.CrawlDatum; import org.apache.nutch.crawl.NutchWritable; import org.apache.nutch.metadata.Nutch; import org.apache.nutch.util.NutchConfiguration; import org.apache.nutch.util.NutchJob; import org.apache.nutch.util.NutchTool; import org.apache.nutch.util.TimingUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A queue-based fetcher. * * <p> * This fetcher uses a well-known model of one producer (a QueueFeeder) and many * consumers (FetcherThread-s). * * <p> * QueueFeeder reads input fetchlists and populates a set of FetchItemQueue-s, * which hold FetchItem-s that describe the items to be fetched. There are as * many queues as there are unique hosts, but at any given time the total number * of fetch items in all queues is less than a fixed number (currently set to a * multiple of the number of threads). * * <p> * As items are consumed from the queues, the QueueFeeder continues to add new * input items, so that their total count stays fixed (FetcherThread-s may also * add new items to the queues e.g. as a results of redirection) - until all * input items are exhausted, at which point the number of items in the queues * begins to decrease. When this number reaches 0 fetcher will finish. * * <p> * This fetcher implementation handles per-host blocking itself, instead of * delegating this work to protocol-specific plugins. Each per-host queue * handles its own "politeness" settings, such as the maximum number of * concurrent requests and crawl delay between consecutive requests - and also a * list of requests in progress, and the time the last request was finished. As * FetcherThread-s ask for new items to be fetched, queues may return eligible * items or null if for "politeness" reasons this host's queue is not yet ready. * * <p> * If there are still unfetched items in the queues, but none of the items are * ready, FetcherThread-s will spin-wait until either some items become * available, or a timeout is reached (at which point the Fetcher will abort, * assuming the task is hung). * * @author Andrzej Bialecki */ public class Fetcher extends NutchTool implements Tool { public static final int PERM_REFRESH_TIME = 5; public static final String CONTENT_REDIR = "content"; public static final String PROTOCOL_REDIR = "protocol"; private static final Logger LOG = LoggerFactory .getLogger(MethodHandles.lookup().lookupClass()); public static class InputFormat extends SequenceFileInputFormat<Text, CrawlDatum> { /** * Don't split inputs to keep things polite - a single fetch list must be * processed in one fetcher task. Do not split a fetch lists and assigning * the splits to multiple parallel tasks. */ @Override public List<InputSplit> getSplits(JobContext job) throws IOException { List<FileStatus> files = listStatus(job); List<InputSplit> splits = new ArrayList<>(); for (FileStatus cur : files) { splits.add( new FileSplit(cur.getPath(), 0, cur.getLen(), (String[]) null)); } return splits; } } public Fetcher() { super(null); } public Fetcher(Configuration conf) { super(conf); } public static boolean isParsing(Configuration conf) { return conf.getBoolean("fetcher.parse", true); } public static boolean isStoringContent(Configuration conf) { return conf.getBoolean("fetcher.store.content", true); } public static class FetcherRun extends Mapper<Text, CrawlDatum, Text, NutchWritable> { private String segmentName; private AtomicInteger activeThreads = new AtomicInteger(0); private AtomicInteger spinWaiting = new AtomicInteger(0); private long start = System.currentTimeMillis(); private AtomicLong lastRequestStart = new AtomicLong(start); private AtomicLong bytes = new AtomicLong(0); // total bytes fetched private AtomicInteger pages = new AtomicInteger(0); // total pages fetched private AtomicInteger errors = new AtomicInteger(0); // total pages errored private boolean storingContent; private boolean parsing; private AtomicInteger getActiveThreads() { return activeThreads; } private void reportStatus(Context context, FetchItemQueues fetchQueues, int pagesLastSec, int bytesLastSec) throws IOException { StringBuilder status = new StringBuilder(); Long elapsed = Long.valueOf((System.currentTimeMillis() - start) / 1000); float avgPagesSec = (float) pages.get() / elapsed.floatValue(); long avgBytesSec = (bytes.get() / 128l) / elapsed.longValue(); status.append(activeThreads).append(" threads (").append(spinWaiting.get()) .append(" waiting), "); status.append(fetchQueues.getQueueCount()).append(" queues, "); status.append(fetchQueues.getTotalSize()).append(" URLs queued, "); status.append(pages).append(" pages, ").append(errors).append(" errors, "); status.append(String.format("%.2f", avgPagesSec)).append(" pages/s ("); status.append(pagesLastSec).append(" last sec), "); status.append(avgBytesSec).append(" kbits/s (") .append((bytesLastSec / 128)).append(" last sec)"); context.setStatus(status.toString()); } @Override public void setup(Mapper<Text, CrawlDatum, Text, NutchWritable>.Context context) { Configuration conf = context.getConfiguration(); segmentName = conf.get(Nutch.SEGMENT_NAME_KEY); storingContent = isStoringContent(conf); parsing = isParsing(conf); } @Override public void run(Context innerContext) throws IOException { setup(innerContext); Configuration conf = innerContext.getConfiguration(); LinkedList<FetcherThread> fetcherThreads = new LinkedList<>(); FetchItemQueues fetchQueues = new FetchItemQueues(conf); QueueFeeder feeder; int threadCount = conf.getInt("fetcher.threads.fetch", 10); if (LOG.isInfoEnabled()) { LOG.info("Fetcher: threads: {}", threadCount); } int timeoutDivisor = conf.getInt("fetcher.threads.timeout.divisor", 2); if (LOG.isInfoEnabled()) { LOG.info("Fetcher: time-out divisor: {}", timeoutDivisor); } int queueDepthMuliplier = conf.getInt( "fetcher.queue.depth.multiplier", 50); feeder = new QueueFeeder(innerContext, fetchQueues, threadCount * queueDepthMuliplier); // the value of the time limit is either -1 or the time where it should // finish long timelimit = conf.getLong("fetcher.timelimit", -1); if (timelimit != -1) feeder.setTimeLimit(timelimit); feeder.start(); for (int i = 0; i < threadCount; i++) { // spawn threads FetcherThread t = new FetcherThread(conf, getActiveThreads(), fetchQueues, feeder, spinWaiting, lastRequestStart, innerContext, errors, segmentName, parsing, storingContent, pages, bytes); fetcherThreads.add(t); t.start(); } // select a timeout that avoids a task timeout long timeout = conf.getInt("mapreduce.task.timeout", 10 * 60 * 1000) / timeoutDivisor; // Used for threshold check, holds pages and bytes processed in the last // second int pagesLastSec; int bytesLastSec; int throughputThresholdNumRetries = 0; int throughputThresholdPages = conf.getInt( "fetcher.throughput.threshold.pages", -1); if (LOG.isInfoEnabled()) { LOG.info("Fetcher: throughput threshold: {}", throughputThresholdPages); } int throughputThresholdMaxRetries = conf.getInt( "fetcher.throughput.threshold.retries", 5); if (LOG.isInfoEnabled()) { LOG.info("Fetcher: throughput threshold retries: {}", throughputThresholdMaxRetries); } long throughputThresholdTimeLimit = conf.getLong( "fetcher.throughput.threshold.check.after", -1); int targetBandwidth = conf.getInt("fetcher.bandwidth.target", -1) * 1000; int maxNumThreads = conf.getInt("fetcher.maxNum.threads", threadCount); if (maxNumThreads < threadCount) { LOG.info("fetcher.maxNum.threads can't be < than {} : using {} instead", threadCount, threadCount); maxNumThreads = threadCount; } int bandwidthTargetCheckEveryNSecs = conf.getInt( "fetcher.bandwidth.target.check.everyNSecs", 30); if (bandwidthTargetCheckEveryNSecs < 1) { LOG.info("fetcher.bandwidth.target.check.everyNSecs can't be < to 1 : using 1 instead"); bandwidthTargetCheckEveryNSecs = 1; } int maxThreadsPerQueue = conf.getInt("fetcher.threads.per.queue", 1); int bandwidthTargetCheckCounter = 0; long bytesAtLastBWTCheck = 0l; do { // wait for threads to exit pagesLastSec = pages.get(); bytesLastSec = (int) bytes.get(); try { Thread.sleep(1000); } catch (InterruptedException e) { } pagesLastSec = pages.get() - pagesLastSec; bytesLastSec = (int) bytes.get() - bytesLastSec; innerContext.getCounter("FetcherStatus", "bytes_downloaded").increment(bytesLastSec); reportStatus(innerContext, fetchQueues, pagesLastSec, bytesLastSec); LOG.info("-activeThreads=" + activeThreads + ", spinWaiting=" + spinWaiting.get() + ", fetchQueues.totalSize=" + fetchQueues.getTotalSize() + ", fetchQueues.getQueueCount=" + fetchQueues.getQueueCount()); if (!feeder.isAlive() && fetchQueues.getTotalSize() < 5) { fetchQueues.dump(); } // if throughput threshold is enabled if (throughputThresholdTimeLimit < System.currentTimeMillis() && throughputThresholdPages != -1) { // Check if we're dropping below the threshold if (pagesLastSec < throughputThresholdPages) { throughputThresholdNumRetries++; LOG.warn("{}: dropping below configured threshold of {} pages per second", Integer.toString(throughputThresholdNumRetries), Integer.toString(throughputThresholdPages)); // Quit if we dropped below threshold too many times if (throughputThresholdNumRetries == throughputThresholdMaxRetries) { LOG.warn("Dropped below threshold too many times, killing!"); // Disable the threshold checker throughputThresholdPages = -1; // Empty the queues cleanly and get number of items that were // dropped int hitByThrougputThreshold = fetchQueues.emptyQueues(); if (hitByThrougputThreshold != 0) innerContext.getCounter("FetcherStatus", "hitByThrougputThreshold").increment( hitByThrougputThreshold); } } } // adjust the number of threads if a target bandwidth has been set if (targetBandwidth > 0) { if (bandwidthTargetCheckCounter < bandwidthTargetCheckEveryNSecs) bandwidthTargetCheckCounter++; else if (bandwidthTargetCheckCounter == bandwidthTargetCheckEveryNSecs) { long bpsSinceLastCheck = ((bytes.get() - bytesAtLastBWTCheck) * 8) / bandwidthTargetCheckEveryNSecs; bytesAtLastBWTCheck = bytes.get(); bandwidthTargetCheckCounter = 0; int averageBdwPerThread = 0; if (activeThreads.get() > 0) averageBdwPerThread = Math.round(bpsSinceLastCheck / activeThreads.get()); LOG.info("averageBdwPerThread : {} kbps", (averageBdwPerThread / 1000)); if (bpsSinceLastCheck < targetBandwidth && averageBdwPerThread > 0) { // check whether it is worth doing e.g. more queues than threads if ((fetchQueues.getQueueCount() * maxThreadsPerQueue) > activeThreads .get()) { long remainingBdw = targetBandwidth - bpsSinceLastCheck; int additionalThreads = Math.round(remainingBdw / averageBdwPerThread); int availableThreads = maxNumThreads - activeThreads.get(); // determine the number of available threads (min between // availableThreads and additionalThreads) additionalThreads = (availableThreads < additionalThreads ? availableThreads : additionalThreads); LOG.info("Has space for more threads ({} vs {} kbps) \t=> adding {} new threads", new Object[]{(bpsSinceLastCheck / 1000), (targetBandwidth / 1000), additionalThreads}); // activate new threads for (int i = 0; i < additionalThreads; i++) { FetcherThread thread = new FetcherThread(conf, getActiveThreads(), fetchQueues, feeder, spinWaiting, lastRequestStart, innerContext, errors, segmentName, parsing, storingContent, pages, bytes); fetcherThreads.add(thread); thread.start(); } } } else if (bpsSinceLastCheck > targetBandwidth && averageBdwPerThread > 0) { // if the bandwidth we're using is greater then the expected // bandwidth, we have to stop some threads long excessBdw = bpsSinceLastCheck - targetBandwidth; int excessThreads = Math.round(excessBdw / averageBdwPerThread); LOG.info("Exceeding target bandwidth ({} vs {} kbps). \t=> excessThreads = {}", new Object[]{bpsSinceLastCheck / 1000, (targetBandwidth / 1000), excessThreads}); // keep at least one if (excessThreads >= fetcherThreads.size()) excessThreads = 0; // de-activates threads for (int i = 0; i < excessThreads; i++) { FetcherThread thread = fetcherThreads.removeLast(); thread.setHalted(true); } } } } // check timelimit if (!feeder.isAlive()) { int hitByTimeLimit = fetchQueues.checkTimelimit(); if (hitByTimeLimit != 0) innerContext.getCounter("FetcherStatus", "hitByTimeLimit").increment( hitByTimeLimit); } // some requests seem to hang, despite all intentions if ((System.currentTimeMillis() - lastRequestStart.get()) > timeout) { if (LOG.isWarnEnabled()) { LOG.warn("Aborting with {} hung threads.", activeThreads); for (int i = 0; i < fetcherThreads.size(); i++) { FetcherThread thread = fetcherThreads.get(i); if (thread.isAlive()) { LOG.warn("Thread #{} hung while processing {}", i, thread.getReprUrl()); if (LOG.isDebugEnabled()) { StackTraceElement[] stack = thread.getStackTrace(); StringBuilder sb = new StringBuilder(); sb.append("Stack of thread #").append(i).append(":\n"); for (StackTraceElement s : stack) { sb.append(s.toString()).append('\n'); } LOG.debug(sb.toString()); } } } } return; } } while (activeThreads.get() > 0); LOG.info("-activeThreads={}", activeThreads); } } public void fetch(Path segment, int threads) throws IOException, InterruptedException, ClassNotFoundException { checkConfiguration(); long start = System.currentTimeMillis(); if (LOG.isInfoEnabled()) { LOG.info("Fetcher: starting at {}", TimingUtil.logDateMillis(start)); LOG.info("Fetcher: segment: {}", segment); } // set the actual time for the timelimit relative // to the beginning of the whole job and not of a specific task // otherwise it keeps trying again if a task fails long timelimit = getConf().getLong("fetcher.timelimit.mins", -1); if (timelimit != -1) { timelimit = System.currentTimeMillis() + (timelimit * 60 * 1000); LOG.info("Fetcher Timelimit set for : {} ({})", timelimit, TimingUtil.logDateMillis(timelimit)); getConf().setLong("fetcher.timelimit", timelimit); } // Set the time limit after which the throughput threshold feature is // enabled timelimit = getConf().getLong("fetcher.throughput.threshold.check.after", 10); timelimit = System.currentTimeMillis() + (timelimit * 60 * 1000); getConf().setLong("fetcher.throughput.threshold.check.after", timelimit); int maxOutlinkDepth = getConf().getInt("fetcher.follow.outlinks.depth", -1); if (maxOutlinkDepth > 0) { LOG.info("Fetcher: following outlinks up to depth: {}", Integer.toString(maxOutlinkDepth)); int maxOutlinkDepthNumLinks = getConf().getInt( "fetcher.follow.outlinks.num.links", 4); int outlinksDepthDivisor = getConf().getInt( "fetcher.follow.outlinks.depth.divisor", 2); int totalOutlinksToFollow = 0; for (int i = 0; i < maxOutlinkDepth; i++) { totalOutlinksToFollow += (int) Math.floor(outlinksDepthDivisor / (i + 1) * maxOutlinkDepthNumLinks); } LOG.info("Fetcher: maximum outlinks to follow: {}", Integer.toString(totalOutlinksToFollow)); } Job job = NutchJob.getInstance(getConf()); job.setJobName("FetchData"); Configuration conf = job.getConfiguration(); conf.setInt("fetcher.threads.fetch", threads); conf.set(Nutch.SEGMENT_NAME_KEY, segment.getName()); // for politeness, don't permit parallel execution of a single task conf.set("mapreduce.map.speculative","false"); FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.GENERATE_DIR_NAME)); job.setInputFormatClass(InputFormat.class); job.setJarByClass(Fetcher.class); job.setMapperClass(Fetcher.FetcherRun.class); FileOutputFormat.setOutputPath(job, segment); job.setOutputFormatClass(FetcherOutputFormat.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(NutchWritable.class); try { boolean success = job.waitForCompletion(true); if (!success) { String message = "Fetcher job did not succeed, job status:" + job.getStatus().getState() + ", reason: " + job.getStatus().getFailureInfo(); LOG.error(message); throw new RuntimeException(message); } } catch (InterruptedException | ClassNotFoundException e) { LOG.error(StringUtils.stringifyException(e)); throw e; } long end = System.currentTimeMillis(); LOG.info("Fetcher: finished at {}, elapsed: {}", TimingUtil.logDateMillis(end), TimingUtil.elapsedTime(start, end)); } /** Run the fetcher. */ public static void main(String[] args) throws Exception { int res = ToolRunner.run(NutchConfiguration.create(), new Fetcher(), args); System.exit(res); } public int run(String[] args) throws Exception { String usage = "Usage: Fetcher <segment> [-threads n]"; if (args.length < 1) { System.err.println(usage); return -1; } Path segment = new Path(args[0]); int threads = getConf().getInt("fetcher.threads.fetch", 10); for (int i = 1; i < args.length; i++) { // parse command line if (args[i].equals("-threads")) { // found -threads option threads = Integer.parseInt(args[++i]); } } getConf().setInt("fetcher.threads.fetch", threads); try { fetch(segment, threads); return 0; } catch (Exception e) { LOG.error("Fetcher: {}", StringUtils.stringifyException(e)); return -1; } } private void checkConfiguration() { // ensure that a value has been set for the agent name String agentName = getConf().get("http.agent.name"); if (agentName == null || agentName.trim().length() == 0) { String message = "Fetcher: No agents listed in 'http.agent.name'" + " property."; if (LOG.isErrorEnabled()) { LOG.error(message); } throw new IllegalArgumentException(message); } } @Override public Map<String, Object> run(Map<String, Object> args, String crawlId) throws Exception { Map<String, Object> results = new HashMap<>(); Path segment = null; if(args.containsKey(Nutch.ARG_SEGMENTS)) { Object seg = args.get(Nutch.ARG_SEGMENTS); if(seg instanceof Path) { segment = (Path) seg; } else if(seg instanceof String){ segment = new Path(seg.toString()); } else if(seg instanceof ArrayList) { String[] segmentsArray = (String[])seg; segment = new Path(segmentsArray[0].toString()); if(segmentsArray.length > 1){ LOG.warn("Only the first segment of segments array is used."); } } } else { String segmentDir = crawlId+"/segments"; File segmentsDir = new File(segmentDir); File[] segmentsList = segmentsDir.listFiles(); Arrays.sort(segmentsList, (f1, f2) -> { if(f1.lastModified()>f2.lastModified()) return -1; else return 0; }); segment = new Path(segmentsList[0].getPath()); } int threads = getConf().getInt("fetcher.threads.fetch", 10); // parse command line if (args.containsKey("threads")) { // found -threads option threads = Integer.parseInt((String)args.get("threads")); } getConf().setInt("fetcher.threads.fetch", threads); try { fetch(segment, threads); results.put(Nutch.VAL_RESULT, Integer.toString(0)); return results; } catch (Exception e) { LOG.error("Fetcher: {}", StringUtils.stringifyException(e)); results.put(Nutch.VAL_RESULT, Integer.toString(-1)); return results; } } }
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { public static void main(String args[]) { Element[] elements = new Element[51]; testArraySetCheckCastNull(elements); System.out.println("passed"); } /// CHECK-START: void Main.testArraySetCheckCastNull(Main$Element[]) builder (after) /// CHECK: <<Array:l\d+>> ParameterValue /// CHECK-DAG: <<Index:i\d+>> IntConstant 42 /// CHECK-DAG: <<Null:l\d+>> NullConstant /// CHECK-DAG: <<Class:l\d+>> LoadClass /// CHECK-DAG: CheckCast [<<Null>>,<<Class>>] /// CHECK-DAG: <<CheckedValue:l\d+>> BoundType [<<Null>>] klass:Main$Element can_be_null:true /// CHECK-DAG: <<CheckedArray:l\d+>> NullCheck [<<Array>>] /// CHECK-DAG: <<Length:i\d+>> ArrayLength [<<CheckedArray>>] /// CHECK-DAG: <<CheckedIndex:i\d+>> BoundsCheck [<<Index>>,<<Length>>] /// CHECK-DAG: <<ArraySet:v\d+>> ArraySet [<<CheckedArray>>,<<CheckedIndex>>,<<CheckedValue>>] needs_type_check:true /// CHECK-START: void Main.testArraySetCheckCastNull(Main$Element[]) instruction_simplifier (after) /// CHECK-NOT: CheckCast /// CHECK-START: void Main.testArraySetCheckCastNull(Main$Element[]) prepare_for_register_allocation (before) /// CHECK: <<Array:l\d+>> ParameterValue /// CHECK-DAG: <<Index:i\d+>> IntConstant 42 /// CHECK-DAG: <<Null:l\d+>> NullConstant /// CHECK-DAG: <<Class:l\d+>> LoadClass /// CHECK-DAG: <<CheckedValue:l\d+>> BoundType [<<Null>>] /// CHECK-DAG: <<CheckedArray:l\d+>> NullCheck [<<Array>>] /// CHECK-DAG: <<Length:i\d+>> ArrayLength [<<CheckedArray>>] /// CHECK-DAG: <<CheckedIndex:i\d+>> BoundsCheck [<<Index>>,<<Length>>] /// CHECK-DAG: <<ArraySet:v\d+>> ArraySet [<<CheckedArray>>,<<CheckedIndex>>,<<CheckedValue>>] needs_type_check:true /// CHECK-START: void Main.testArraySetCheckCastNull(Main$Element[]) prepare_for_register_allocation (after) /// CHECK: <<Array:l\d+>> ParameterValue /// CHECK-DAG: <<Index:i\d+>> IntConstant 42 /// CHECK-DAG: <<Null:l\d+>> NullConstant /// CHECK-DAG: <<Class:l\d+>> LoadClass /// CHECK-DAG: <<Length:i\d+>> ArrayLength [<<Array>>] /// CHECK-DAG: <<ArraySet:v\d+>> ArraySet [<<Array>>,<<Index>>,<<Null>>] needs_type_check:false static void testArraySetCheckCastNull(Element[] elements) { Object object = null; Element element = (Element) object; elements[42] = element; } class Element {} }
package io.pivotal.davos; import java.time.LocalDate; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.Builder; import lombok.Getter; import lombok.ToString; @Builder @Getter @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "id", "type", "sourceId", "title", "details", "vendor", "cvssVector", "severity", "reporterAcknowledgement", "status", "urls", "cwe", "pendingDerivation", "discoveredDate", "publishedDate", "receivedDate" }) @ToString public class Notice { @JsonProperty("id") private Integer id; @JsonProperty("type") private String type; @JsonProperty("sourceId") private String sourceId; @JsonProperty("title") private String title; @JsonProperty("details") private String details; @JsonProperty("vendor") private String vendor; @JsonProperty("cvssVector") private String cvssVector; @JsonProperty("severity") private String severity; @JsonProperty("reporterAcknowledgement") private String reporterAcknowledgement; @JsonProperty("status") private String status; @JsonProperty("urls") private List<Url> urls; @JsonProperty("cwe") private String cwe; @JsonProperty("pendingDerivation") private boolean pendingDerivation; @JsonProperty("discoveredDate") private LocalDate discoveredDate; @JsonProperty("publishedDate") private LocalDate publishedDate; @JsonProperty("receivedDate") private LocalDate receivedDate; public Notice( @JsonProperty("id") Integer id, @JsonProperty("type") String type, @JsonProperty("sourceId")String sourceId, @JsonProperty("title") String title, @JsonProperty("details") String details, @JsonProperty("vendor") String vendor, @JsonProperty("cvssVector") String cvssVector, @JsonProperty("severity") String severity, @JsonProperty("reporterAcknowledgement") String reporterAcknowledgement, @JsonProperty("status") String status, @JsonProperty("urls") List<Url> urls, @JsonProperty("cwe") String cwe, @JsonProperty("pendingDerivation") boolean pendingDerivation, @JsonProperty("discoveredDate") LocalDate discoveredDate, @JsonProperty("publishedDate") LocalDate publishedDate, @JsonProperty("receivedDate") LocalDate receivedDate) { this.id = id; this.type = type; this.sourceId = sourceId; this.title = title; this.details = details; this.vendor = vendor; this.cvssVector = cvssVector; this.severity = severity; this.reporterAcknowledgement = reporterAcknowledgement; this.status = status; this.urls = urls; this.cwe = cwe; this.pendingDerivation = pendingDerivation; this.discoveredDate = discoveredDate; this.publishedDate = publishedDate; this.receivedDate = receivedDate; } }
package com.example.julioparedes.mapa; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.PolygonOptions; import java.lang.reflect.Array; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener, LocationListener { private GoogleMap mMap; //variable para el marcador de ubicacion actual private SimpleGeofence geo; Marker area, areaDos; private Marker marcador; Spinner Lugares; double lat; double lng; //aqui se almacenan los datos de los puntos del mapa // String[] veclatp = {"25.791176", "25.790967", "25.790629", "25.788927", "25.788743", "25.787977", "25.787977"}; //String[] veclonp = {"-109.003629", "-109.004978", "-109.004039", "-109.004199", "-109.005349", "-109.006323", "-109.007220"}; //String[] descripcionp = {"Jardín Xerofíto", "Jardín del Camino Dorado", "Jardín del Ying Yang", "Jardín Francés", "Estanque", "Plantario", "Área Recreativa"}; //String [] brevep={"Es la colección más reciente del jardín botánico. En ella se aprecian especies del semidesierto mexicano, representado por los estados del noroeste (Sinaloa, Sonora y Baja California).","Los olivos negros que custodian el sendero dan origen al nombre de camino dorado por las tonalidades de las hojas secas sobre el suelo que son tocadas por el sol, es posible que los primero olivos negros introducidos en Sinaloa hayan sido los del jardín de Johnston.","Una notable influencia oriental en su diseño es el distintivo principal de este espacio, sus curvos caminos resaltados son pasarelas por las que desfila especies tan peculiares como sorprendentes, el árbol flor de madera se llama así por sus frutos esférico secos que abren formando una flor.","Este espacio fue el jardín privado de la familia Johnston y sitio habitual de la convivencia entre sus invitados.","Es un cuerpo de agua rodeado por diversidad de árboles y palmeras, bajo las cuales se encuentra un camino adoquinado conectado por dos puentes, desde el cual se distingue una fuente colocada al frente.","Un espacio educativo y recreativo, a través del contacto con la naturaleza, conformado por una colección de mas de 100 especies tropicales, que explican su interacción en el ecosistema.","Costumbres y tradiciones generan la identidad de una región, por ello comprometidos por preservarlas trabajamos bajo tres objetivos principales en este recinto: difusión, educación y preservación de los diferentes elementos que conforma nuestra etnia yoreme-mayo."}; //String [] links={"http://jbbfj.org/v3/jardin-botanico/jardines/jardin-xerofito","http://jbbfj.org/v3/jardin-botanico/jardines/jardin-camino-dorado","http://jbbfj.org/v3/jardin-botanico/jardines/jardin-ying-yang","http://jbbfj.org/v3/jardin-botanico/jardines/jardin-frances","http://jbbfj.org/v3/jardin-botanico/mapa-jardin#estanque","http://jbbfj.org/v3/educacion/plantario","http://jbbfj.org/v3/educacion/recinto-educativo"}; //aqui se almacenan los datos de los puntos del mapa String[] veclat = {"23.2557316", "23.241388888889", "23.2115696", "23.2314459"}; String[] veclon = {"-106.459335", "-106.40972222222", "-106.4215502","-106.4265313"}; String[] descripcion = {"The Palms Resort", "El acuario", "Monumento al Pescador","UAS DE MAZATLÁN"}; String[] breve = {"Hotel en el cual nos encontramos ", "Acuario con un estanque de peces, especataculos en vivo conn animales marinos.", "El Monumento al Pescador es una obra realizada por el escultor Rodolfo Becerra Gómez que simbolizan todo aquello que estuviera en comunión directa con el mar.", "Escuela Evaluada por Iván Tostado"}; //String [] links={"http://jbbfj.org/v3/jardin-botanico/jardines/jardin-xerofito","http://jbbfj.org/v3/jardin-botanico/jardines/jardin-camino-dorado","http://jbbfj.org/v3/jardin-botanico/jardines/jardin-ying-yang","http://jbbfj.org/v3/jardin-botanico/jardines/jardin-frances","http://jbbfj.org/v3/jardin-botanico/mapa-jardin#estanque","http://jbbfj.org/v3/educacion/plantario","http://jbbfj.org/v3/educacion/recinto-educativo"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); Button cambiarUbicacionUno = (Button) findViewById(R.id.cambiarUbicacionUno); Button cambiarUbicacionDos = (Button) findViewById(R.id.cambiarUbicacionDos); //ArrayAdapter<CharSequence> adapter =ArrayAdapter.createFromResource(this,R.array.Lugares,android.R.layout.simple_spinner_item); //Lugares.setAdapter(adapter); LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) this); onLocationChanged(new Location(LocationManager.NETWORK_PROVIDER)); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); // cuando se hace click en el botton uno hte cambia tu ubicacion actual y entra al geocerca cambiarUbicacionUno.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(MapsActivity.this, "Geocerca área", Toast.LENGTH_LONG).show(); //lat=25.788884; //lng=-109.004274; actualMarcador(lat,lng); try { Thread.sleep(1000); // Do some stuff } catch (Exception e) { e.getLocalizedMessage(); } area.showInfoWindow(); } }); // cuando se hace click en el botton dos te cambia tu ubicacion actual y entra al geocerca // cambiarUbicacionDos.setOnClickListener( new View.OnClickListener() { // @Override //public void onClick(View v) { // finish(); // } // }); // Lugares.setOnItemClickListener(new AdapterView.OnItemClickListener() { // @Override // public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { //switch (i){ // case 1:{ //Intent ii=new Intent(view.getContext(),MainActivity.class); //ii.putExtra("lugar",i); //startActivity(ii); //break; //} //case 2:{ // Intent ii=new Intent(view.getContext(),MainActivity.class); // ii.putExtra("lugar",i); // startActivity(ii); // break; //} //case 3:{ // Intent ii=new Intent(view.getContext(),MainActivity.class); // ii.putExtra("lugar",i); //startActivity(ii); //break; //} //case 4:{ // Intent ii=new Intent(view.getContext(),MainActivity.class); // ii.putExtra("lugar",i); /// startActivity(ii); //break; //} //case 5:{ // Intent ii=new Intent(view.getContext(),MainActivity.class); // ii.putExtra("lugar",i); //startActivity(ii); //break; //} //} // } // }//); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; UiSettings uis=mMap.getUiSettings(); uis.setMyLocationButtonEnabled(true); // crear marcador de ubicaion actual actualMarcador(lat,lng); //agregar marcadores de lugares del parque for (int i = 0; i < veclat.length; i++) { agregarMarcador(i); } mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); mMap.setOnInfoWindowClickListener(this); } //en este metodo se agregan al mapa los marcadores de los lugares mas importantes y de los cuales similaremos el geocerca public void agregarMarcador(int id) { String texto = descripcion[id]; String desBreve = breve[id]; Double lati = Double.parseDouble(veclat[id]); Double longi = Double.parseDouble(veclon[id]); LatLng lugar = new LatLng(lati, longi); if (texto.equals("Jardín Francés")){ area = mMap.addMarker(new MarkerOptions().position(lugar) .title(texto).snippet(desBreve).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))); // mMap.moveCamera(CameraUpdateFactory.newLatLng(lugar)); geo = new SimpleGeofence(lati,longi,20,id ,texto); addMarkerForFence(geo); } else if (texto.equals("Jardín del Camino Dorado")){ areaDos = mMap.addMarker(new MarkerOptions().position(lugar) .title(texto).snippet(desBreve).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))); // mMap.moveCamera(CameraUpdateFactory.newLatLng(lugar)); geo = new SimpleGeofence(lati,longi,20,id ,texto); addMarkerForFence(geo); } else{ mMap.addMarker(new MarkerOptions().position(lugar) .title(texto).snippet(desBreve).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))); // mMap.moveCamera(CameraUpdateFactory.newLatLng(lugar)); geo = new SimpleGeofence(lati,longi,20,id ,texto); addMarkerForFence(geo); } } //metodo para mostrar marcador de ubicacion actual private void actualMarcador(double lat, double lng) { LatLng coordenadas = new LatLng(lat, lng); CameraUpdate miUbicacion = CameraUpdateFactory.newLatLngZoom(coordenadas, 16); if (marcador != null) marcador.remove(); { marcador = mMap.addMarker(new MarkerOptions().position(coordenadas).title("Ubicación Actual").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))); mMap.animateCamera(miUbicacion); } //Toast.makeText(MapsActivity.this, "dentro actualMarcador", Toast.LENGTH_LONG).show(); } //metodo para crear el geocerca con el circulo rojito public void addMarkerForFence(SimpleGeofence fence){ if(fence == null){ // display en error message and return return; } //Instantiates a new CircleOptions object + center/radius Circle circle = mMap.addCircle(new CircleOptions() .center(new LatLng(fence.getLatitude(), fence.getLongitude())) .radius(fence.getRadius()) .fillColor(0x40ff0000) .strokeColor(Color.TRANSPARENT)); // more operations on the circle... } //metodo para ir al link al hacer click en la ventana emergente @Override public void onInfoWindowClick(Marker marker) { //primero sacamos el id del marcador el cual es un string y le sacaremos el numero a ese string para saber la posicion del vector de los links que accederemos String idStr=""; int id; idStr=marker.getId(); id=Integer.parseInt(idStr.substring(idStr.length() - 1)); LugaresDialogFragment.newInstance(descripcion[id-1],breve[id-1]).show(getSupportFragmentManager(), null); //Toast.makeText(MapsActivity.this, "id: "+id, Toast.LENGTH_LONG).show(); //abre el navegador con el link del area //startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(links[id-1]))); } @Override public void onLocationChanged(Location location) { // Este mŽtodo se ejecuta cada vez que el GPS recibe nuevas coordenadas // debido a la detecci—n de un cambio de ubicacion lat=location.getLatitude(); lng=location.getLongitude(); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }
package com.meiyou.bigwhale.entity; import com.meiyou.bigwhale.common.Constant; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.Date; /** * @author Suxy * @date 2021/2/5 * @description file description */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "monitor") public class Monitor { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private Integer cycle; private Integer intervals; private Integer minute; private Integer hour; /** * 多条数据用,分割 */ private String week; private String cron; private Boolean exRestart; private Integer waitingBatches; private Boolean blockingRestart; private Boolean sendEmail; /** * 多条数据用,分割 */ private String dingdingHooks; private Boolean enabled; private Date realFireTime; public String generateCron() { if (cron != null) { return cron; } else { String cron = null; if (cycle == Constant.TIMER_CYCLE_MINUTE) { cron = "0 */" + intervals + " * * * ? *"; } else if (cycle == Constant.TIMER_CYCLE_HOUR) { cron = "0 " + minute + " * * * ? *"; } else if (cycle == Constant.TIMER_CYCLE_DAY) { cron = "0 " + minute + " " + hour + " * * ? *"; } else if (cycle == Constant.TIMER_CYCLE_WEEK) { cron = "0 " + minute + " " + hour + " ? * " + week + " *"; } if (cron == null) { throw new IllegalArgumentException("cron expression is incorrect"); } return cron; } } }
/* * Copyright 2016 tamas.csaba@gmail.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsplode.synapse.proxy.handlers; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageEncoder; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import java.util.HashSet; import java.util.List; import org.thingsplode.synapse.core.AbstractMessage; import org.thingsplode.synapse.core.Request; import org.thingsplode.synapse.proxy.RequestDecorator; import org.thingsplode.synapse.util.Util; /** * * @author Csaba Tamas */ @ChannelHandler.Sharable public class RequestEncoder extends MessageToMessageEncoder<Request> { private final HashSet<RequestDecorator> decorators; public RequestEncoder(HashSet<RequestDecorator> decorators, String hostExpression) { if (decorators != null) { this.decorators = decorators; } else { this.decorators = new HashSet<>(); } this.decorators.add((RequestDecorator) (Request request) -> { //basic data decorator request.getHeader().addProperty(HttpHeaderNames.HOST.toString(), hostExpression); request.getHeader().addProperty(HttpHeaderNames.ACCEPT_ENCODING.toString(), HttpHeaderValues.GZIP.toString()); request.getHeader().addProperty(HttpHeaderNames.ACCEPT.toString(), "*/*"); request.getHeader().addProperty(HttpHeaderNames.USER_AGENT.toString(), "synapse"); if (Util.notEmpty(request.getHeader().getMsgId())) { request.getHeader().addProperty(AbstractMessage.PROP_MESSAGE_ID, request.getHeader().getMsgId()); } }); } @Override protected void encode(ChannelHandlerContext ctx, Request msg, List<Object> out) throws Exception { decorate(msg); out.add(msg); } private void decorate(Request req) { decorators.forEach(d -> d.decorate(req)); } }
//$Id: $ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution statements * applied by the authors. * * All third-party contributions are distributed under license by Red Hat * Middleware LLC. This copyrighted material is made available to anyone * wishing to use, modify, copy, or redistribute it subject to the terms * and conditions of the GNU Lesser General Public License, as published by * the Free Software Foundation. This program is distributed in the hope * that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. You should * have received a copy of the GNU Lesser General Public License along with * this distribution; if not, write to: Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor Boston, MA 02110-1301 USA */ package org.hibernate.test.event.collection; /** * * @author Gail Badner */ public class ChildValue implements Child { private String name; public ChildValue() { } public ChildValue(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean equals(Object otherChild) { if ( this == otherChild ) { return true; } if ( !( otherChild instanceof ChildValue ) ) { return false; } return name.equals( ( ( ChildValue ) otherChild ).name ); } public int hashCode() { return name.hashCode(); } }
package com.bookstore.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; @Entity @PrimaryKeyJoinColumn(name="paperback_book_id") public class Paperback extends Book implements Serializable { private static final long serialVersionUID = 1L; private String sizeIn; private String weightLbs; public String getSizeIn() { return sizeIn; } public void setSizeIn(String sizeIn) { this.sizeIn = sizeIn; } public String getWeightLbs() { return weightLbs; } public void setWeightLbs(String weightLbs) { this.weightLbs = weightLbs; } @Override public String toString() { return super.toString() + ", Paperback{" + "sizeIn=" + sizeIn + ", weightLbs=" + weightLbs + '}'; } }
/** * Copyright 2006-2019 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements; import org.mybatis.generator.api.dom.xml.Attribute; import org.mybatis.generator.api.dom.xml.TextElement; import org.mybatis.generator.api.dom.xml.XmlElement; import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities; import static org.mybatis.generator.internal.util.StringUtility.stringHasValue; public class SelectByExampleWithoutBLOBsElementGenerator extends AbstractXmlElementGenerator { public SelectByExampleWithoutBLOBsElementGenerator() { super(); } @Override public void addElements(XmlElement parentElement) { String fqjt = introspectedTable.getExampleType(); XmlElement answer = new XmlElement("select"); answer.addAttribute(new Attribute("id", introspectedTable.getSelectByExampleStatementId())); answer.addAttribute(new Attribute( "resultMap", introspectedTable.getBaseResultMapId())); answer.addAttribute(new Attribute("parameterType", fqjt)); context.getCommentGenerator().addComment(answer); answer.addElement(new TextElement("select")); XmlElement ifElement = new XmlElement("if"); ifElement.addAttribute(new Attribute("test", "distinct")); //$NON-NLS-2$ ifElement.addElement(new TextElement("distinct")); answer.addElement(ifElement); StringBuilder sb = new StringBuilder(); if (stringHasValue(introspectedTable.getSelectByExampleQueryId())) { sb.append('\''); sb.append(introspectedTable.getSelectByExampleQueryId()); sb.append("' as QUERYID,"); answer.addElement(new TextElement(sb.toString())); } answer.addElement(getBaseColumnListElement()); sb.setLength(0); sb.append("from "); sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()); answer.addElement(new TextElement(sb.toString())); answer.addElement(getExampleIncludeElement()); if (!introspectedTable.getPrimaryKeyColumns().isEmpty()) { ifElement = new XmlElement("if"); ifElement.addAttribute(new Attribute("test", "pageId != null")); //$NON-NLS-2$ ifElement.addElement(new TextElement("and " + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedTable.getPrimaryKeyColumns().get(0)) + " <![CDATA[ < ]]> ${pageId}")); answer.addElement(ifElement); } ifElement = new XmlElement("if"); ifElement.addAttribute(new Attribute("test", "groupByClause != null")); //$NON-NLS-2$ ifElement.addElement(new TextElement("GROUP BY ${groupByClause}")); answer.addElement(ifElement); ifElement = new XmlElement("if"); ifElement.addAttribute(new Attribute("test", "orderByClause != null")); //$NON-NLS-2$ ifElement.addElement(new TextElement("order by ${orderByClause}")); answer.addElement(ifElement); XmlElement ifElement1 = new XmlElement("if"); ifElement1.addAttribute(new Attribute("test", "limit != null")); //$NON-NLS-2$ XmlElement ifElement2 = new XmlElement("if"); ifElement2.addAttribute(new Attribute("test", "offset != null")); //$NON-NLS-2$ ifElement2.addElement(new TextElement("limit ${offset}, ${limit}")); ifElement1.addElement(0, ifElement2); ifElement2 = new XmlElement("if"); ifElement2.addAttribute(new Attribute("test", "offset == null")); //$NON-NLS-2$ ifElement2.addElement(new TextElement("limit ${limit}")); ifElement1.addElement(1, ifElement2); answer.addElement(ifElement1); if (context.getPlugins() .sqlMapSelectByExampleWithoutBLOBsElementGenerated(answer, introspectedTable)) { parentElement.addElement(answer); } } }
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package scouter.bytebuddy.jar.asm.commons; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import scouter.bytebuddy.jar.asm.ClassVisitor; import scouter.bytebuddy.jar.asm.Handle; import scouter.bytebuddy.jar.asm.Label; import scouter.bytebuddy.jar.asm.MethodVisitor; import scouter.bytebuddy.jar.asm.Opcodes; import scouter.bytebuddy.jar.asm.Type; /** * A {@link MethodVisitor} with convenient methods to generate * code. For example, using this adapter, the class below * * <pre> * public class Example { * public static void main(String[] args) { * System.out.println(&quot;Hello world!&quot;); * } * } * </pre> * * can be generated as follows: * * <pre> * ClassWriter cw = new ClassWriter(true); * cw.visit(V1_1, ACC_PUBLIC, &quot;Example&quot;, null, &quot;java/lang/Object&quot;, null); * * Method m = Method.getMethod(&quot;void &lt;init&gt; ()&quot;); * GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cw); * mg.loadThis(); * mg.invokeConstructor(Type.getType(Object.class), m); * mg.returnValue(); * mg.endMethod(); * * m = Method.getMethod(&quot;void main (String[])&quot;); * mg = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw); * mg.getStatic(Type.getType(System.class), &quot;out&quot;, Type.getType(PrintStream.class)); * mg.push(&quot;Hello world!&quot;); * mg.invokeVirtual(Type.getType(PrintStream.class), * Method.getMethod(&quot;void println (String)&quot;)); * mg.returnValue(); * mg.endMethod(); * * cw.visitEnd(); * </pre> * * @author Juozas Baliuka * @author Chris Nokleberg * @author Eric Bruneton * @author Prashant Deva */ public class GeneratorAdapter extends LocalVariablesSorter { private static final String CLDESC = "Ljava/lang/Class;"; private static final Type BYTE_TYPE = Type.getObjectType("java/lang/Byte"); private static final Type BOOLEAN_TYPE = Type .getObjectType("java/lang/Boolean"); private static final Type SHORT_TYPE = Type .getObjectType("java/lang/Short"); private static final Type CHARACTER_TYPE = Type .getObjectType("java/lang/Character"); private static final Type INTEGER_TYPE = Type .getObjectType("java/lang/Integer"); private static final Type FLOAT_TYPE = Type .getObjectType("java/lang/Float"); private static final Type LONG_TYPE = Type.getObjectType("java/lang/Long"); private static final Type DOUBLE_TYPE = Type .getObjectType("java/lang/Double"); private static final Type NUMBER_TYPE = Type .getObjectType("java/lang/Number"); private static final Type OBJECT_TYPE = Type .getObjectType("java/lang/Object"); private static final Method BOOLEAN_VALUE = Method .getMethod("boolean booleanValue()"); private static final Method CHAR_VALUE = Method .getMethod("char charValue()"); private static final Method INT_VALUE = Method.getMethod("int intValue()"); private static final Method FLOAT_VALUE = Method .getMethod("float floatValue()"); private static final Method LONG_VALUE = Method .getMethod("long longValue()"); private static final Method DOUBLE_VALUE = Method .getMethod("double doubleValue()"); /** * Constant for the {@link #math math} method. */ public static final int ADD = Opcodes.IADD; /** * Constant for the {@link #math math} method. */ public static final int SUB = Opcodes.ISUB; /** * Constant for the {@link #math math} method. */ public static final int MUL = Opcodes.IMUL; /** * Constant for the {@link #math math} method. */ public static final int DIV = Opcodes.IDIV; /** * Constant for the {@link #math math} method. */ public static final int REM = Opcodes.IREM; /** * Constant for the {@link #math math} method. */ public static final int NEG = Opcodes.INEG; /** * Constant for the {@link #math math} method. */ public static final int SHL = Opcodes.ISHL; /** * Constant for the {@link #math math} method. */ public static final int SHR = Opcodes.ISHR; /** * Constant for the {@link #math math} method. */ public static final int USHR = Opcodes.IUSHR; /** * Constant for the {@link #math math} method. */ public static final int AND = Opcodes.IAND; /** * Constant for the {@link #math math} method. */ public static final int OR = Opcodes.IOR; /** * Constant for the {@link #math math} method. */ public static final int XOR = Opcodes.IXOR; /** * Constant for the {@link #ifCmp ifCmp} method. */ public static final int EQ = Opcodes.IFEQ; /** * Constant for the {@link #ifCmp ifCmp} method. */ public static final int NE = Opcodes.IFNE; /** * Constant for the {@link #ifCmp ifCmp} method. */ public static final int LT = Opcodes.IFLT; /** * Constant for the {@link #ifCmp ifCmp} method. */ public static final int GE = Opcodes.IFGE; /** * Constant for the {@link #ifCmp ifCmp} method. */ public static final int GT = Opcodes.IFGT; /** * Constant for the {@link #ifCmp ifCmp} method. */ public static final int LE = Opcodes.IFLE; /** * Access flags of the method visited by this adapter. */ private final int access; /** * Return type of the method visited by this adapter. */ private final Type returnType; /** * Argument types of the method visited by this adapter. */ private final Type[] argumentTypes; /** * Types of the local variables of the method visited by this adapter. */ private final List<Type> localTypes = new ArrayList<Type>(); /** * Creates a new {@link GeneratorAdapter}. <i>Subclasses must not use this * constructor</i>. Instead, they must use the * {@link #GeneratorAdapter(int, MethodVisitor, int, String, String)} * version. * * @param mv * the method visitor to which this adapter delegates calls. * @param access * the method's access flags (see {@link Opcodes}). * @param name * the method's name. * @param desc * the method's descriptor (see {@link Type Type}). * @throws IllegalStateException * If a subclass calls this constructor. */ public GeneratorAdapter(final MethodVisitor mv, final int access, final String name, final String desc) { this(Opcodes.ASM5, mv, access, name, desc); if (getClass() != GeneratorAdapter.class) { throw new IllegalStateException(); } } /** * Creates a new {@link GeneratorAdapter}. * * @param api * the ASM API version implemented by this visitor. Must be one * of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}. * @param mv * the method visitor to which this adapter delegates calls. * @param access * the method's access flags (see {@link Opcodes}). * @param name * the method's name. * @param desc * the method's descriptor (see {@link Type Type}). */ protected GeneratorAdapter(final int api, final MethodVisitor mv, final int access, final String name, final String desc) { super(api, access, desc, mv); this.access = access; this.returnType = Type.getReturnType(desc); this.argumentTypes = Type.getArgumentTypes(desc); } /** * Creates a new {@link GeneratorAdapter}. <i>Subclasses must not use this * constructor</i>. Instead, they must use the * {@link #GeneratorAdapter(int, MethodVisitor, int, String, String)} * version. * * @param access * access flags of the adapted method. * @param method * the adapted method. * @param mv * the method visitor to which this adapter delegates calls. */ public GeneratorAdapter(final int access, final Method method, final MethodVisitor mv) { this(mv, access, null, method.getDescriptor()); } /** * Creates a new {@link GeneratorAdapter}. <i>Subclasses must not use this * constructor</i>. Instead, they must use the * {@link #GeneratorAdapter(int, MethodVisitor, int, String, String)} * version. * * @param access * access flags of the adapted method. * @param method * the adapted method. * @param signature * the signature of the adapted method (may be <tt>null</tt>). * @param exceptions * the exceptions thrown by the adapted method (may be * <tt>null</tt>). * @param cv * the class visitor to which this adapter delegates calls. */ public GeneratorAdapter(final int access, final Method method, final String signature, final Type[] exceptions, final ClassVisitor cv) { this(access, method, cv .visitMethod(access, method.getName(), method.getDescriptor(), signature, getInternalNames(exceptions))); } /** * Returns the internal names of the given types. * * @param types * a set of types. * @return the internal names of the given types. */ private static String[] getInternalNames(final Type[] types) { if (types == null) { return null; } String[] names = new String[types.length]; for (int i = 0; i < names.length; ++i) { names[i] = types[i].getInternalName(); } return names; } // ------------------------------------------------------------------------ // Instructions to push constants on the stack // ------------------------------------------------------------------------ /** * Generates the instruction to push the given value on the stack. * * @param value * the value to be pushed on the stack. */ public void push(final boolean value) { push(value ? 1 : 0); } /** * Generates the instruction to push the given value on the stack. * * @param value * the value to be pushed on the stack. */ public void push(final int value) { if (value >= -1 && value <= 5) { mv.visitInsn(Opcodes.ICONST_0 + value); } else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { mv.visitIntInsn(Opcodes.BIPUSH, value); } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) { mv.visitIntInsn(Opcodes.SIPUSH, value); } else { mv.visitLdcInsn(value); } } /** * Generates the instruction to push the given value on the stack. * * @param value * the value to be pushed on the stack. */ public void push(final long value) { if (value == 0L || value == 1L) { mv.visitInsn(Opcodes.LCONST_0 + (int) value); } else { mv.visitLdcInsn(value); } } /** * Generates the instruction to push the given value on the stack. * * @param value * the value to be pushed on the stack. */ public void push(final float value) { int bits = Float.floatToIntBits(value); if (bits == 0L || bits == 0x3f800000 || bits == 0x40000000) { // 0..2 mv.visitInsn(Opcodes.FCONST_0 + (int) value); } else { mv.visitLdcInsn(value); } } /** * Generates the instruction to push the given value on the stack. * * @param value * the value to be pushed on the stack. */ public void push(final double value) { long bits = Double.doubleToLongBits(value); if (bits == 0L || bits == 0x3ff0000000000000L) { // +0.0d and 1.0d mv.visitInsn(Opcodes.DCONST_0 + (int) value); } else { mv.visitLdcInsn(value); } } /** * Generates the instruction to push the given value on the stack. * * @param value * the value to be pushed on the stack. May be <tt>null</tt>. */ public void push(final String value) { if (value == null) { mv.visitInsn(Opcodes.ACONST_NULL); } else { mv.visitLdcInsn(value); } } /** * Generates the instruction to push the given value on the stack. * * @param value * the value to be pushed on the stack. */ public void push(final Type value) { if (value == null) { mv.visitInsn(Opcodes.ACONST_NULL); } else { switch (value.getSort()) { case Type.BOOLEAN: mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", "TYPE", CLDESC); break; case Type.CHAR: mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Character", "TYPE", CLDESC); break; case Type.BYTE: mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Byte", "TYPE", CLDESC); break; case Type.SHORT: mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Short", "TYPE", CLDESC); break; case Type.INT: mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Integer", "TYPE", CLDESC); break; case Type.FLOAT: mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Float", "TYPE", CLDESC); break; case Type.LONG: mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Long", "TYPE", CLDESC); break; case Type.DOUBLE: mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Double", "TYPE", CLDESC); break; default: mv.visitLdcInsn(value); } } } /** * Generates the instruction to push a handle on the stack. * * @param handle * the handle to be pushed on the stack. */ public void push(final Handle handle) { mv.visitLdcInsn(handle); } // ------------------------------------------------------------------------ // Instructions to load and store method arguments // ------------------------------------------------------------------------ /** * Returns the index of the given method argument in the frame's local * variables array. * * @param arg * the index of a method argument. * @return the index of the given method argument in the frame's local * variables array. */ private int getArgIndex(final int arg) { int index = (access & Opcodes.ACC_STATIC) == 0 ? 1 : 0; for (int i = 0; i < arg; i++) { index += argumentTypes[i].getSize(); } return index; } /** * Generates the instruction to push a local variable on the stack. * * @param type * the type of the local variable to be loaded. * @param index * an index in the frame's local variables array. */ private void loadInsn(final Type type, final int index) { mv.visitVarInsn(type.getOpcode(Opcodes.ILOAD), index); } /** * Generates the instruction to store the top stack value in a local * variable. * * @param type * the type of the local variable to be stored. * @param index * an index in the frame's local variables array. */ private void storeInsn(final Type type, final int index) { mv.visitVarInsn(type.getOpcode(Opcodes.ISTORE), index); } /** * Generates the instruction to load 'this' on the stack. */ public void loadThis() { if ((access & Opcodes.ACC_STATIC) != 0) { throw new IllegalStateException( "no 'this' pointer within static method"); } mv.visitVarInsn(Opcodes.ALOAD, 0); } /** * Generates the instruction to load the given method argument on the stack. * * @param arg * the index of a method argument. */ public void loadArg(final int arg) { loadInsn(argumentTypes[arg], getArgIndex(arg)); } /** * Generates the instructions to load the given method arguments on the * stack. * * @param arg * the index of the first method argument to be loaded. * @param count * the number of method arguments to be loaded. */ public void loadArgs(final int arg, final int count) { int index = getArgIndex(arg); for (int i = 0; i < count; ++i) { Type t = argumentTypes[arg + i]; loadInsn(t, index); index += t.getSize(); } } /** * Generates the instructions to load all the method arguments on the stack. */ public void loadArgs() { loadArgs(0, argumentTypes.length); } /** * Generates the instructions to load all the method arguments on the stack, * as a single object array. */ public void loadArgArray() { push(argumentTypes.length); newArray(OBJECT_TYPE); for (int i = 0; i < argumentTypes.length; i++) { dup(); push(i); loadArg(i); box(argumentTypes[i]); arrayStore(OBJECT_TYPE); } } /** * Generates the instruction to store the top stack value in the given * method argument. * * @param arg * the index of a method argument. */ public void storeArg(final int arg) { storeInsn(argumentTypes[arg], getArgIndex(arg)); } // ------------------------------------------------------------------------ // Instructions to load and store local variables // ------------------------------------------------------------------------ /** * Returns the type of the given local variable. * * @param local * a local variable identifier, as returned by * {@link LocalVariablesSorter#newLocal(Type) newLocal()}. * @return the type of the given local variable. */ public Type getLocalType(final int local) { return localTypes.get(local - firstLocal); } @Override protected void setLocalType(final int local, final Type type) { int index = local - firstLocal; while (localTypes.size() < index + 1) { localTypes.add(null); } localTypes.set(index, type); } /** * Generates the instruction to load the given local variable on the stack. * * @param local * a local variable identifier, as returned by * {@link LocalVariablesSorter#newLocal(Type) newLocal()}. */ public void loadLocal(final int local) { loadInsn(getLocalType(local), local); } /** * Generates the instruction to load the given local variable on the stack. * * @param local * a local variable identifier, as returned by * {@link LocalVariablesSorter#newLocal(Type) newLocal()}. * @param type * the type of this local variable. */ public void loadLocal(final int local, final Type type) { setLocalType(local, type); loadInsn(type, local); } /** * Generates the instruction to store the top stack value in the given local * variable. * * @param local * a local variable identifier, as returned by * {@link LocalVariablesSorter#newLocal(Type) newLocal()}. */ public void storeLocal(final int local) { storeInsn(getLocalType(local), local); } /** * Generates the instruction to store the top stack value in the given local * variable. * * @param local * a local variable identifier, as returned by * {@link LocalVariablesSorter#newLocal(Type) newLocal()}. * @param type * the type of this local variable. */ public void storeLocal(final int local, final Type type) { setLocalType(local, type); storeInsn(type, local); } /** * Generates the instruction to load an element from an array. * * @param type * the type of the array element to be loaded. */ public void arrayLoad(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IALOAD)); } /** * Generates the instruction to store an element in an array. * * @param type * the type of the array element to be stored. */ public void arrayStore(final Type type) { mv.visitInsn(type.getOpcode(Opcodes.IASTORE)); } // ------------------------------------------------------------------------ // Instructions to manage the stack // ------------------------------------------------------------------------ /** * Generates a POP instruction. */ public void pop() { mv.visitInsn(Opcodes.POP); } /** * Generates a POP2 instruction. */ public void pop2() { mv.visitInsn(Opcodes.POP2); } /** * Generates a DUP instruction. */ public void dup() { mv.visitInsn(Opcodes.DUP); } /** * Generates a DUP2 instruction. */ public void dup2() { mv.visitInsn(Opcodes.DUP2); } /** * Generates a DUP_X1 instruction. */ public void dupX1() { mv.visitInsn(Opcodes.DUP_X1); } /** * Generates a DUP_X2 instruction. */ public void dupX2() { mv.visitInsn(Opcodes.DUP_X2); } /** * Generates a DUP2_X1 instruction. */ public void dup2X1() { mv.visitInsn(Opcodes.DUP2_X1); } /** * Generates a DUP2_X2 instruction. */ public void dup2X2() { mv.visitInsn(Opcodes.DUP2_X2); } /** * Generates a SWAP instruction. */ public void swap() { mv.visitInsn(Opcodes.SWAP); } /** * Generates the instructions to swap the top two stack values. * * @param prev * type of the top - 1 stack value. * @param type * type of the top stack value. */ public void swap(final Type prev, final Type type) { if (type.getSize() == 1) { if (prev.getSize() == 1) { swap(); // same as dupX1(), pop(); } else { dupX2(); pop(); } } else { if (prev.getSize() == 1) { dup2X1(); pop2(); } else { dup2X2(); pop2(); } } } // ------------------------------------------------------------------------ // Instructions to do mathematical and logical operations // ------------------------------------------------------------------------ /** * Generates the instruction to do the specified mathematical or logical * operation. * * @param op * a mathematical or logical operation. Must be one of ADD, SUB, * MUL, DIV, REM, NEG, SHL, SHR, USHR, AND, OR, XOR. * @param type * the type of the operand(s) for this operation. */ public void math(final int op, final Type type) { mv.visitInsn(type.getOpcode(op)); } /** * Generates the instructions to compute the bitwise negation of the top * stack value. */ public void not() { mv.visitInsn(Opcodes.ICONST_1); mv.visitInsn(Opcodes.IXOR); } /** * Generates the instruction to increment the given local variable. * * @param local * the local variable to be incremented. * @param amount * the amount by which the local variable must be incremented. */ public void iinc(final int local, final int amount) { mv.visitIincInsn(local, amount); } /** * Generates the instructions to cast a numerical value from one type to * another. * * @param from * the type of the top stack value * @param to * the type into which this value must be cast. */ public void cast(final Type from, final Type to) { if (from != to) { if (from == Type.DOUBLE_TYPE) { if (to == Type.FLOAT_TYPE) { mv.visitInsn(Opcodes.D2F); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Opcodes.D2L); } else { mv.visitInsn(Opcodes.D2I); cast(Type.INT_TYPE, to); } } else if (from == Type.FLOAT_TYPE) { if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Opcodes.F2D); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Opcodes.F2L); } else { mv.visitInsn(Opcodes.F2I); cast(Type.INT_TYPE, to); } } else if (from == Type.LONG_TYPE) { if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Opcodes.L2D); } else if (to == Type.FLOAT_TYPE) { mv.visitInsn(Opcodes.L2F); } else { mv.visitInsn(Opcodes.L2I); cast(Type.INT_TYPE, to); } } else { if (to == Type.BYTE_TYPE) { mv.visitInsn(Opcodes.I2B); } else if (to == Type.CHAR_TYPE) { mv.visitInsn(Opcodes.I2C); } else if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Opcodes.I2D); } else if (to == Type.FLOAT_TYPE) { mv.visitInsn(Opcodes.I2F); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Opcodes.I2L); } else if (to == Type.SHORT_TYPE) { mv.visitInsn(Opcodes.I2S); } } } } // ------------------------------------------------------------------------ // Instructions to do boxing and unboxing operations // ------------------------------------------------------------------------ private static Type getBoxedType(final Type type) { switch (type.getSort()) { case Type.BYTE: return BYTE_TYPE; case Type.BOOLEAN: return BOOLEAN_TYPE; case Type.SHORT: return SHORT_TYPE; case Type.CHAR: return CHARACTER_TYPE; case Type.INT: return INTEGER_TYPE; case Type.FLOAT: return FLOAT_TYPE; case Type.LONG: return LONG_TYPE; case Type.DOUBLE: return DOUBLE_TYPE; } return type; } /** * Generates the instructions to box the top stack value. This value is * replaced by its boxed equivalent on top of the stack. * * @param type * the type of the top stack value. */ public void box(final Type type) { if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) { return; } if (type == Type.VOID_TYPE) { push((String) null); } else { Type boxed = getBoxedType(type); newInstance(boxed); if (type.getSize() == 2) { // Pp -> Ppo -> oPpo -> ooPpo -> ooPp -> o dupX2(); dupX2(); pop(); } else { // p -> po -> opo -> oop -> o dupX1(); swap(); } invokeConstructor(boxed, new Method("<init>", Type.VOID_TYPE, new Type[] { type })); } } /** * Generates the instructions to box the top stack value using Java 5's * valueOf() method. This value is replaced by its boxed equivalent on top * of the stack. * * @param type * the type of the top stack value. */ public void valueOf(final Type type) { if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) { return; } if (type == Type.VOID_TYPE) { push((String) null); } else { Type boxed = getBoxedType(type); invokeStatic(boxed, new Method("valueOf", boxed, new Type[] { type })); } } /** * Generates the instructions to unbox the top stack value. This value is * replaced by its unboxed equivalent on top of the stack. * * @param type * the type of the top stack value. */ public void unbox(final Type type) { Type t = NUMBER_TYPE; Method sig = null; switch (type.getSort()) { case Type.VOID: return; case Type.CHAR: t = CHARACTER_TYPE; sig = CHAR_VALUE; break; case Type.BOOLEAN: t = BOOLEAN_TYPE; sig = BOOLEAN_VALUE; break; case Type.DOUBLE: sig = DOUBLE_VALUE; break; case Type.FLOAT: sig = FLOAT_VALUE; break; case Type.LONG: sig = LONG_VALUE; break; case Type.INT: case Type.SHORT: case Type.BYTE: sig = INT_VALUE; } if (sig == null) { checkCast(type); } else { checkCast(t); invokeVirtual(t, sig); } } // ------------------------------------------------------------------------ // Instructions to jump to other instructions // ------------------------------------------------------------------------ /** * Creates a new {@link Label}. * * @return a new {@link Label}. */ public Label newLabel() { return new Label(); } /** * Marks the current code position with the given label. * * @param label * a label. */ public void mark(final Label label) { mv.visitLabel(label); } /** * Marks the current code position with a new label. * * @return the label that was created to mark the current code position. */ public Label mark() { Label label = new Label(); mv.visitLabel(label); return label; } /** * Generates the instructions to jump to a label based on the comparison of * the top two stack values. * * @param type * the type of the top two stack values. * @param mode * how these values must be compared. One of EQ, NE, LT, GE, GT, * LE. * @param label * where to jump if the comparison result is <tt>true</tt>. */ public void ifCmp(final Type type, final int mode, final Label label) { switch (type.getSort()) { case Type.LONG: mv.visitInsn(Opcodes.LCMP); break; case Type.DOUBLE: mv.visitInsn(mode == GE || mode == GT ? Opcodes.DCMPL : Opcodes.DCMPG); break; case Type.FLOAT: mv.visitInsn(mode == GE || mode == GT ? Opcodes.FCMPL : Opcodes.FCMPG); break; case Type.ARRAY: case Type.OBJECT: switch (mode) { case EQ: mv.visitJumpInsn(Opcodes.IF_ACMPEQ, label); return; case NE: mv.visitJumpInsn(Opcodes.IF_ACMPNE, label); return; } throw new IllegalArgumentException("Bad comparison for type " + type); default: int intOp = -1; switch (mode) { case EQ: intOp = Opcodes.IF_ICMPEQ; break; case NE: intOp = Opcodes.IF_ICMPNE; break; case GE: intOp = Opcodes.IF_ICMPGE; break; case LT: intOp = Opcodes.IF_ICMPLT; break; case LE: intOp = Opcodes.IF_ICMPLE; break; case GT: intOp = Opcodes.IF_ICMPGT; break; } mv.visitJumpInsn(intOp, label); return; } mv.visitJumpInsn(mode, label); } /** * Generates the instructions to jump to a label based on the comparison of * the top two integer stack values. * * @param mode * how these values must be compared. One of EQ, NE, LT, GE, GT, * LE. * @param label * where to jump if the comparison result is <tt>true</tt>. */ public void ifICmp(final int mode, final Label label) { ifCmp(Type.INT_TYPE, mode, label); } /** * Generates the instructions to jump to a label based on the comparison of * the top integer stack value with zero. * * @param mode * how these values must be compared. One of EQ, NE, LT, GE, GT, * LE. * @param label * where to jump if the comparison result is <tt>true</tt>. */ public void ifZCmp(final int mode, final Label label) { mv.visitJumpInsn(mode, label); } /** * Generates the instruction to jump to the given label if the top stack * value is null. * * @param label * where to jump if the condition is <tt>true</tt>. */ public void ifNull(final Label label) { mv.visitJumpInsn(Opcodes.IFNULL, label); } /** * Generates the instruction to jump to the given label if the top stack * value is not null. * * @param label * where to jump if the condition is <tt>true</tt>. */ public void ifNonNull(final Label label) { mv.visitJumpInsn(Opcodes.IFNONNULL, label); } /** * Generates the instruction to jump to the given label. * * @param label * where to jump if the condition is <tt>true</tt>. */ public void goTo(final Label label) { mv.visitJumpInsn(Opcodes.GOTO, label); } /** * Generates a RET instruction. * * @param local * a local variable identifier, as returned by * {@link LocalVariablesSorter#newLocal(Type) newLocal()}. */ public void ret(final int local) { mv.visitVarInsn(Opcodes.RET, local); } /** * Generates the instructions for a switch statement. * * @param keys * the switch case keys. * @param generator * a generator to generate the code for the switch cases. */ public void tableSwitch(final int[] keys, final TableSwitchGenerator generator) { float density; if (keys.length == 0) { density = 0; } else { density = (float) keys.length / (keys[keys.length - 1] - keys[0] + 1); } tableSwitch(keys, generator, density >= 0.5f); } /** * Generates the instructions for a switch statement. * * @param keys * the switch case keys. * @param generator * a generator to generate the code for the switch cases. * @param useTable * <tt>true</tt> to use a TABLESWITCH instruction, or * <tt>false</tt> to use a LOOKUPSWITCH instruction. */ public void tableSwitch(final int[] keys, final TableSwitchGenerator generator, final boolean useTable) { for (int i = 1; i < keys.length; ++i) { if (keys[i] < keys[i - 1]) { throw new IllegalArgumentException( "keys must be sorted ascending"); } } Label def = newLabel(); Label end = newLabel(); if (keys.length > 0) { int len = keys.length; int min = keys[0]; int max = keys[len - 1]; int range = max - min + 1; if (useTable) { Label[] labels = new Label[range]; Arrays.fill(labels, def); for (int i = 0; i < len; ++i) { labels[keys[i] - min] = newLabel(); } mv.visitTableSwitchInsn(min, max, def, labels); for (int i = 0; i < range; ++i) { Label label = labels[i]; if (label != def) { mark(label); generator.generateCase(i + min, end); } } } else { Label[] labels = new Label[len]; for (int i = 0; i < len; ++i) { labels[i] = newLabel(); } mv.visitLookupSwitchInsn(def, keys, labels); for (int i = 0; i < len; ++i) { mark(labels[i]); generator.generateCase(keys[i], end); } } } mark(def); generator.generateDefault(); mark(end); } /** * Generates the instruction to return the top stack value to the caller. */ public void returnValue() { mv.visitInsn(returnType.getOpcode(Opcodes.IRETURN)); } // ------------------------------------------------------------------------ // Instructions to load and store fields // ------------------------------------------------------------------------ /** * Generates a get field or set field instruction. * * @param opcode * the instruction's opcode. * @param ownerType * the class in which the field is defined. * @param name * the name of the field. * @param fieldType * the type of the field. */ private void fieldInsn(final int opcode, final Type ownerType, final String name, final Type fieldType) { mv.visitFieldInsn(opcode, ownerType.getInternalName(), name, fieldType.getDescriptor()); } /** * Generates the instruction to push the value of a static field on the * stack. * * @param owner * the class in which the field is defined. * @param name * the name of the field. * @param type * the type of the field. */ public void getStatic(final Type owner, final String name, final Type type) { fieldInsn(Opcodes.GETSTATIC, owner, name, type); } /** * Generates the instruction to store the top stack value in a static field. * * @param owner * the class in which the field is defined. * @param name * the name of the field. * @param type * the type of the field. */ public void putStatic(final Type owner, final String name, final Type type) { fieldInsn(Opcodes.PUTSTATIC, owner, name, type); } /** * Generates the instruction to push the value of a non static field on the * stack. * * @param owner * the class in which the field is defined. * @param name * the name of the field. * @param type * the type of the field. */ public void getField(final Type owner, final String name, final Type type) { fieldInsn(Opcodes.GETFIELD, owner, name, type); } /** * Generates the instruction to store the top stack value in a non static * field. * * @param owner * the class in which the field is defined. * @param name * the name of the field. * @param type * the type of the field. */ public void putField(final Type owner, final String name, final Type type) { fieldInsn(Opcodes.PUTFIELD, owner, name, type); } // ------------------------------------------------------------------------ // Instructions to invoke methods // ------------------------------------------------------------------------ /** * Generates an invoke method instruction. * * @param opcode * the instruction's opcode. * @param type * the class in which the method is defined. * @param method * the method to be invoked. */ private void invokeInsn(final int opcode, final Type type, final Method method, final boolean itf) { String owner = type.getSort() == Type.ARRAY ? type.getDescriptor() : type.getInternalName(); mv.visitMethodInsn(opcode, owner, method.getName(), method.getDescriptor(), itf); } /** * Generates the instruction to invoke a normal method. * * @param owner * the class in which the method is defined. * @param method * the method to be invoked. */ public void invokeVirtual(final Type owner, final Method method) { invokeInsn(Opcodes.INVOKEVIRTUAL, owner, method, false); } /** * Generates the instruction to invoke a constructor. * * @param type * the class in which the constructor is defined. * @param method * the constructor to be invoked. */ public void invokeConstructor(final Type type, final Method method) { invokeInsn(Opcodes.INVOKESPECIAL, type, method, false); } /** * Generates the instruction to invoke a static method. * * @param owner * the class in which the method is defined. * @param method * the method to be invoked. */ public void invokeStatic(final Type owner, final Method method) { invokeInsn(Opcodes.INVOKESTATIC, owner, method, false); } /** * Generates the instruction to invoke an interface method. * * @param owner * the class in which the method is defined. * @param method * the method to be invoked. */ public void invokeInterface(final Type owner, final Method method) { invokeInsn(Opcodes.INVOKEINTERFACE, owner, method, true); } /** * Generates an invokedynamic instruction. * * @param name * the method's name. * @param desc * the method's descriptor (see {@link Type Type}). * @param bsm * the bootstrap method. * @param bsmArgs * the bootstrap method constant arguments. Each argument must be * an {@link Integer}, {@link Float}, {@link Long}, * {@link Double}, {@link String}, {@link Type} or {@link Handle} * value. This method is allowed to modify the content of the * array so a caller should expect that this array may change. */ public void invokeDynamic(String name, String desc, Handle bsm, Object... bsmArgs) { mv.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); } // ------------------------------------------------------------------------ // Instructions to create objects and arrays // ------------------------------------------------------------------------ /** * Generates a type dependent instruction. * * @param opcode * the instruction's opcode. * @param type * the instruction's operand. */ private void typeInsn(final int opcode, final Type type) { mv.visitTypeInsn(opcode, type.getInternalName()); } /** * Generates the instruction to create a new object. * * @param type * the class of the object to be created. */ public void newInstance(final Type type) { typeInsn(Opcodes.NEW, type); } /** * Generates the instruction to create a new array. * * @param type * the type of the array elements. */ public void newArray(final Type type) { int typ; switch (type.getSort()) { case Type.BOOLEAN: typ = Opcodes.T_BOOLEAN; break; case Type.CHAR: typ = Opcodes.T_CHAR; break; case Type.BYTE: typ = Opcodes.T_BYTE; break; case Type.SHORT: typ = Opcodes.T_SHORT; break; case Type.INT: typ = Opcodes.T_INT; break; case Type.FLOAT: typ = Opcodes.T_FLOAT; break; case Type.LONG: typ = Opcodes.T_LONG; break; case Type.DOUBLE: typ = Opcodes.T_DOUBLE; break; default: typeInsn(Opcodes.ANEWARRAY, type); return; } mv.visitIntInsn(Opcodes.NEWARRAY, typ); } // ------------------------------------------------------------------------ // Miscelaneous instructions // ------------------------------------------------------------------------ /** * Generates the instruction to compute the length of an array. */ public void arrayLength() { mv.visitInsn(Opcodes.ARRAYLENGTH); } /** * Generates the instruction to throw an exception. */ public void throwException() { mv.visitInsn(Opcodes.ATHROW); } /** * Generates the instructions to create and throw an exception. The * exception class must have a constructor with a single String argument. * * @param type * the class of the exception to be thrown. * @param msg * the detailed message of the exception. */ public void throwException(final Type type, final String msg) { newInstance(type); dup(); push(msg); invokeConstructor(type, Method.getMethod("void <init> (String)")); throwException(); } /** * Generates the instruction to check that the top stack value is of the * given type. * * @param type * a class or interface type. */ public void checkCast(final Type type) { if (!type.equals(OBJECT_TYPE)) { typeInsn(Opcodes.CHECKCAST, type); } } /** * Generates the instruction to test if the top stack value is of the given * type. * * @param type * a class or interface type. */ public void instanceOf(final Type type) { typeInsn(Opcodes.INSTANCEOF, type); } /** * Generates the instruction to get the monitor of the top stack value. */ public void monitorEnter() { mv.visitInsn(Opcodes.MONITORENTER); } /** * Generates the instruction to release the monitor of the top stack value. */ public void monitorExit() { mv.visitInsn(Opcodes.MONITOREXIT); } // ------------------------------------------------------------------------ // Non instructions // ------------------------------------------------------------------------ /** * Marks the end of the visited method. */ public void endMethod() { if ((access & Opcodes.ACC_ABSTRACT) == 0) { mv.visitMaxs(0, 0); } mv.visitEnd(); } /** * Marks the start of an exception handler. * * @param start * beginning of the exception handler's scope (inclusive). * @param end * end of the exception handler's scope (exclusive). * @param exception * internal name of the type of exceptions handled by the * handler. */ public void catchException(final Label start, final Label end, final Type exception) { Label doCatch = new Label(); if (exception == null) { mv.visitTryCatchBlock(start, end, doCatch, null); } else { mv.visitTryCatchBlock(start, end, doCatch, exception.getInternalName()); } mark(doCatch); } }
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ package org.unitime.timetable.onlinesectioning.status; import java.text.DateFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringEscapeUtils; import org.unitime.commons.hibernate.util.HibernateUtil; import org.unitime.localization.impl.Localization; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.gwt.resources.StudentSectioningConstants; import org.unitime.timetable.gwt.resources.StudentSectioningMessages; import org.unitime.timetable.gwt.server.DayCode; import org.unitime.timetable.gwt.server.Query; import org.unitime.timetable.gwt.server.Query.QueryFormatter; import org.unitime.timetable.gwt.shared.ClassAssignmentInterface; import org.unitime.timetable.gwt.shared.SectioningException; import org.unitime.timetable.gwt.shared.ClassAssignmentInterface.SectioningAction; import org.unitime.timetable.onlinesectioning.AcademicSessionInfo; import org.unitime.timetable.onlinesectioning.OnlineSectioningAction; import org.unitime.timetable.onlinesectioning.OnlineSectioningHelper; import org.unitime.timetable.onlinesectioning.OnlineSectioningLog; import org.unitime.timetable.onlinesectioning.OnlineSectioningServer; import org.unitime.timetable.onlinesectioning.model.XAreaClassificationMajor; import org.unitime.timetable.onlinesectioning.model.XStudent; import org.unitime.timetable.util.Constants; import com.google.protobuf.InvalidProtocolBufferException; /** * @author Tomas Muller */ public class FindOnlineSectioningLogAction implements OnlineSectioningAction<List<SectioningAction>> { private static final long serialVersionUID = 1L; protected static StudentSectioningMessages MSG = Localization.create(StudentSectioningMessages.class); protected static StudentSectioningConstants CONST = Localization.create(StudentSectioningConstants.class); private Query iQuery; private Integer iLimit = 100; public FindOnlineSectioningLogAction forQuery(String query) { iQuery = new Query(query.isEmpty() ? "limit:100" : query); Matcher m = Pattern.compile("limit:[ ]?([0-9]*)", Pattern.CASE_INSENSITIVE).matcher(query); if (m.find()) { iLimit = Integer.parseInt(m.group(1)); } return this; } public Query getQuery() { return iQuery; } public Integer getLimit() { return iLimit; } @Override public List<SectioningAction> execute(OnlineSectioningServer server, OnlineSectioningHelper helper) { helper.beginTransaction(); try { List<SectioningAction> ret = new ArrayList<SectioningAction>(); DateFormat df = Localization.getDateFormat(CONST.timeStampFormat()); NumberFormat nf = Localization.getNumberFormat(CONST.executionTimeFormat()); AcademicSessionInfo session = server.getAcademicSession(); org.hibernate.Query q = helper.getHibSession().createQuery( "select l, s.uniqueId from OnlineSectioningLog l, Student s " + (getQuery().hasAttribute("area", "clasf", "classification", "major") ? "left outer join s.areaClasfMajors m " : "") + (getQuery().hasAttribute("minor") ? "left outer join s.areaClasfMinors n " : "") + (getQuery().hasAttribute("group") ? "left outer join s.groups g " : "") + (getQuery().hasAttribute("accommodation") ? "left outer join s.accomodations a " : "") + (getQuery().hasAttribute("course") ? "left outer join s.courseDemands cd left outer join cd.courseRequests cr " : "") + "where l.session.uniqueId = :sessionId and l.session = s.session and l.student = s.externalUniqueId " + "and (" + getQuery().toString(new SectioningLogQueryFormatter()) + ") " + "and (l.result is not null or l.operation not in ('reload-offering', 'check-offering')) order by l.timeStamp desc, l.uniqueId desc"); q.setLong("sessionId", session.getUniqueId()); if (getLimit() != null) q.setMaxResults(getLimit()); for (Object[] o: (List<Object[]>)q.list()) { try { org.unitime.timetable.model.OnlineSectioningLog log = (org.unitime.timetable.model.OnlineSectioningLog)o[0]; XStudent student = server.getStudent((Long)o[1]); if (student == null) continue; ClassAssignmentInterface.Student st = new ClassAssignmentInterface.Student(); st.setId(student.getStudentId()); st.setSessionId(session.getUniqueId()); st.setExternalId(student.getExternalId()); st.setName(student.getName()); for (XAreaClassificationMajor acm: student.getMajors()) { st.addArea(acm.getArea()); st.addClassification(acm.getClassification()); st.addMajor(acm.getMajor()); } for (String acc: student.getAccomodations()) { st.addAccommodation(acc); } for (String gr: student.getGroups()) { st.addGroup(gr); } SectioningAction a = new SectioningAction(); a.setStudent(st); a.setTimeStamp(log.getTimeStamp()); a.setOperation(Constants.toInitialCase(log.getOperation().replace('-', ' '))); OnlineSectioningLog.Action action = OnlineSectioningLog.Action.parseFrom(log.getAction()); if (action.hasCpuTime()) a.setCpuTime(action.getCpuTime()); if (action.hasStartTime() && action.hasEndTime()) a.setWallTime(action.getEndTime() - action.getStartTime()); if (action.hasUser()) a.setUser(action.getUser().getName()); if (action.hasResult()) a.setResult(Constants.toInitialCase(action.getResult().name())); // a.setProto(action.toString().replace("<", "&lt;").replace(">", "&gt;").replace(" ", "&nbsp;").replace("\n", "<br>")); String html = "<table class='unitime-ChangeLog'>"; html += "<tr><td class='unitime-MainTableHeader' colspan='2'>General</td></tr>"; html += "<tr><td><b>" + MSG.colOperation() + ":</b></td><td>" + Constants.toInitialCase(log.getOperation().replace('-', ' ')) + "</td></tr>"; if (action.hasResult()) html += "<tr><td><b>" + MSG.colResult() + ":</b></td><td>" + Constants.toInitialCase(action.getResult().name()) + "</td></tr>"; if (action.hasStudent()) { XStudent s = server.getStudent(action.getStudent().getUniqueId()); if (s != null) { html += "<tr><td><b>" + MSG.colStudent() + ":</b></td><td>" + s.getName() + "</td></tr>"; } } for (OnlineSectioningLog.Entity other: action.getOtherList()) { html += "<tr><td><b>" + Constants.toInitialCase(other.getType().name()) + ":</b></td><td>" + other.getName() + "</td></tr>"; } html += "<tr><td><b>Time Stamp:</b></td><td>" + df.format(log.getTimeStamp()) + "</td></tr>"; for (OnlineSectioningLog.Property p: action.getOptionList()) { html += "<tr><td><b>" + Constants.toInitialCase(p.getKey()) + ":</b></td><td><div class='property'>" + (p.hasValue() ? p.getValue() : "") + "</div></td></tr>"; } if (action.hasCpuTime()) { html += "<tr><td><b>" + MSG.colCpuTime() + ":</b></td><td>" + nf.format(0.000000001 * action.getCpuTime()) + "</td></tr>"; } if (action.hasStartTime() && action.hasEndTime()) { html += "<tr><td nowrap><b>" + MSG.colWallTime() + ":</b></td><td>" + nf.format(0.001 * (action.getEndTime() - action.getStartTime())) + "</td></tr>"; } if (action.hasApiGetTime()) { html += "<tr><td nowrap><b>" + MSG.colApiGetTime() + ":</b></td><td>" + nf.format(0.001 * action.getApiGetTime()) + "</td></tr>"; } if (action.hasApiPostTime()) { html += "<tr><td nowrap><b>" + MSG.colApiPostTime() + ":</b></td><td>" + nf.format(0.001 * action.getApiPostTime()) + "</td></tr>"; } if (action.hasApiException()) { html += "<tr><td nowrap><b>" + MSG.colApiException() + ":</b></td><td>" + action.getApiException() + "</td></tr>"; } if (!action.getRequestList().isEmpty()) { html += "<tr><td class='unitime-MainTableHeader' colspan='2'>" + MSG.courseRequestsCourses() + "</td></tr>"; html += "<tr><td colspan='2'><table cellspacing='0' cellpadding='2'>" + "<td class='unitime-TableHeader'>" + MSG.colPriority() + "</td>" + "<td class='unitime-TableHeader'>" + MSG.colCourse() + "</td>" + "<td class='unitime-TableHeader'>" + MSG.colPreferences() + "</td></tr>"; } String request = ""; String selected = ""; int notAlt = 0, lastFT = -1; for (OnlineSectioningLog.Request r: action.getRequestList()) { if (!r.getAlternative()) notAlt = r.getPriority() + 1; int idx = 0; for (OnlineSectioningLog.Time f: r.getFreeTimeList()) { if (idx == 0) { html += (r.getPriority() > 0 && lastFT != r.getPriority() ? "<tr><td class='top-border-dashed'>" : "<tr><td>") + (lastFT == r.getPriority() ? "" : !r.getAlternative() ? MSG.courseRequestsPriority(1 + r.getPriority()) : MSG.courseRequestsAlternative(1 + r.getPriority() - notAlt)) + "</td>"; html += (r.getPriority() > 0 && lastFT != r.getPriority() ?"<td class='top-border-dashed' colspan='2'>":"<td colspan='2'>") + CONST.freePrefix() + " "; request += (lastFT == r.getPriority() ? ", " : (request.isEmpty() ? "" : "<br>") + (r.getAlternative() ? "A" + (1 + r.getPriority() - notAlt) : String.valueOf(1 + r.getPriority())) + ". " + CONST.freePrefix() + " "); } else { html += ", "; request += ", "; } idx++; html += DayCode.toString(f.getDays()) + " " + time(f.getStart()) + " - " + time(f.getStart() + f.getLength()); request += DayCode.toString(f.getDays()) + " " + time(f.getStart()) + " - " + time(f.getStart() + f.getLength()); html += "</td></tr>"; lastFT = r.getPriority(); } if (r.getFreeTimeList().isEmpty()) for (OnlineSectioningLog.Entity e: r.getCourseList()) { if (idx == 0) { html += (r.getPriority() > 0 ? "<tr><td class='top-border-dashed'>" : "<tr><td>") + (!r.getAlternative() ? MSG.courseRequestsPriority(1 + r.getPriority()) : MSG.courseRequestsAlternative(1 + r.getPriority() - notAlt)) + "</td>"; html += (r.getPriority() > 0 ?"<td class='top-border-dashed'>":"<td>"); request += (request.isEmpty() ? "" : "<br>") + (r.getAlternative() ? "A" + (1 + r.getPriority() - notAlt) : String.valueOf(1 + r.getPriority())) + ". "; } else { html += "<tr><td></td><td>"; request += ", "; } idx++; html += e.getName(); request += e.getName(); html += (r.getPriority() > 0 && idx == 1 ? "</td><td class='top-border-dashed'>" : "</td><td>" ); for (int i = 0; i < e.getParameterCount(); i++) html += (i > 0 ? ", " : "") + e.getParameter(i).getValue(); html += "</td></tr>"; } for (OnlineSectioningLog.Section s: r.getSectionList()) { if (s.getPreference() == OnlineSectioningLog.Section.Preference.SELECTED) { if (!selected.isEmpty()) selected += "<br>"; String loc = ""; for (OnlineSectioningLog.Entity e: s.getLocationList()) { if (!loc.isEmpty()) loc += ", "; loc += e.getName(); } String instr = ""; for (OnlineSectioningLog.Entity e: s.getInstructorList()) { if (!instr.isEmpty()) instr += ", "; instr += e.getName(); } selected += s.getCourse().getName() + " " + s.getSubpart().getName() + " " + s.getClazz().getName() + " " + (s.hasTime() ? DayCode.toString(s.getTime().getDays()) + " " + time(s.getTime().getStart()) + " - " + time(s.getTime().getStart() + s.getTime().getLength()) : "") + " " + loc; } } } if (!action.getRequestList().isEmpty()) { html += "</table></td></tr>"; } String enrollment = ""; Map<OnlineSectioningLog.Enrollment.EnrollmentType, String> enrollmentByType = new HashMap<OnlineSectioningLog.Enrollment.EnrollmentType, String>(); for (OnlineSectioningLog.Enrollment e: action.getEnrollmentList()) { enrollment = ""; html += "<tr><td class='unitime-MainTableHeader' colspan='2'>"+ (e.hasType() ? Constants.toInitialCase(e.getType().name()) + " ": "") + MSG.enrollmentsTable() + "</td></tr>"; html += "<tr><td colspan='2'><table cellspacing='0' cellpadding='2'>" + "<td class='unitime-TableHeader'>" + MSG.colCourse() + "</td>" + "<td class='unitime-TableHeader'>" + MSG.colSubject() + "</td>" + "<td class='unitime-TableHeader'>" + MSG.colClass() + "</td>" + "<td class='unitime-TableHeader'>" + MSG.colDays() + "</td>" + "<td class='unitime-TableHeader'>" + MSG.colStart() + "</td>" + "<td class='unitime-TableHeader'>" + MSG.colEnd() + "</td>" + "<td class='unitime-TableHeader'>" + MSG.colDate() + "</td>" + "<td class='unitime-TableHeader'>" + MSG.colRoom() + "</td>" + "<td class='unitime-TableHeader'>" + MSG.colInstructor() + "</td></tr>"; for (OnlineSectioningLog.Section s: e.getSectionList()) { if (!s.hasCourse()) continue; if (!enrollment.isEmpty()) enrollment += "<br>"; String loc = ""; for (OnlineSectioningLog.Entity r: s.getLocationList()) { if (!loc.isEmpty()) loc += ", "; loc += r.getName(); } String instr = ""; for (OnlineSectioningLog.Entity r: s.getInstructorList()) { if (!instr.isEmpty()) instr += ", "; instr += r.getName(); } html += "<tr>" + "<td>" + s.getCourse().getName() + "</td>" + "<td>" + s.getSubpart().getName() + "</td>" + "<td>" + s.getClazz().getName() + "</td>" + "<td>" + (s.hasTime() ? DayCode.toString(s.getTime().getDays()) : "") + "</td>" + "<td>" + (s.hasTime() ? time(s.getTime().getStart()) : "") + "</td>" + "<td>" + (s.hasTime() ? time(s.getTime().getStart() + s.getTime().getLength()) : "") + "</td>" + "<td>" + (s.hasTime() && s.getTime().hasPattern() ? s.getTime().getPattern() : "") + "</td>" + "<td>" + loc + "</td>" + "<td>" + instr + "</td>" + "</tr>"; enrollment += s.getCourse().getName() + " " + s.getSubpart().getName() + " " + s.getClazz().getName() + " " + (s.hasTime() ? DayCode.toString(s.getTime().getDays()) + " " + time(s.getTime().getStart()) : "") + " " + loc; } html += "</table></td></tr>"; enrollmentByType.put(e.getType(), enrollment); } String message = ""; if (!action.getMessageList().isEmpty()) { html += "<tr><td class='unitime-MainTableHeader' colspan='2'>" + MSG.tableMessages() + "</td></tr>"; for (OnlineSectioningLog.Message m: action.getMessageList()) { if (m.hasText()) { html += "<tr><td><b>" + m.getLevel().name() + ":</b></td><td>" + m.getText() + "</td></tr>"; message = m.getText(); } if (m.hasException()) { html += "<tr><td><b>Exception:</b></td><td>" + m.getException() + "</td></tr>"; message = m.getException(); } } } html += "<tr><td class='unitime-MainTableHeader' colspan='2'>" + MSG.tableProto() + "</td></tr>"; html += "<tr><td colspan='2' class='proto'>" + action.toString().replace("<", "&lt;").replace(">", "&gt;").replace(" ", "&nbsp;").replace("\n", "<br>") + "</td></tr>"; html += "</table>"; if ("student-email".equals(log.getOperation())) { for (OnlineSectioningLog.Property p: action.getOptionList()) if ("email".equals(p.getKey()) && p.hasValue()) html = p.getValue(); } if (action.hasResult() && OnlineSectioningLog.Action.ResultType.FAILURE.equals(action.getResult()) && !message.isEmpty()) { a.setMessage(message); } else if ("suggestions".equals(log.getOperation())) { a.setMessage(selected.isEmpty() ? message : selected); } else if ("section".equals(log.getOperation())) { a.setMessage(request.isEmpty() ? message : request); } else if (enrollmentByType.containsKey(OnlineSectioningLog.Enrollment.EnrollmentType.REQUESTED)) { a.setMessage(enrollmentByType.get(OnlineSectioningLog.Enrollment.EnrollmentType.REQUESTED)); } else { a.setMessage(enrollment.isEmpty() ? request.isEmpty() ? message : request : enrollment); } a.setProto(html); ret.add(a); } catch (InvalidProtocolBufferException e) {} } helper.commitTransaction(); return ret; } catch (Exception e) { helper.rollbackTransaction(); if (e instanceof SectioningException) throw (SectioningException)e; throw new SectioningException(MSG.exceptionUnknown(e.getMessage()), e); } } protected String time(int slot) { int h = slot / 12; int m = 5 * (slot % 12); if (CONST.useAmPm()) return (h > 12 ? h - 12 : h) + ":" + (m < 10 ? "0" : "") + m + (h == 24 ? "a" : h >= 12 ? "p" : "a"); else return h + ":" + (m < 10 ? "0" : "") + m; } public static class SectioningLogQueryFormatter implements QueryFormatter { @Override public String format(String attr, String body) { if (body != null && !body.isEmpty()) body = StringEscapeUtils.escapeSql(body); if ("id".equalsIgnoreCase(attr) || "student".equalsIgnoreCase(attr)) { if (ApplicationProperty.DataExchangeTrimLeadingZerosFromExternalIds.isTrue() && body.startsWith("0")) { return "s.externalUniqueId = '" + body.replaceFirst("^0+(?!$)", "") + "'"; } else { return "s.externalUniqueId = '" + body + "'"; } } else if ("operation".equalsIgnoreCase(attr) || "op".equalsIgnoreCase(attr)) { return "lower(l.operation) = '" + body.toLowerCase() + "'"; } else if ("max-age".equalsIgnoreCase(attr) || "age".equalsIgnoreCase(attr)) { return HibernateUtil.addDate("l.timeStamp", body) + " > current_date()"; } else if ("limit".equalsIgnoreCase(attr)) { return "1 = 1"; } else if ("area".equalsIgnoreCase(attr)) { return "lower(m.academicArea.academicAreaAbbreviation) = '" + body.toLowerCase() + "'"; } else if ("clasf".equalsIgnoreCase(attr) || "classification".equalsIgnoreCase(attr)) { return "lower(m.academicClassification.code) = '" + body.toLowerCase() + "'"; } else if ("major".equalsIgnoreCase(attr)) { return "lower(m.major.code) = '" + body.toLowerCase() + "'"; } else if ("minor".equalsIgnoreCase(attr)) { return "lower(n.minor.code) = '" + body.toLowerCase() + "'"; } else if ("group".equalsIgnoreCase(attr)) { return "lower(g.groupAbbreviation) = '" + body.toLowerCase() + "'"; } else if ("accommodation".equalsIgnoreCase(attr)) { return "lower(a.abbreviation) = '" + body.toLowerCase() + "'"; } else if ("user".equalsIgnoreCase(attr)) { return ("none".equalsIgnoreCase(body) ? "l.user is null" : "l.user = '" + body + "'"); } else if ("result".equalsIgnoreCase(attr)) { for (OnlineSectioningLog.Action.ResultType t: OnlineSectioningLog.Action.ResultType.values()) if (t.name().equalsIgnoreCase(body)) return "l.result = " + t.getNumber(); if ("none".equalsIgnoreCase(body) || "unknown".equalsIgnoreCase(body)) return "l.result is null"; else return "1 = 1"; } else if ("status".equalsIgnoreCase(attr)) { if ("Not Set".equalsIgnoreCase(body)) return "s.sectioningStatus is null"; else return "lower(s.sectioningStatus.reference) = '" + body.toLowerCase() + "'"; } else if ("over".equalsIgnoreCase(attr)) { try { return "l.wallTime >= " + 1000 * Integer.parseInt(body.trim()); } catch (Exception e) { return "1 = 1"; } } else if ("under".equalsIgnoreCase(attr)) { try { return "l.wallTime <= " + 1000 * Integer.parseInt(body.trim()); } catch (Exception e) { return "1 = 1"; } } else if ("api".equalsIgnoreCase(attr)) { try { return "l.apiGetTime >= " + 1000 * Integer.parseInt(body.trim()) + "or l.apiPostTime >= " + 1000 * Integer.parseInt(body.trim()) + " or (l.apiGetTime + l.apiPostTime) >= " + 1000 * Integer.parseInt(body.trim()); } catch (Exception e) { return "l.apiException like '%" + body + "%'"; } } else if ("message".equalsIgnoreCase(attr)) { return "l.message like '%" + body + "%' or l.apiException like '%" + body + "%'"; } else if ("get".equalsIgnoreCase(attr)) { try { return "l.apiGetTime >= " + 1000 * Integer.parseInt(body.trim()); } catch (Exception e) { return "1 = 1"; } } else if ("post".equalsIgnoreCase(attr)) { try { return "l.apiPostTime >= " + 1000 * Integer.parseInt(body.trim()); } catch (Exception e) { return "1 = 1"; } } else if ("course".equalsIgnoreCase(attr)) { return "cr.courseOffering.subjectAreaAbbv = '" + body + "' or (cr.courseOffering.subjectAreaAbbv || ' ' || cr.courseOffering.courseNbr) = '" + body + "'"; } else if (attr == null && !body.isEmpty()) { return "lower(s.firstName || ' ' || s.middleName || ' ' || s.lastName) like '%" + body.toLowerCase() + "%'"; } else { return "1 = 1"; } } } @Override public String name() { return "sectioning-log"; } }
package com.qulice.plugin.violations; import java.util.ArrayList; public class Violations { public void test() { System.setProperty("test", "test value"); } /** * Test method. * @todo #123 First * second */ public final void foreach() { for (String txt : new String[] {"test"}) { System.out.println(txt); } } /** * Missing final in catch. * @todo #123 First * second */ public final void catchFinal() { try { Integer.parseInt("123"); } catch (NumberFormatException ex) { throw new IllegalStateException(ex); } } /** * ArrayList without initializer. * @todo #123 Make this * a better text. */ public final void arrayLists() { System.out.println(new ArrayList<Integer>()); System.out.println(new java.util.ArrayList<Integer>()); System.out.println(new ArrayList<Integer>(1)); System.out.println(new java.util.ArrayList<Integer>(2)); } }
/* * * Copyright (c) 2020 Green Button Alliance, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 // See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.08.18 at 12:33:05 AM EDT // package org.greenbuttonalliance.espi.resourceserver.web.model.usage; import javax.xml.bind.annotation.*; /** * [extension] Represents a permission granted by an owner for access to a resource. * * Atom Links: * self link to this resource * rel corresponding ApplicationInformation (if this is the client access containing token instance) * rel corresponding to the authorized resource (if this is the access_token containing instance for a customer resource) * * Note: for privacy there is no identifier of the RetailCustomer in this structure but an implementation will have consider how to maintain a correspondence between a RetailCustomer and his authorization. * * <p>Java class for Authorization complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Authorization"&gt; * &lt;complexContent&gt; * &lt;extension base="{http://naesb.org/espi}IdentifiedObject"&gt; * &lt;sequence&gt; * &lt;element name="authorizedPeriod" type="{http://naesb.org/espi}DateTimeInterval" minOccurs="0"/&gt; * &lt;element name="publishedPeriod" type="{http://naesb.org/espi}DateTimeInterval" minOccurs="0"/&gt; * &lt;element name="status" type="{http://naesb.org/espi}AuthorizationStatus"/&gt; * &lt;element name="expires_at" type="{http://naesb.org/espi}TimeType"/&gt; * &lt;element name="grant_type" type="{http://naesb.org/espi}GrantType" minOccurs="0"/&gt; * &lt;element name="scope" type="{http://naesb.org/espi}String256"/&gt; * &lt;element name="token_type" type="{http://naesb.org/espi}TokenType"/&gt; * &lt;element name="error" type="{http://naesb.org/espi}OAuthError" minOccurs="0"/&gt; * &lt;element name="error_description" type="{http://naesb.org/espi}String256" minOccurs="0"/&gt; * &lt;element name="error_uri" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/&gt; * &lt;element name="resourceURI" type="{http://www.w3.org/2001/XMLSchema}anyURI"/&gt; * &lt;element name="authorizationURI" type="{http://www.w3.org/2001/XMLSchema}anyURI"/&gt; * &lt;element name="customerResourceURI" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Authorization", propOrder = { "authorizedPeriod", "publishedPeriod", "status", "expiresAt", "grantType", "scope", "tokenType", "error", "errorDescription", "errorUri", "resourceURI", "authorizationURI", "customerResourceURI" }) public class Authorization extends IdentifiedObject { protected DateTimeInterval authorizedPeriod; protected DateTimeInterval publishedPeriod; @XmlElement(required = true) protected String status; @XmlElement(name = "expires_at") protected long expiresAt; @XmlElement(name = "grant_type") @XmlSchemaType(name = "string") protected GrantType grantType; @XmlElement(required = true) protected String scope; @XmlElement(name = "token_type", required = true) @XmlSchemaType(name = "string") protected TokenType tokenType; @XmlSchemaType(name = "string") protected OAuthError error; @XmlElement(name = "error_description") protected String errorDescription; @XmlElement(name = "error_uri") @XmlSchemaType(name = "anyURI") protected String errorUri; @XmlElement(required = true) @XmlSchemaType(name = "anyURI") protected String resourceURI; @XmlElement(required = true) @XmlSchemaType(name = "anyURI") protected String authorizationURI; @XmlSchemaType(name = "anyURI") protected String customerResourceURI; /** * Gets the value of the authorizedPeriod property. * * @return * possible object is * {@link DateTimeInterval } * */ public DateTimeInterval getAuthorizedPeriod() { return authorizedPeriod; } /** * Sets the value of the authorizedPeriod property. * * @param value * allowed object is * {@link DateTimeInterval } * */ public void setAuthorizedPeriod(DateTimeInterval value) { this.authorizedPeriod = value; } /** * Gets the value of the publishedPeriod property. * * @return * possible object is * {@link DateTimeInterval } * */ public DateTimeInterval getPublishedPeriod() { return publishedPeriod; } /** * Sets the value of the publishedPeriod property. * * @param value * allowed object is * {@link DateTimeInterval } * */ public void setPublishedPeriod(DateTimeInterval value) { this.publishedPeriod = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link String } * */ public String getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link String } * */ public void setStatus(String value) { this.status = value; } /** * Gets the value of the expiresAt property. * */ public long getExpiresAt() { return expiresAt; } /** * Sets the value of the expiresAt property. * */ public void setExpiresAt(long value) { this.expiresAt = value; } /** * Gets the value of the grantType property. * * @return * possible object is * {@link GrantType } * */ public GrantType getGrantType() { return grantType; } /** * Sets the value of the grantType property. * * @param value * allowed object is * {@link GrantType } * */ public void setGrantType(GrantType value) { this.grantType = value; } /** * Gets the value of the scope property. * * @return * possible object is * {@link String } * */ public String getScope() { return scope; } /** * Sets the value of the scope property. * * @param value * allowed object is * {@link String } * */ public void setScope(String value) { this.scope = value; } /** * Gets the value of the tokenType property. * * @return * possible object is * {@link TokenType } * */ public TokenType getTokenType() { return tokenType; } /** * Sets the value of the tokenType property. * * @param value * allowed object is * {@link TokenType } * */ public void setTokenType(TokenType value) { this.tokenType = value; } /** * Gets the value of the error property. * * @return * possible object is * {@link OAuthError } * */ public OAuthError getError() { return error; } /** * Sets the value of the error property. * * @param value * allowed object is * {@link OAuthError } * */ public void setError(OAuthError value) { this.error = value; } /** * Gets the value of the errorDescription property. * * @return * possible object is * {@link String } * */ public String getErrorDescription() { return errorDescription; } /** * Sets the value of the errorDescription property. * * @param value * allowed object is * {@link String } * */ public void setErrorDescription(String value) { this.errorDescription = value; } /** * Gets the value of the errorUri property. * * @return * possible object is * {@link String } * */ public String getErrorUri() { return errorUri; } /** * Sets the value of the errorUri property. * * @param value * allowed object is * {@link String } * */ public void setErrorUri(String value) { this.errorUri = value; } /** * Gets the value of the resourceURI property. * * @return * possible object is * {@link String } * */ public String getResourceURI() { return resourceURI; } /** * Sets the value of the resourceURI property. * * @param value * allowed object is * {@link String } * */ public void setResourceURI(String value) { this.resourceURI = value; } /** * Gets the value of the authorizationURI property. * * @return * possible object is * {@link String } * */ public String getAuthorizationURI() { return authorizationURI; } /** * Sets the value of the authorizationURI property. * * @param value * allowed object is * {@link String } * */ public void setAuthorizationURI(String value) { this.authorizationURI = value; } /** * Gets the value of the customerResourceURI property. * * @return * possible object is * {@link String } * */ public String getCustomerResourceURI() { return customerResourceURI; } /** * Sets the value of the customerResourceURI property. * * @param value * allowed object is * {@link String } * */ public void setCustomerResourceURI(String value) { this.customerResourceURI = value; } }
//,temp,AhcProducer.java,122,132,temp,TelegramServiceRestBotAPIAdapter.java,457,466 //,3 public class xxx { @Override public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception { // write body parts to stream, which we will bind to the Camel Exchange in onComplete os.write(bodyPart.getBodyPartBytes()); if (LOG.isTraceEnabled()) { LOG.trace("{} onBodyPartReceived {} bytes", exchange.getExchangeId(), bodyPart.length()); } contentLength += bodyPart.length(); return State.CONTINUE; } };
package com.icepoint.framework.workorder.work.entity; import com.icepoint.framework.web.system.entity.FieldMetadata; import lombok.*; import lombok.experimental.SuperBuilder; import javax.persistence.Entity; /** * @author Juyss * @version 1.0 * @ClassName FieldMetadataWithObject * @description * @since 2021-07-20 16:14 */ @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor public class FieldMetadataWithObject extends FieldMetadata { private Object uiTypeObject; }
/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ /* * Copyright (C) 2004, * * Arjuna Technologies Ltd, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: RecoveryManagerTest.java 2342 2006-03-30 13:06:17Z $ */ package com.hp.mwtests.ts.jta.recovery; import org.junit.Test; import com.arjuna.ats.arjuna.common.recoveryPropertyManager; import com.arjuna.ats.arjuna.recovery.RecoveryManager; public class RecoveryManagerTest { @Test public void test() { recoveryPropertyManager.getRecoveryEnvironmentBean().setRecoveryBackoffPeriod(1); System.setProperty("com.arjuna.ats.jta.xaRecoveryNode", "1"); System.setProperty("XAResourceRecovery1", "com.hp.mwtests.ts.jta.recovery.DummyXARecoveryResource"); RecoveryManager manager = RecoveryManager.manager(RecoveryManager.DIRECT_MANAGEMENT); manager.scan(); manager.scan(); System.clearProperty("com.arjuna.ats.jta.xaRecoveryNode"); System.clearProperty("XAResourceRecovery1"); } }
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.gwtproject.i18n.shared.cldr.impl; // DO NOT EDIT - GENERATED FROM CLDR AND ICU DATA /** * Implementation of DateTimeFormatInfo for the "vai_Vaii_LR" locale. */ import org.gwtproject.i18n.shared.cldr.DateTimeFormatInfoImpl; public class DateTimeFormatInfoImpl_vai_Vaii_LR extends DateTimeFormatInfoImpl_vai_Vaii { @Override public String[] ampms() { return new String[] { "AM", "PM" }; } @Override public String dateFormat() { return dateFormatMedium(); } @Override public String dateFormatFull() { return "EEEE, d MMMM y"; } @Override public String dateFormatLong() { return "d MMMM y"; } @Override public String dateFormatMedium() { return "d MMM y"; } @Override public String dateFormatShort() { return "dd/MM/y"; } @Override public String dateTime(String timePattern, String datePattern) { return dateTimeMedium(timePattern, datePattern); } @Override public String dateTimeFull(String timePattern, String datePattern) { return datePattern + " " + timePattern; } @Override public String dateTimeLong(String timePattern, String datePattern) { return datePattern + " " + timePattern; } @Override public String dateTimeMedium(String timePattern, String datePattern) { return datePattern + " " + timePattern; } @Override public String dateTimeShort(String timePattern, String datePattern) { return datePattern + " " + timePattern; } @Override public String[] erasFull() { return new String[] { "BCE", "CE" }; } @Override public String[] erasShort() { return new String[] { "BCE", "CE" }; } @Override public int firstDayOfTheWeek() { return 1; } @Override public String formatDay() { return "d"; } @Override public String formatHour12Minute() { return "h:mm a"; } @Override public String formatHour12MinuteSecond() { return "h:mm:ss a"; } @Override public String formatHour24Minute() { return "HH:mm"; } @Override public String formatHour24MinuteSecond() { return "HH:mm:ss"; } @Override public String formatMinuteSecond() { return "mm:ss"; } @Override public String formatMonthAbbrev() { return "LLL"; } @Override public String formatMonthAbbrevDay() { return "MMM d"; } @Override public String formatMonthFull() { return "LLLL"; } @Override public String formatMonthFullDay() { return "MMMM d"; } @Override public String formatMonthFullWeekdayDay() { return "EEEE, MMMM d"; } @Override public String formatMonthNumDay() { return "M/d"; } @Override public String formatYear() { return "y"; } @Override public String formatYearMonthAbbrev() { return "MMM y"; } @Override public String formatYearMonthAbbrevDay() { return "d MMM y"; } @Override public String formatYearMonthFull() { return "MMMM y"; } @Override public String formatYearMonthFullDay() { return "d MMMM y"; } @Override public String formatYearMonthNum() { return "M/y"; } @Override public String formatYearMonthNumDay() { return "d/M/y"; } @Override public String formatYearMonthWeekdayDay() { return "EEE, MMM d, y"; } @Override public String formatYearQuarterFull() { return "QQQQ y"; } @Override public String formatYearQuarterShort() { return "Q y"; } @Override public String[] monthsFull() { return new String[] { "ꖨꖕ ꕪꕴ ꔞꔀꕮꕊ", "ꕒꕡꖝꖕ", "ꕾꖺ", "ꖢꖕ", "ꖑꕱ", "ꖱꘋ", "ꖱꕞꔤ", "ꗛꔕ", "ꕢꕌ", "ꕭꖃ", "ꔞꘋꕔꕿ ꕸꖃꗏ", "ꖨꖕ ꕪꕴ ꗏꖺꕮꕊ" }; } @Override public String[] monthsFullStandalone() { return monthsFull(); } @Override public String[] monthsNarrow() { return new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }; } @Override public String[] monthsNarrowStandalone() { return monthsNarrow(); } @Override public String[] monthsShort() { return new String[] { "ꖨꖕꔞ", "ꕒꕡ", "ꕾꖺ", "ꖢꖕ", "ꖑꕱ", "ꖱꘋ", "ꖱꕞ", "ꗛꔕ", "ꕢꕌ", "ꕭꖃ", "ꔞꘋ", "ꖨꖕꗏ" }; } @Override public String[] monthsShortStandalone() { return monthsShort(); } @Override public String[] quartersFull() { return new String[] { "Q1", "Q2", "Q3", "Q4" }; } @Override public String[] quartersShort() { return new String[] { "Q1", "Q2", "Q3", "Q4" }; } @Override public String timeFormat() { return timeFormatMedium(); } @Override public String timeFormatFull() { return "h:mm:ss a zzzz"; } @Override public String timeFormatLong() { return "h:mm:ss a z"; } @Override public String timeFormatMedium() { return "h:mm:ss a"; } @Override public String timeFormatShort() { return "h:mm a"; } @Override public String[] weekdaysFull() { return new String[] { "ꕞꕌꔵ", "ꗳꗡꘉ", "ꕚꕞꕚ", "ꕉꕞꕒ", "ꕉꔤꕆꕢ", "ꕉꔤꕀꕮ", "ꔻꔬꔳ" }; } @Override public String[] weekdaysFullStandalone() { return weekdaysFull(); } @Override public String[] weekdaysNarrow() { return new String[] { "S", "M", "T", "W", "T", "F", "S" }; } @Override public String[] weekdaysNarrowStandalone() { return weekdaysNarrow(); } @Override public String[] weekdaysShort() { return new String[] { "ꕞꕌꔵ", "ꗳꗡꘉ", "ꕚꕞꕚ", "ꕉꕞꕒ", "ꕉꔤꕆꕢ", "ꕉꔤꕀꕮ", "ꔻꔬꔳ" }; } @Override public String[] weekdaysShortStandalone() { return weekdaysShort(); } @Override public int weekendEnd() { return 0; } @Override public int weekendStart() { return 6; } }
package be.pxl.vraag1; /* Daan Vankerkom 1 TIN J */ public final class Landmijn extends WereldObject { public final static int MINSCHADE = 10; public final static int MAXSCHADE = 100; private int schade; private boolean actief; public Landmijn(int schade) { if (schade < MINSCHADE) { this.schade = MINSCHADE; } else if (schade > MAXSCHADE) { this.schade = MAXSCHADE; } else { this.schade = schade; } this.actief = true; } public int getSchade() { return schade; } public boolean isActief() { return actief; } public void ontplof() { actief = false; } @Override public String toString() { if (actief) { return "Actieve landmijn " + schade + " schade"; }else{ return "Ontplofte landmijn"; } } }
package com.thebund1st.tiantong.wechatpay; public final class WeChatPayTradeStates { public static final String SUCCESS = "SUCCESS"; public static final String NOT_PAY = "NOT_PAY"; public static final String CLOSED = "CLOSED"; }
package com.example.coolweather; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.preference.PreferenceManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.coolweather.gson.Forecast; import com.example.coolweather.gson.Weather; import com.example.coolweather.service.AutoUpdateService; import com.example.coolweather.util.HttpUtil; import com.example.coolweather.util.Utility; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class WeatherActivity extends AppCompatActivity { public DrawerLayout drawerLayout; private Button navButton; public SwipeRefreshLayout swipeRefresh; private String mWeatherId; private ScrollView weatherLayout; private TextView titleCity; private TextView titleUpdateTime; private TextView degreeText; private TextView weatherInfoText; private LinearLayout forecastLayout; private TextView aqiText; private TextView pm25Text; private TextView comfortText; private TextView carWashText; private TextView sportText; private ImageView bingPicImg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21) { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow().setStatusBarColor(Color.TRANSPARENT); } setContentView(R.layout.activity_weather); //初始化各控件 bingPicImg = (ImageView) findViewById(R.id.bing_pic_img); weatherLayout = (ScrollView) findViewById(R.id.weather_layout); titleCity = (TextView) findViewById(R.id.title_city); titleUpdateTime = (TextView) findViewById(R.id.title_update_time); degreeText = (TextView) findViewById(R.id.degree_text); weatherInfoText = (TextView) findViewById(R.id.weather_info_text); forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); navButton = (Button) findViewById(R.id.nav_button); aqiText = (TextView) findViewById(R.id.aqi_text); pm25Text = (TextView) findViewById(R.id.pm25_text); comfortText = (TextView) findViewById(R.id.comfort_text); carWashText = (TextView) findViewById(R.id.car_wash_text); sportText = (TextView) findViewById(R.id.sport_text); swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh); swipeRefresh.setColorSchemeResources(R.color.colorPrimary); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherString = prefs.getString("weather", null); String bingPic = prefs.getString("bing_pic", null); navButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawerLayout.openDrawer(GravityCompat.START); } }); if (bingPic != null) { Glide.with(this).load(bingPic).into(bingPicImg); } else { loadBingPic(); } if (weatherString != null) { //有缓存时直接解析天气数据 Weather weather = Utility.handleWeatherResponse(weatherString); mWeatherId = weather.basic.weatherId; showWeatherInfo(weather); } else { //无缓存时去服务器查询天气 String mWeatherId = getIntent().getStringExtra("weather_id"); weatherLayout.setVisibility(View.INVISIBLE); requestWeather(mWeatherId); } swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { requestWeather(mWeatherId); } }); loadBingPic(); } /** * 加载必应每日一图 */ private void loadBingPic() { String requestBingPic = "http://guolin.tech/api/bing_pic"; HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { final String bingPic = response.body().string(); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit(); editor.putString("bing_pic", bingPic); editor.apply(); runOnUiThread(new Runnable() { @Override public void run() { Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg); } }); } }); } /** * 根据天气id请求城市天气信息 * @param weatherId */ public void requestWeather(final String weatherId) { String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=66748a2404c947a0b2a0244ddf541087"; HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show(); swipeRefresh.setRefreshing(false); } }); } @Override public void onResponse(Call call, Response response) throws IOException { final String responseText = response.body().string(); final Weather weather = Utility.handleWeatherResponse(responseText); runOnUiThread(new Runnable() { @Override public void run() { if (weather != null && "ok".equals(weather.status)) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit(); editor.putString("weather", responseText); editor.apply(); showWeatherInfo(weather); } else { Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show(); } swipeRefresh.setRefreshing(false); } }); } }); } /** * 处理并展示Weather实体类中的数据 * @param weather */ private void showWeatherInfo(Weather weather) { if (weather != null && "ok".equals(weather.status)) { String cityName = weather.basic.cityName; String updateTime = weather.basic.update.updateTime.split(" ")[1]; String degree = weather.now.temperature + "℃"; String weatherInfo = weather.now.more.info; titleCity.setText(cityName); titleUpdateTime.setText(updateTime); degreeText.setText(degree); weatherInfoText.setText(weatherInfo); forecastLayout.removeAllViews(); for (Forecast forecast : weather.forecastList) { View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false); TextView dateText = (TextView) view.findViewById(R.id.date_text); TextView infoText = (TextView) view.findViewById(R.id.info_text); TextView maxText = (TextView) view.findViewById(R.id.max_text); TextView minText = (TextView) view.findViewById(R.id.min_text); dateText.setText(forecast.date); infoText.setText(forecast.more.info); maxText.setText(forecast.temperature.max); minText.setText(forecast.temperature.min); forecastLayout.addView(view); } if (weather.aqi != null) { aqiText.setText(weather.aqi.city.aqi); pm25Text.setText(weather.aqi.city.pm25); } String comfort = "舒适度:" + weather.suggestion.comfort.info; String carWash = "洗车指数:" + weather.suggestion.carWash.info; String sport = "运动建议:" + weather.suggestion.sport.info; comfortText.setText(comfort); carWashText.setText(carWash); sportText.setText(sport); weatherLayout.setVisibility(View.VISIBLE); Intent intent = new Intent(this, AutoUpdateService.class); startService(intent); } else { Toast.makeText(this, "获取天气信息失败", Toast.LENGTH_SHORT).show(); } } }
/* * This file is part of ThermalRecycling, licensed under the MIT License (MIT). * * Copyright (c) OreCruncher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.blockartistry.mod.ThermalRecycling.machines.gui; import org.blockartistry.mod.ThermalRecycling.items.CoreType; import org.blockartistry.mod.ThermalRecycling.machines.entity.MachineStatus; import org.blockartistry.mod.ThermalRecycling.machines.entity.ThermalRecyclerTileEntity; import org.blockartistry.mod.ThermalRecycling.util.MyUtils; import cofh.lib.gui.slot.SlotAcceptValid; import cofh.lib.gui.slot.SlotRemoveOnly; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; /* * A good chunk of this code was sourced from the following: * * http://jabelarminecraft.blogspot.com/p/minecraft-modding-containers.html */ public final class ThermalRecyclerContainer extends MachineContainer<ThermalRecyclerTileEntity> { private MachineStatus currentStatus = MachineStatus.IDLE; private int currentProgress = 0; private int currentEnergy = 0; private int currentEnergyRate = 0; public ThermalRecyclerContainer(final InventoryPlayer inv, final IInventory tileEntity) { super((ThermalRecyclerTileEntity)tileEntity); // GUI dimension is width 427, height 240 final IInventory inventory = entity.getMachineInventory(); Slot s = new SlotAcceptValid(inventory, ThermalRecyclerTileEntity.INPUT, 56, 34); addSlotToContainer(s); for (int i = 0; i < ThermalRecyclerTileEntity.OUTPUT_SLOTS.length; i++) { final int oSlot = ThermalRecyclerTileEntity.OUTPUT_SLOTS[i]; final int h = (i % 3) * GUI_INVENTORY_CELL_SIZE + 106; final int v = (i / 3) * GUI_INVENTORY_CELL_SIZE + 17; s = new SlotRemoveOnly(inventory, oSlot, h, v); addSlotToContainer(s); } s = new SlotAcceptValid(inventory, ThermalRecyclerTileEntity.CORE, 33, 34); addSlotToContainer(s); addPlayerInventory(inv, 166); } @Override public void handleStatus() { final MachineStatus status = entity.getStatus(); final int progress = entity.getProgress(); final int energy = entity.getInfoEnergyStored(); final int energyRate = entity.getInfoEnergyPerTick(); for (int i = 0; i < crafters.size(); ++i) { final ICrafting icrafting = (ICrafting) crafters.get(i); if (progress != currentProgress) icrafting.sendProgressBarUpdate(this, ThermalRecyclerTileEntity.UPDATE_ACTION_PROGRESS, progress); if (energy != currentEnergy) icrafting.sendProgressBarUpdate(this, ThermalRecyclerTileEntity.UPDATE_ACTION_ENERGY, energy/10); if (energyRate != currentEnergyRate) icrafting.sendProgressBarUpdate(this, ThermalRecyclerTileEntity.UPDATE_ACTION_ENERGY_RATE, energyRate); if (status != currentStatus) icrafting.sendProgressBarUpdate(this, ThermalRecyclerTileEntity.UPDATE_ACTION_STATUS, status.ordinal()); } currentStatus = status; currentProgress = progress; currentEnergy = energy; currentEnergyRate = energyRate; } @Override public ItemStack transferStackInSlot(final EntityPlayer playerIn, final int slotIndex) { ItemStack stack = null; final Slot slot = (Slot) inventorySlots.get(slotIndex); // null checks and checks if the item can be stacked (maxStackSize > 1) if (slot != null && slot.getHasStack()) { final ItemStack stackInSlot = slot.getStack(); stack = stackInSlot.copy(); // If the slot is INPUT or one of the OUTPUTs, move the contents // to the player inventory if (MyUtils.contains(ThermalRecyclerTileEntity.ALL_SLOTS, slotIndex)) { if (!mergeToPlayerInventory(stackInSlot)) { return null; } } else { final int targetSlot = CoreType.isProcessingCore(stackInSlot) ? ThermalRecyclerTileEntity.CORE : ThermalRecyclerTileEntity.INPUT; if (entity.isItemValidForSlot(targetSlot, stackInSlot)) { // Try moving to the input slot if (!mergeItemStack(stackInSlot, targetSlot, targetSlot + 1, false)) { return null; } } } // Cleanup the stack if (stackInSlot.stackSize == 0) { slot.putStack(null); } // Nothing changed if (stackInSlot.stackSize == stack.stackSize) { return null; } } return stack; } }
package top.chao.funding.bean; import java.util.ArrayList; import java.util.List; public class TTagExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public TTagExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andPidIsNull() { addCriterion("pid is null"); return (Criteria) this; } public Criteria andPidIsNotNull() { addCriterion("pid is not null"); return (Criteria) this; } public Criteria andPidEqualTo(Integer value) { addCriterion("pid =", value, "pid"); return (Criteria) this; } public Criteria andPidNotEqualTo(Integer value) { addCriterion("pid <>", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThan(Integer value) { addCriterion("pid >", value, "pid"); return (Criteria) this; } public Criteria andPidGreaterThanOrEqualTo(Integer value) { addCriterion("pid >=", value, "pid"); return (Criteria) this; } public Criteria andPidLessThan(Integer value) { addCriterion("pid <", value, "pid"); return (Criteria) this; } public Criteria andPidLessThanOrEqualTo(Integer value) { addCriterion("pid <=", value, "pid"); return (Criteria) this; } public Criteria andPidIn(List<Integer> values) { addCriterion("pid in", values, "pid"); return (Criteria) this; } public Criteria andPidNotIn(List<Integer> values) { addCriterion("pid not in", values, "pid"); return (Criteria) this; } public Criteria andPidBetween(Integer value1, Integer value2) { addCriterion("pid between", value1, value2, "pid"); return (Criteria) this; } public Criteria andPidNotBetween(Integer value1, Integer value2) { addCriterion("pid not between", value1, value2, "pid"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
// *************************************************************************************************************************** // * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * // * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * // * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * // * with the License. You may obtain a copy of the License at * // * * // * http://www.apache.org/licenses/LICENSE-2.0 * // * * // * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * // * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * // * specific language governing permissions and limitations under the License. * // *************************************************************************************************************************** package org.apache.juneau.rest.client; import org.apache.http.*; import org.apache.juneau.rest.client.assertion.*; /** * An implementation of {@link StatusLine} that adds assertions methods. */ public class ResponseStatusLine implements StatusLine { private final RestResponse response; private final StatusLine inner; /** * Constructor. * * @param response The response that created this object. * @param inner The status line returned by the underlying client. */ protected ResponseStatusLine(RestResponse response, StatusLine inner) { this.response = response; this.inner = inner; } @Override /* StatusLine */ public ProtocolVersion getProtocolVersion() { return inner.getProtocolVersion(); } @Override /* StatusLine */ public int getStatusCode() { return inner.getStatusCode(); } @Override /* StatusLine */ public String getReasonPhrase() { return inner.getReasonPhrase(); } //------------------------------------------------------------------------------------------------------------------ // Assertions //------------------------------------------------------------------------------------------------------------------ /** * Provides the ability to perform fluent-style assertions on this response status line. * * <h5 class='section'>Examples:</h5> * <p class='bcode w800'> * <jc>// Validates the content type header is provided.</jc> * <jv>client</jv> * .get(<jsf>URI</jsf>) * .run() * .getStatusLine().assertValue().code().is(200); * </p> * * @return A new fluent assertion object. */ public FluentResponseStatusLineAssertion<ResponseStatusLine> assertValue() { return new FluentResponseStatusLineAssertion<>(this, this); } /** * Returns the response that created this object. * * @return The response that created this object. */ public RestResponse response() { return response; } //------------------------------------------------------------------------------------------------------------------ // Other methods //------------------------------------------------------------------------------------------------------------------ @Override /* Object */ public String toString() { return inner.toString(); } }
package com.cloudhopper.smpp.pdu; /* * #%L * ch-smpp * %% * Copyright (C) 2009 - 2015 Cloudhopper by Twitter * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.cloudhopper.smpp.SmppConstants; public class SubmitSmResp extends BaseSmResp { public SubmitSmResp() { super(SmppConstants.CMD_ID_SUBMIT_SM_RESP, "submit_sm_resp"); } }
package com.woshidaniu.orm.mybatis.utils; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import org.apache.ibatis.builder.xml.dynamic.ForEachSqlNode; import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.executor.ExecutorException; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.mapping.ParameterMode; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.property.PropertyTokenizer; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.type.TypeHandler; import org.apache.ibatis.type.TypeHandlerRegistry; public abstract class MybatisUtils { /** * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler * @param ps * @param mappedStatement * @param boundSql * @param parameterObject * @throws SQLException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void setParameters(PreparedStatement ps,MappedStatement mappedStatement,BoundSql boundSql,Object parameterObject) throws SQLException { /*ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql); parameterHandler.setParameters(ps); */ ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId()); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings != null) { Configuration configuration = mappedStatement.getConfiguration(); TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); MetaObject metaObject = parameterObject == null ? null: configuration.newMetaObject(parameterObject); ParameterMapping parameterMapping = null; Object value = null; String propertyName = null; for (int i = 0; i < parameterMappings.size(); i++) { parameterMapping = parameterMappings.get(i); if (parameterMapping.getMode() != ParameterMode.OUT) { propertyName = parameterMapping.getProperty(); PropertyTokenizer prop = new PropertyTokenizer(propertyName); if (parameterObject == null) { value = null; } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { value = parameterObject; } else if (boundSql.hasAdditionalParameter(propertyName)) { value = boundSql.getAdditionalParameter(propertyName); } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)&& boundSql.hasAdditionalParameter(prop.getName())) { value = boundSql.getAdditionalParameter(prop.getName()); if (value != null) { value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length())); } } else { value = metaObject == null ? null : metaObject.getValue(propertyName); } TypeHandler typeHandler = parameterMapping.getTypeHandler(); if (typeHandler == null) { throw new ExecutorException("There was no TypeHandler found for parameter "+ propertyName + " of statement "+ mappedStatement.getId()); } typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType()); } } } } }
package com.godmonth.status.test.sample.db2; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties; import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionOperations; import org.springframework.transaction.support.TransactionTemplate; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.util.Map; @Configuration @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) @EnableJpaRepositories(entityManagerFactoryRef = "e2", transactionManagerRef = "tm2", basePackages = "com.godmonth.status.test.sample.repo") //@EntityScan("com.godmonth.status.test.sample.domain") public class RepoConfig2 { @Bean("d2") @ConfigurationProperties(prefix = "spring.db2") public DataSource userDataSource() { return DataSourceBuilder.create().build(); } // userEntityManager bean @Bean("e2") public LocalContainerEntityManagerFactoryBean entityManagerFactory( @Qualifier("d2") DataSource userDataSource, JpaProperties jpaProperties) { JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); EntityManagerFactoryBuilder builder = new EntityManagerFactoryBuilder(vendorAdapter, jpaProperties.getProperties(), null); HibernateProperties hibernateProperties = new HibernateProperties(); Map<String, Object> properties = hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()); return builder.dataSource(userDataSource).properties(properties).packages("com.godmonth.status.test.sample.domain").build(); } @Bean("tm2") public PlatformTransactionManager userTransactionManager(@Qualifier("e2") EntityManagerFactory entityManagerFactory) { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager; } @Bean("tt2") public TransactionOperations transactionTemplate(@Qualifier("tm2") PlatformTransactionManager platformTransactionManager) { return new TransactionTemplate(platformTransactionManager); } }
package com.xiaoanjujia.common.widget.pulltorefresh.util; import android.util.Log; /** * An encapsulation of {@link Log}, enable log level and print log with parameters. * * @author http://www.liaohuqiu.net/ */ public class PtrCLog { public static final int LEVEL_VERBOSE = 0; public static final int LEVEL_DEBUG = 1; public static final int LEVEL_INFO = 2; public static final int LEVEL_WARNING = 3; public static final int LEVEL_ERROR = 4; public static final int LEVEL_FATAL = 5; private static int sLevel = LEVEL_VERBOSE; /** * set log level, the level lower than this level will not be logged * * @param level */ public static void setLogLevel(int level) { sLevel = level; } /** * Send a VERBOSE log message. * * @param tag * @param msg */ public static void v(String tag, String msg) { if (sLevel > LEVEL_VERBOSE) { return; } Log.v(tag, msg); } /** * Send a VERBOSE log message. * * @param tag * @param msg * @param throwable */ public static void v(String tag, String msg, Throwable throwable) { if (sLevel > LEVEL_VERBOSE) { return; } Log.v(tag, msg, throwable); } /** * Send a VERBOSE log message. * * @param tag * @param msg * @param args */ public static void v(String tag, String msg, Object... args) { if (sLevel > LEVEL_VERBOSE) { return; } if (args.length > 0) { msg = String.format(msg, args); } Log.v(tag, msg); } /** * Send a DEBUG log message * * @param tag * @param msg */ public static void d(String tag, String msg) { if (sLevel > LEVEL_DEBUG) { return; } Log.d(tag, msg); } /** * Send a DEBUG log message * * @param tag * @param msg * @param args */ public static void d(String tag, String msg, Object... args) { if (sLevel > LEVEL_DEBUG) { return; } if (args.length > 0) { msg = String.format(msg, args); } Log.d(tag, msg); } /** * Send a DEBUG log message * * @param tag * @param msg * @param throwable */ public static void d(String tag, String msg, Throwable throwable) { if (sLevel > LEVEL_DEBUG) { return; } Log.d(tag, msg, throwable); } /** * Send an INFO log message * * @param tag * @param msg */ public static void i(String tag, String msg) { if (sLevel > LEVEL_INFO) { return; } Log.i(tag, msg); } /** * Send an INFO log message * * @param tag * @param msg * @param args */ public static void i(String tag, String msg, Object... args) { if (sLevel > LEVEL_INFO) { return; } if (args.length > 0) { msg = String.format(msg, args); } Log.i(tag, msg); } /** * Send an INFO log message * * @param tag * @param msg */ public static void i(String tag, String msg, Throwable throwable) { if (sLevel > LEVEL_INFO) { return; } Log.i(tag, msg, throwable); } /** * Send a WARNING log message * * @param tag * @param msg */ public static void w(String tag, String msg) { if (sLevel > LEVEL_WARNING) { return; } Log.w(tag, msg); } /** * Send a WARNING log message * * @param tag * @param msg * @param args */ public static void w(String tag, String msg, Object... args) { if (sLevel > LEVEL_WARNING) { return; } if (args.length > 0) { msg = String.format(msg, args); } Log.w(tag, msg); } /** * Send a WARNING log message * * @param tag * @param msg * @param throwable */ public static void w(String tag, String msg, Throwable throwable) { if (sLevel > LEVEL_WARNING) { return; } Log.w(tag, msg, throwable); } /** * Send an ERROR log message * * @param tag * @param msg */ public static void e(String tag, String msg) { if (sLevel > LEVEL_ERROR) { return; } Log.e(tag, msg); } /** * Send an ERROR log message * * @param tag * @param msg * @param args */ public static void e(String tag, String msg, Object... args) { if (sLevel > LEVEL_ERROR) { return; } if (args.length > 0) { msg = String.format(msg, args); } Log.e(tag, msg); } /** * Send an ERROR log message * * @param tag * @param msg * @param throwable */ public static void e(String tag, String msg, Throwable throwable) { if (sLevel > LEVEL_ERROR) { return; } Log.e(tag, msg, throwable); } /** * Send a FATAL ERROR log message * * @param tag * @param msg */ public static void f(String tag, String msg) { if (sLevel > LEVEL_FATAL) { return; } Log.wtf(tag, msg); } /** * Send a FATAL ERROR log message * * @param tag * @param msg * @param args */ public static void f(String tag, String msg, Object... args) { if (sLevel > LEVEL_FATAL) { return; } if (args.length > 0) { msg = String.format(msg, args); } Log.wtf(tag, msg); } /** * Send a FATAL ERROR log message * * @param tag * @param msg * @param throwable */ public static void f(String tag, String msg, Throwable throwable) { if (sLevel > LEVEL_FATAL) { return; } Log.wtf(tag, msg, throwable); } }
package com.letv.android.client.live.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView.Adapter; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.LayoutInflater; import android.view.ViewGroup; import com.letv.android.client.R; import com.letv.android.client.live.utils.LiveUtils; import com.letv.hackdex.VerifyLoad; import com.letv.hotfixlib.HotFix; public class LiveRemenChannelAdapter extends Adapter { private Context mContext; public LiveRemenChannelAdapter(Context context) { if (HotFix.PREVENT_VERIFY) { System.out.println(VerifyLoad.class); } this.mContext = context; } public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(this, LayoutInflater.from(this.mContext).inflate(R.layout.item_live_remen_channel, parent, false)); } public void onBindViewHolder(ViewHolder holder, int position) { ViewHolder viewHolder = (ViewHolder) holder; ViewHolder.access$000(viewHolder).setText(LiveUtils.names[position]); ViewHolder.access$100(viewHolder).setImageResource(LiveUtils.icons[position]); if (position % 2 == 0) { ViewHolder.access$200(viewHolder).setVisibility(8); if (position == 0) { ViewHolder.access$300(viewHolder).setVisibility(0); ViewHolder.access$400(viewHolder).setVisibility(8); ViewHolder.access$500(viewHolder).setVisibility(8); ViewHolder.access$600(viewHolder).setVisibility(0); return; } else if (position == 10) { ViewHolder.access$300(viewHolder).setVisibility(8); ViewHolder.access$400(viewHolder).setVisibility(8); ViewHolder.access$500(viewHolder).setVisibility(0); ViewHolder.access$600(viewHolder).setVisibility(8); return; } else { ViewHolder.access$300(viewHolder).setVisibility(0); ViewHolder.access$400(viewHolder).setVisibility(0); ViewHolder.access$500(viewHolder).setVisibility(8); ViewHolder.access$600(viewHolder).setVisibility(8); return; } } ViewHolder.access$400(viewHolder).setVisibility(8); ViewHolder.access$500(viewHolder).setVisibility(8); ViewHolder.access$600(viewHolder).setVisibility(8); ViewHolder.access$300(viewHolder).setVisibility(8); ViewHolder.access$200(viewHolder).setVisibility(0); } public int getItemCount() { return LiveUtils.names.length; } }
package org.carlspring.strongbox.storage.routing; import javax.annotation.concurrent.Immutable; import java.util.Collections; import java.util.List; import com.google.common.collect.ImmutableList; import static java.util.stream.Collectors.toList; /** * @author Przemyslaw Fusik */ @Immutable public class RoutingRules { private final List<RoutingRule> rules; private List<RoutingRule> denied; private List<RoutingRule> accepted; public RoutingRules(final MutableRoutingRules delegate) { this.rules = immuteRoutingRules(delegate.getRules()); } private List<RoutingRule> immuteRoutingRules(final List<MutableRoutingRule> source) { return source != null ? ImmutableList.copyOf(source.stream().map(RoutingRule::new).collect(toList())) : Collections.emptyList(); } public List<RoutingRule> getRules() { return rules; } public List<RoutingRule> getDenied() { if (denied != null) { return denied; } return denied = rules.stream().filter(RoutingRule::isDeny).collect(toList()); } public List<RoutingRule> getAccepted() { if (accepted != null) { return accepted; } return accepted = rules.stream().filter(RoutingRule::isAccept).collect(toList()); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.scalar; import com.facebook.presto.metadata.BoundVariables; import com.facebook.presto.metadata.FunctionKind; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.Signature; import com.facebook.presto.metadata.SqlScalarFunction; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.block.BlockBuilderStatus; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import java.lang.invoke.MethodHandle; import static com.facebook.presto.metadata.Signature.typeVariable; import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.spi.type.TypeUtils.readNativeValue; import static com.facebook.presto.spi.type.TypeUtils.writeNativeValue; import static com.facebook.presto.util.Failures.checkCondition; import static com.facebook.presto.util.Reflection.methodHandle; public final class ZipWithFunction extends SqlScalarFunction { public static final ZipWithFunction ZIP_WITH_FUNCTION = new ZipWithFunction(); private static final MethodHandle METHOD_HANDLE = methodHandle(ZipWithFunction.class, "zipWith", Type.class, Type.class, Type.class, ConnectorSession.class, Block.class, Block.class, MethodHandle.class); private ZipWithFunction() { super(new Signature( "zip_with", FunctionKind.SCALAR, ImmutableList.of(typeVariable("T"), typeVariable("U"), typeVariable("R")), ImmutableList.of(), parseTypeSignature("array(R)"), ImmutableList.of(parseTypeSignature("array(T)"), parseTypeSignature("array(U)"), parseTypeSignature("function(T,U,R)")), false)); } @Override public boolean isHidden() { return false; } @Override public boolean isDeterministic() { return false; } @Override public String getDescription() { return "merge two arrays, element-wise, into a single array using the lambda function"; } @Override public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { Type leftElementType = boundVariables.getTypeVariable("T"); Type rightElementType = boundVariables.getTypeVariable("U"); Type outputElementType = boundVariables.getTypeVariable("R"); return new ScalarFunctionImplementation( false, ImmutableList.of(false, false, false), METHOD_HANDLE.bindTo(leftElementType).bindTo(rightElementType).bindTo(outputElementType), isDeterministic()); } public static Block zipWith(Type leftElementType, Type rightElementType, Type outputElementType, ConnectorSession session, Block leftBlock, Block rightBlock, MethodHandle function) { checkCondition(leftBlock.getPositionCount() == rightBlock.getPositionCount(), INVALID_FUNCTION_ARGUMENT, "Arrays must have the same length"); BlockBuilder resultBuilder = outputElementType.createBlockBuilder(new BlockBuilderStatus(), leftBlock.getPositionCount()); for (int position = 0; position < leftBlock.getPositionCount(); position++) { Object left = readNativeValue(leftElementType, leftBlock, position); Object right = readNativeValue(rightElementType, rightBlock, position); Object output; try { output = function.invoke(session, left, right); } catch (Throwable throwable) { throw Throwables.propagate(throwable); } writeNativeValue(outputElementType, resultBuilder, output); } return resultBuilder.build(); } }
package orangelynx.ic2_extra_fuels; import com.google.gson.Gson; import ic2.api.recipe.Recipes; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.Logger; import java.io.*; @Mod(modid = Constant.MODID, name = Constant.NAME, version = Constant.VERSION, acceptableRemoteVersions = "*") public class Ic2ExtraFuels { private static Logger logger; private FuelData fuelData; @EventHandler public void preInit(FMLPreInitializationEvent event) { logger = event.getModLog(); File additionalFuelsConfigFile = new File(event.getModConfigurationDirectory(), Constant.ADDITIONAL_FUELS_CFG_FILE_NAME); if (!additionalFuelsConfigFile.exists()) { logger.info("Additional fuels config file \"{}\" not found. Creating default config.", Constant.ADDITIONAL_FUELS_CFG_FILE_NAME); this.writeDefaultAdditionalFuelsConfig(event.getModConfigurationDirectory()); } try (FileReader fileReader = new FileReader(additionalFuelsConfigFile)) { Gson gson = new Gson(); this.fuelData = gson.fromJson(fileReader, FuelData.class); } catch (FileNotFoundException e) { // This should never happen as we checked the file's existence before! logger.error("Additional fuels config file \"" + Constant.ADDITIONAL_FUELS_CFG_FILE_NAME + "\" not found! Something is very odd, please consider filing a bug report.", e); } catch (IOException e) { logger.error("Additional fuels config file \"" + Constant.ADDITIONAL_FUELS_CFG_FILE_NAME + "\" is malformed! Replacing with default config for next restart.", e); this.writeDefaultAdditionalFuelsConfig(event.getModConfigurationDirectory()); } } @EventHandler public void postInit(FMLPostInitializationEvent event) { for (Fuel fuel : fuelData.getSemiFluidGenerator()) { if (Recipes.semiFluidGenerator.getFuelProperties().containsKey(fuel.getName())) { Gson gson = new Gson(); logger.info("fuel semiFluidGenerator exists with props: " + gson.toJson(Recipes.semiFluidGenerator.getFuelProperties().get(fuel.getName()))); continue; } Recipes.semiFluidGenerator.addFluid(fuel.getName(), fuel.getAmountConsumedPerTick(), fuel.getGeneratedPerTick()); logger.info("Recipes.semiFluidGenerator.addFluid({})",fuel); } for (Fuel fuel : fuelData.getFluidHeatGenerator()) { if (Recipes.fluidHeatGenerator.getBurnProperties().containsKey(fuel.getName())) { Gson gson = new Gson(); logger.info("fuel fluidHeatGenerator exists with props: " + gson.toJson(Recipes.fluidHeatGenerator.getBurnProperties().get(fuel.getName()))); continue; } Recipes.fluidHeatGenerator.addFluid(fuel.getName(), fuel.getAmountConsumedPerTick(), fuel.getGeneratedPerTick()); logger.info("Recipes.fluidHeatGenerator.addFluid({})",fuel); } } private void writeDefaultAdditionalFuelsConfig(File modConfigDirectory) { File additionalFuelsConfigFile = new File(modConfigDirectory, Constant.ADDITIONAL_FUELS_CFG_FILE_NAME); if (additionalFuelsConfigFile.exists()) { return; } try (InputStream defaultAdditionalFuelsConfigStream = getClass().getResourceAsStream("/assets/config/" + Constant.ADDITIONAL_FUELS_CFG_FILE_NAME)) { if (defaultAdditionalFuelsConfigStream == null) { throw new NullPointerException("don't find default additional"); } try (FileOutputStream outputStream = new FileOutputStream(additionalFuelsConfigFile)) { IOUtils.copy(defaultAdditionalFuelsConfigStream, outputStream); } } catch (Throwable e) { logger.error("Could not write default additional fuels config file \"" + Constant.ADDITIONAL_FUELS_CFG_FILE_NAME + "\" to mod's configuration directory! If this issue persists across restarts, please consider filing a bug report.", e); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.genetics; import java.util.ArrayList; import java.util.List; import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.exception.util.LocalizedFormats; /** * Mutation operator for {@link RandomKey}s. Changes a randomly chosen element * of the array representation to a random value uniformly distributed in [0,1]. * * @since 2.0 * @version $Revision: 983921 $ $Date: 2010-08-10 12:46:06 +0200 (mar. 10 août 2010) $ */ public class RandomKeyMutation implements MutationPolicy { /** * {@inheritDoc} * * @throws IllegalArgumentException if <code>original</code> is not a * {@link RandomKey} instance */ public Chromosome mutate(Chromosome original) { if (!(original instanceof RandomKey<?>)) { throw MathRuntimeException.createIllegalArgumentException( LocalizedFormats.RANDOMKEY_MUTATION_WRONG_CLASS, original.getClass().getSimpleName()); } RandomKey<?> originalRk = (RandomKey<?>) original; List<Double> repr = originalRk.getRepresentation(); int rInd = GeneticAlgorithm.getRandomGenerator().nextInt(repr.size()); List<Double> newRepr = new ArrayList<Double> (repr); newRepr.set(rInd, GeneticAlgorithm.getRandomGenerator().nextDouble()); return originalRk.newFixedLengthChromosome(newRepr); } }
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * <fullname>AWS Secrets Manager API Reference</fullname> * <p> * AWS Secrets Manager provides a service to enable you to store, manage, and retrieve, secrets. * </p> * <p> * This guide provides descriptions of the Secrets Manager API. For more information about using this service, see the * <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/introduction.html">AWS Secrets Manager User * Guide</a>. * </p> * <p> * <b>API Version</b> * </p> * <p> * This version of the Secrets Manager API Reference documents the Secrets Manager API version 2017-10-17. * </p> * <note> * <p> * As an alternative to using the API, you can use one of the AWS SDKs, which consist of libraries and sample code for * various programming languages and platforms such as Java, Ruby, .NET, iOS, and Android. The SDKs provide a convenient * way to create programmatic access to AWS Secrets Manager. For example, the SDKs provide cryptographically signing * requests, managing errors, and retrying requests automatically. For more information about the AWS SDKs, including * downloading and installing them, see <a href="http://aws.amazon.com/tools/">Tools for Amazon Web Services</a>. * </p> * </note> * <p> * We recommend you use the AWS SDKs to make programmatic API calls to Secrets Manager. However, you also can use the * Secrets Manager HTTP Query API to make direct calls to the Secrets Manager web service. To learn more about the * Secrets Manager HTTP Query API, see <a * href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/query-requests.html">Making Query Requests</a> in * the <i>AWS Secrets Manager User Guide</i>. * </p> * <p> * Secrets Manager API supports GET and POST requests for all actions, and doesn't require you to use GET for some * actions and POST for others. However, GET requests are subject to the limitation size of a URL. Therefore, for * operations that require larger sizes, use a POST request. * </p> * <p> * <b>Support and Feedback for AWS Secrets Manager</b> * </p> * <p> * We welcome your feedback. Send your comments to <a * href="mailto:awssecretsmanager-feedback@amazon.com">awssecretsmanager-feedback@amazon.com</a>, or post your feedback * and questions in the <a href="http://forums.aws.amazon.com/forum.jspa?forumID=296">AWS Secrets Manager Discussion * Forum</a>. For more information about the AWS Discussion Forums, see <a * href="http://forums.aws.amazon.com/help.jspa">Forums Help</a>. * </p> * <p> * <b>How examples are presented</b> * </p> * <p> * The JSON that AWS Secrets Manager expects as your request parameters and the service returns as a response to HTTP * query requests contain single, long strings without line breaks or white space formatting. The JSON shown in the * examples displays the code formatted with both line breaks and white space to improve readability. When example input * parameters can also cause long strings extending beyond the screen, you can insert line breaks to enhance * readability. You should always submit the input as a single JSON text string. * </p> * <p> * <b>Logging API Requests</b> * </p> * <p> * AWS Secrets Manager supports AWS CloudTrail, a service that records AWS API calls for your AWS account and delivers * log files to an Amazon S3 bucket. By using information that's collected by AWS CloudTrail, you can determine the * requests successfully made to Secrets Manager, who made the request, when it was made, and so on. For more about AWS * Secrets Manager and support for AWS CloudTrail, see <a * href="http://docs.aws.amazon.com/secretsmanager/latest/userguide/monitoring.html#monitoring_cloudtrail">Logging AWS * Secrets Manager Events with AWS CloudTrail</a> in the <i>AWS Secrets Manager User Guide</i>. To learn more about * CloudTrail, including enabling it and find your log files, see the <a * href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html">AWS CloudTrail * User Guide</a>. * </p> */ package com.amazonaws.services.secretsmanager;
package com.aliya.uimode.widget; import android.content.Context; import android.content.res.TypedArray; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View.MeasureSpec; import android.view.ViewGroup.LayoutParams; import com.aliya.uimode.R; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; /** * 固定宽高比 - 助手 * * @author a_liYa * @date 2017/7/18 23:00. */ class RatioHelper { private static final String RATIO_SYMBOL = ":"; private static final int NO_VALUE = -1; private float ratio_w2h = NO_VALUE; public RatioHelper(@NonNull Context context, @Nullable AttributeSet attrs) { if (attrs == null) return; TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RatioLayout); if (ta.hasValue(R.styleable.RatioLayout_ratio_w2h)) { String w_h = ta.getString(R.styleable.RatioLayout_ratio_w2h); if (!TextUtils.isEmpty(w_h) && w_h.contains(RATIO_SYMBOL)) { String[] split = w_h.trim().split(RATIO_SYMBOL); if (split != null && split.length == 2) { try { ratio_w2h = Float.parseFloat(split[0].trim()) / Float.parseFloat(split[1].trim()); } catch (NumberFormatException e) { // no-op } } } } ta.recycle(); } public int widthMeasureSpec(int widthMeasureSpec, int heightMeasureSpec, LayoutParams params) { if (ratio_w2h > 0) { int wMode = MeasureSpec.getMode(widthMeasureSpec); int hMode = MeasureSpec.getMode(heightMeasureSpec); int hSize = MeasureSpec.getSize(heightMeasureSpec); if (wMode != MeasureSpec.EXACTLY && hMode == MeasureSpec.EXACTLY || params.width == WRAP_CONTENT && params.height != WRAP_CONTENT) { widthMeasureSpec = MeasureSpec .makeMeasureSpec(Math.round(hSize * ratio_w2h), MeasureSpec.EXACTLY); } } return widthMeasureSpec; } public int heightMeasureSpec(int widthMeasureSpec, int heightMeasureSpec, LayoutParams params) { if (ratio_w2h > 0) { int wMode = MeasureSpec.getMode(widthMeasureSpec); int hMode = MeasureSpec.getMode(heightMeasureSpec); int wSize = MeasureSpec.getSize(widthMeasureSpec); if (wMode == MeasureSpec.EXACTLY && hMode != MeasureSpec.EXACTLY || params.width != WRAP_CONTENT && params.height == WRAP_CONTENT) { heightMeasureSpec = MeasureSpec .makeMeasureSpec(Math.round(wSize / ratio_w2h), MeasureSpec.EXACTLY); } } return heightMeasureSpec; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.any23.extractor.calendar; import biweekly.ICalDataType; import biweekly.ICalVersion; import biweekly.ICalendar; import biweekly.component.ICalComponent; import biweekly.component.VTimezone; import biweekly.io.ParseWarning; import biweekly.io.SkipMeException; import biweekly.io.StreamReader; import biweekly.io.TimezoneAssignment; import biweekly.io.TimezoneInfo; import biweekly.io.WriteContext; import biweekly.io.json.JCalValue; import biweekly.io.json.JsonValue; import biweekly.io.scribe.ScribeIndex; import biweekly.io.scribe.property.ICalPropertyScribe; import biweekly.parameter.Encoding; import biweekly.parameter.ICalParameters; import biweekly.property.Geo; import biweekly.property.ICalProperty; import biweekly.util.DateTimeComponents; import biweekly.util.ICalDateFormat; import org.apache.any23.extractor.ExtractionContext; import org.apache.any23.extractor.ExtractionException; import org.apache.any23.extractor.ExtractionParameters; import org.apache.any23.extractor.ExtractionResult; import org.apache.any23.extractor.Extractor; import org.apache.any23.extractor.IssueReport; import org.apache.any23.vocab.ICAL; import org.apache.commons.lang3.StringUtils; import org.eclipse.rdf4j.model.BNode; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.XMLSchema; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Hans Brende (hansbrende@apache.org) */ abstract class BaseCalendarExtractor implements Extractor.ContentExtractor { @Override public void setStopAtFirstError(boolean b) { //unsupported } private static final ValueFactory f = SimpleValueFactory.getInstance(); private static final ICAL vICAL = ICAL.getInstance(); abstract StreamReader reader(InputStream inputStream); @Override public final void run(ExtractionParameters extractionParameters, ExtractionContext extractionContext, InputStream inputStream, ExtractionResult result) throws IOException, ExtractionException { result.writeNamespace(RDF.PREFIX, RDF.NAMESPACE); result.writeNamespace(ICAL.PREFIX, ICAL.NS); result.writeNamespace(XMLSchema.PREFIX, XMLSchema.NAMESPACE); ScribeIndex index = new ScribeIndex(); try (StreamReader reader = reader(inputStream)) { ICalendar cal; while ((cal = reader.readNext()) != null) { for (ParseWarning warning : reader.getWarnings()) { String message = warning.getMessage(); Integer lineNumber = warning.getLineNumber(); if (lineNumber == null) { result.notifyIssue(IssueReport.IssueLevel.WARNING, message, -1, -1); } else { result.notifyIssue(IssueReport.IssueLevel.WARNING, message, lineNumber, -1); } } BNode calNode = f.createBNode(); result.writeTriple(calNode, RDF.TYPE, vICAL.Vcalendar); WriteContext ctx = new WriteContext(ICalVersion.V2_0, cal.getTimezoneInfo(), null); extract(index, ctx, calNode, cal, result, true); } } catch (Exception e) { result.notifyIssue(IssueReport.IssueLevel.FATAL, toString(e), -1, -1); } } private static String toString(Throwable th) { StringWriter writer = new StringWriter(); try (PrintWriter pw = new PrintWriter(writer)) { th.printStackTrace(pw); } String string = writer.toString(); if (string.length() > 200) { return string.substring(0, 197) + "..."; } return string; } private static String localNameOfType(String typeName) { return camelCase(typeName, false); } private static String localNameOfProperty(String propertyName) { return camelCase(propertyName, true); } private static String camelCase(String name, boolean forProperty) { String[] nameComponents = name.toLowerCase(Locale.ENGLISH).split("-"); StringBuilder sb = new StringBuilder(name.length()); int i = 0; if (forProperty) { sb.append(nameComponents[i++]); } for (int len = nameComponents.length; i < len; i++) { String n = nameComponents[i]; if (!n.isEmpty()) { int ind = Character.charCount(n.codePointAt(0)); sb.append(n.substring(0, ind).toUpperCase(Locale.ENGLISH)).append(n.substring(ind)); } } return sb.toString(); } private static IRI type(String originalName) { if (originalName.regionMatches(true, 0, "X-", 0, 2)) { //non-standard class return f.createIRI(ICAL.NS, "X-" + localNameOfType(originalName.substring(2))); } String name = localNameOfType(originalName); try { return Objects.requireNonNull(vICAL.getClass(name)); } catch (RuntimeException e) { return null; } } private static IRI predicate(String originalName, ExtractionResult result) { if (originalName.regionMatches(true, 0, "X-", 0, 2)) { //non-standard property return f.createIRI(ICAL.NS, "x-" + localNameOfProperty(originalName.substring(2))); } String name = localNameOfProperty(originalName); try { return Objects.requireNonNull(vICAL.getProperty(name)); } catch (RuntimeException e) { IRI iri = f.createIRI(ICAL.NS, name); result.notifyIssue(IssueReport.IssueLevel.ERROR, "property " + iri + " (" + originalName + ") not defined in " + ICAL.class.getName(), -1, -1); return iri; } } private static final String NaN = Double.toString(Double.NaN); private static String str(Double d) { return d == null ? NaN : d.toString(); } private static BNode writeParams(BNode subject, IRI predicate, ICalParameters params, ExtractionResult result) { BNode bNode = f.createBNode(); result.writeTriple(subject, predicate, bNode); writeParams(bNode, params, result); return bNode; } private static void writeParams(BNode subject, ICalParameters params, ExtractionResult result) { for (Map.Entry<String, List<String>> entry : params.getMap().entrySet()) { List<String> strings = entry.getValue(); if (strings != null && !strings.isEmpty()) { IRI predicate = predicate(entry.getKey(), result); for (String v : strings) { result.writeTriple(subject, predicate, f.createLiteral(v)); } } } } private static IRI dataType(ICalDataType dataType, Boolean isFloating) { if (dataType == null || ICalDataType.TEXT.equals(dataType)) { return XMLSchema.STRING; } else if (ICalDataType.BOOLEAN.equals(dataType)) { return XMLSchema.BOOLEAN; } else if (ICalDataType.INTEGER.equals(dataType)) { return XMLSchema.INTEGER; } else if (ICalDataType.FLOAT.equals(dataType)) { return XMLSchema.FLOAT; } else if (ICalDataType.BINARY.equals(dataType)) { return XMLSchema.BASE64BINARY; } else if (ICalDataType.URI.equals(dataType) || ICalDataType.URL.equals(dataType) || ICalDataType.CONTENT_ID.equals(dataType) || ICalDataType.CAL_ADDRESS.equals(dataType)) { return XMLSchema.ANYURI; } else if (ICalDataType.DATE_TIME.equals(dataType)) { if (isFloating == null) { return null; } return isFloating ? vICAL.DATE_TIME : XMLSchema.DATETIME; } else if (ICalDataType.DATE.equals(dataType)) { return XMLSchema.DATE; } else if (ICalDataType.TIME.equals(dataType)) { return XMLSchema.TIME; } else if (ICalDataType.DURATION.equals(dataType)) { return XMLSchema.DURATION; } else if (ICalDataType.PERIOD.equals(dataType)) { return vICAL.Value_PERIOD; } else if (ICalDataType.RECUR.equals(dataType)) { return vICAL.Value_RECUR; } else { return XMLSchema.STRING; } } private static final Pattern durationWeeksPattern = Pattern.compile("(-?P)(\\d+)W"); private static String normalizeAndReportIfInvalid(String s, IRI dataType, TimeZone zone, ExtractionResult result) { if (dataType == null) { return s; } try { if (XMLSchema.DURATION.equals(dataType)) { Matcher m = durationWeeksPattern.matcher(s); if (m.matches()) { long days = Long.parseLong(m.group(2)) * 7; return m.group(1) + days + "D"; } } else if (vICAL.Value_PERIOD.equals(dataType)) { if (s.indexOf('/') == -1) { throw new IllegalArgumentException(); } } else if (zone != null && XMLSchema.DATETIME.equals(dataType)) { try { DateTimeComponents dt = DateTimeComponents.parse(s); if (!dt.isUtc()) { s = ICalDateFormat.DATE_TIME_EXTENDED.format(dt.toDate(zone), zone); } } catch (IllegalArgumentException e) { //ignore } } else { s = XMLDatatypeUtil.normalize(s, dataType); } if (!XMLDatatypeUtil.isValidValue(s, dataType)) { throw new IllegalArgumentException(); } } catch (IllegalArgumentException e) { String m = e.getMessage(); if (StringUtils.isBlank(m)) { m = "Not a valid " + dataType + " value: " + s; } result.notifyIssue(IssueReport.IssueLevel.ERROR, m, -1, -1); } return s; } private static boolean writeValue(BNode subject, IRI predicate, JsonValue jsonValue, String lang, IRI dataType, TimeZone zone, ExtractionResult result) { if (jsonValue == null || jsonValue.isNull()) { return false; } Object val = jsonValue.getValue(); if (val != null) { Value v; if (val instanceof Byte) { v = f.createLiteral((byte)val); } else if (val instanceof Short) { v = f.createLiteral((short)val); } else if (val instanceof Integer) { v = f.createLiteral((int)val); } else if (val instanceof Long) { v = f.createLiteral((long)val); } else if (val instanceof Float) { v = f.createLiteral((float)val); } else if (val instanceof Double) { v = f.createLiteral((double)val); } else if (val instanceof Boolean) { v = f.createLiteral((boolean)val); } else if (val instanceof BigInteger) { v = f.createLiteral((BigInteger)val); } else if (val instanceof BigDecimal) { v = f.createLiteral((BigDecimal)val); } else { String str = normalizeAndReportIfInvalid(val.toString(), dataType, zone, result); if (XMLSchema.STRING.equals(dataType)) { if (lang == null) { v = f.createLiteral(str); } else { v = f.createLiteral(str, lang); } } else if (XMLSchema.ANYURI.equals(dataType)) { try { v = f.createIRI(str); } catch (IllegalArgumentException e) { v = f.createLiteral(str, dataType); } } else if (vICAL.Value_PERIOD.equals(dataType)) { String[] strs = str.split("/"); if (strs.length == 2) { String firstPart = normalizeAndReportIfInvalid(strs[0], XMLSchema.DATETIME, zone, result); String secondPart = strs[1]; if (secondPart.indexOf('P') != -1) { //duration secondPart = normalizeAndReportIfInvalid(secondPart, XMLSchema.DURATION, zone, result); } else { secondPart = normalizeAndReportIfInvalid(secondPart, XMLSchema.DATETIME, zone, result); } str = firstPart + "/" + secondPart; } v = f.createLiteral(str); } else if (dataType != null) { v = f.createLiteral(str, dataType); } else { v = f.createLiteral(str); } } result.writeTriple(subject, predicate, v); return true; } List<JsonValue> array = jsonValue.getArray(); if (array != null && !array.isEmpty()) { if (array.size() == 1) { return writeValue(subject, predicate, array.get(0), lang, dataType, zone, result); } else { BNode bNode = f.createBNode(); result.writeTriple(subject, predicate, bNode); for (JsonValue value : array) { writeValue(bNode, RDF.VALUE, value, lang, dataType, zone, result); } return true; } } Map<String, JsonValue> object = jsonValue.getObject(); if (object != null) { BNode bNode = f.createBNode(); result.writeTriple(subject, predicate, bNode); for (Map.Entry<String, JsonValue> entry : object.entrySet()) { writeValue(bNode, predicate(entry.getKey(), result), entry.getValue(), lang, XMLSchema.STRING, zone, result); } return true; } return false; } private static TimeZone parseTimeZoneId(String tzId) { for (;;) { TimeZone zone = ICalDateFormat.parseTimeZoneId(tzId); if (zone != null) { return zone; } int ind = tzId.indexOf('/'); if (ind == -1) { return null; } tzId = tzId.substring(ind + 1); } } @SuppressWarnings("unchecked") private static <T extends ICalProperty> void writeProperty(BNode subject, ICalPropertyScribe<T> scribe, ICalProperty property, WriteContext ctx, ExtractionResult result) { try { T prop = (T)property; ICalVersion version = ctx.getVersion(); ICalDataType dataType = scribe.dataType(prop, version); ICalParameters params = scribe.prepareParameters(prop, ctx); String lang = params.getLanguage(); params.removeAll(ICalParameters.LANGUAGE); Encoding encoding = params.getEncoding(); if (dataType == null) { dataType = params.getValue(); if (dataType == null && Encoding.BASE64.equals(encoding)) { dataType = ICalDataType.BINARY; } } params.removeAll(ICalParameters.VALUE); if (ICalDataType.BINARY.equals(dataType)) { // RFC 5545 s. 3.2.7. // If the value type parameter is ";VALUE=BINARY", then the inline // encoding parameter MUST be specified with the value // ";ENCODING=BASE64" if (encoding != null && !Encoding.BASE64.equals(encoding)) { result.notifyIssue(IssueReport.IssueLevel.ERROR, "Invalid encoding " + encoding + " specified for BINARY value", -1, -1); dataType = null; } params.removeAll(ICalParameters.ENCODING); } if (Encoding._8BIT.equals(encoding)) { // RFC 5545 s. 3.2.7. // The default encoding is "8BIT", // corresponding to a property value consisting of text. params.removeAll(ICalParameters.ENCODING); } // RFC 5545 s. 3.1.4. // There is not a property parameter to declare the charset used in a // property value. The default charset for an iCalendar stream is UTF-8 // as defined in [RFC3629]. params.removeAll(ICalParameters.CHARSET); IRI predicate = predicate(scribe.getPropertyName(version), result); if (ICalDataType.CAL_ADDRESS.equals(dataType)) { subject = writeParams(subject, predicate, params, result); predicate = vICAL.calAddress; } else if (!params.isEmpty()) { subject = writeParams(subject, predicate, params, result); predicate = RDF.VALUE; } if (prop instanceof Geo) { // RFC 5870 Geo g = (Geo)prop; IRI value = f.createIRI("geo:" + str(g.getLatitude()) + "," + str(g.getLongitude())); result.writeTriple(subject, predicate, value); } else { String tzId = params.getTimezoneId(); TimezoneInfo tzInfo = ctx.getTimezoneInfo(); TimeZone timeZone = null; Boolean floating; if (tzId != null) { TimezoneAssignment assign = tzInfo.getTimezone(prop); if (assign != null) { timeZone = assign.getTimeZone(); } else { timeZone = parseTimeZoneId(tzId); tzInfo.setFloating(prop, true); } floating = timeZone == null ? null : Boolean.FALSE; } else { floating = tzInfo.isFloating(prop); } IRI dataTypeIRI = dataType(dataType, floating); JCalValue jsonVal = scribe.writeJson(prop, ctx); List<JsonValue> jsonVals = jsonVal.getValues(); boolean mod = false; for (JsonValue value : jsonVals) { mod |= writeValue(subject, predicate, value, lang, dataTypeIRI, timeZone, result); } if (!mod) { result.writeTriple(subject, predicate, f.createLiteral(jsonVal.asSingle())); } } } catch (SkipMeException e) { //ignore } } private static void extract(ScribeIndex index, WriteContext ctx, BNode node, ICalComponent component, ExtractionResult result, boolean writeTimezones) { for (ICalProperty property : component.getProperties().values()) { ctx.setParent(component); writeProperty(node, index.getPropertyScribe(property), property, ctx, result); } Stream<ICalComponent> components = component.getComponents().values().stream(); if (writeTimezones) { Collection<VTimezone> tzs = ctx.getTimezoneInfo().getComponents(); Set<String> tzIds = tzs.stream() .map(tz -> tz.getTimezoneId().getValue()) .collect(Collectors.toSet()); components = Stream.concat(tzs.stream(), components.filter(c -> !(c instanceof VTimezone && tzIds.contains(((VTimezone) c).getTimezoneId().getValue()))) ); } components.forEachOrdered(child -> { BNode childNode = f.createBNode(); String componentName = index.getComponentScribe(child).getComponentName(); IRI childType = type(componentName); if (childType == null) { result.writeTriple(node, predicate(componentName, result), childNode); } else { result.writeTriple(node, vICAL.component, childNode); result.writeTriple(childNode, RDF.TYPE, childType); } extract(index, ctx, childNode, child, result, false); }); } }
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.elasticache.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/CreateGlobalReplicationGroup" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateGlobalReplicationGroupRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The suffix name of a Global Datastore. Amazon ElastiCache automatically applies a prefix to the Global Datastore * ID when it is created. Each AWS Region has its own prefix. For instance, a Global Datastore ID created in the * US-West-1 region will begin with "dsdfu" along with the suffix name you provide. The suffix, combined with the * auto-generated prefix, guarantees uniqueness of the Global Datastore name across multiple regions. * </p> * <p> * For a full list of AWS Regions and their respective Global Datastore iD prefixes, see <a * href="http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Clusters-CLI.html">Using the AWS * CLI with Global Datastores </a>. * </p> */ private String globalReplicationGroupIdSuffix; /** * <p> * Provides details of the Global Datastore * </p> */ private String globalReplicationGroupDescription; /** * <p> * The name of the primary cluster that accepts writes and will replicate updates to the secondary cluster. * </p> */ private String primaryReplicationGroupId; /** * <p> * The suffix name of a Global Datastore. Amazon ElastiCache automatically applies a prefix to the Global Datastore * ID when it is created. Each AWS Region has its own prefix. For instance, a Global Datastore ID created in the * US-West-1 region will begin with "dsdfu" along with the suffix name you provide. The suffix, combined with the * auto-generated prefix, guarantees uniqueness of the Global Datastore name across multiple regions. * </p> * <p> * For a full list of AWS Regions and their respective Global Datastore iD prefixes, see <a * href="http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Clusters-CLI.html">Using the AWS * CLI with Global Datastores </a>. * </p> * * @param globalReplicationGroupIdSuffix * The suffix name of a Global Datastore. Amazon ElastiCache automatically applies a prefix to the Global * Datastore ID when it is created. Each AWS Region has its own prefix. For instance, a Global Datastore ID * created in the US-West-1 region will begin with "dsdfu" along with the suffix name you provide. The * suffix, combined with the auto-generated prefix, guarantees uniqueness of the Global Datastore name across * multiple regions. </p> * <p> * For a full list of AWS Regions and their respective Global Datastore iD prefixes, see <a * href="http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Clusters-CLI.html">Using the * AWS CLI with Global Datastores </a>. */ public void setGlobalReplicationGroupIdSuffix(String globalReplicationGroupIdSuffix) { this.globalReplicationGroupIdSuffix = globalReplicationGroupIdSuffix; } /** * <p> * The suffix name of a Global Datastore. Amazon ElastiCache automatically applies a prefix to the Global Datastore * ID when it is created. Each AWS Region has its own prefix. For instance, a Global Datastore ID created in the * US-West-1 region will begin with "dsdfu" along with the suffix name you provide. The suffix, combined with the * auto-generated prefix, guarantees uniqueness of the Global Datastore name across multiple regions. * </p> * <p> * For a full list of AWS Regions and their respective Global Datastore iD prefixes, see <a * href="http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Clusters-CLI.html">Using the AWS * CLI with Global Datastores </a>. * </p> * * @return The suffix name of a Global Datastore. Amazon ElastiCache automatically applies a prefix to the Global * Datastore ID when it is created. Each AWS Region has its own prefix. For instance, a Global Datastore ID * created in the US-West-1 region will begin with "dsdfu" along with the suffix name you provide. The * suffix, combined with the auto-generated prefix, guarantees uniqueness of the Global Datastore name * across multiple regions. </p> * <p> * For a full list of AWS Regions and their respective Global Datastore iD prefixes, see <a * href="http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Clusters-CLI.html">Using * the AWS CLI with Global Datastores </a>. */ public String getGlobalReplicationGroupIdSuffix() { return this.globalReplicationGroupIdSuffix; } /** * <p> * The suffix name of a Global Datastore. Amazon ElastiCache automatically applies a prefix to the Global Datastore * ID when it is created. Each AWS Region has its own prefix. For instance, a Global Datastore ID created in the * US-West-1 region will begin with "dsdfu" along with the suffix name you provide. The suffix, combined with the * auto-generated prefix, guarantees uniqueness of the Global Datastore name across multiple regions. * </p> * <p> * For a full list of AWS Regions and their respective Global Datastore iD prefixes, see <a * href="http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Clusters-CLI.html">Using the AWS * CLI with Global Datastores </a>. * </p> * * @param globalReplicationGroupIdSuffix * The suffix name of a Global Datastore. Amazon ElastiCache automatically applies a prefix to the Global * Datastore ID when it is created. Each AWS Region has its own prefix. For instance, a Global Datastore ID * created in the US-West-1 region will begin with "dsdfu" along with the suffix name you provide. The * suffix, combined with the auto-generated prefix, guarantees uniqueness of the Global Datastore name across * multiple regions. </p> * <p> * For a full list of AWS Regions and their respective Global Datastore iD prefixes, see <a * href="http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Clusters-CLI.html">Using the * AWS CLI with Global Datastores </a>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateGlobalReplicationGroupRequest withGlobalReplicationGroupIdSuffix(String globalReplicationGroupIdSuffix) { setGlobalReplicationGroupIdSuffix(globalReplicationGroupIdSuffix); return this; } /** * <p> * Provides details of the Global Datastore * </p> * * @param globalReplicationGroupDescription * Provides details of the Global Datastore */ public void setGlobalReplicationGroupDescription(String globalReplicationGroupDescription) { this.globalReplicationGroupDescription = globalReplicationGroupDescription; } /** * <p> * Provides details of the Global Datastore * </p> * * @return Provides details of the Global Datastore */ public String getGlobalReplicationGroupDescription() { return this.globalReplicationGroupDescription; } /** * <p> * Provides details of the Global Datastore * </p> * * @param globalReplicationGroupDescription * Provides details of the Global Datastore * @return Returns a reference to this object so that method calls can be chained together. */ public CreateGlobalReplicationGroupRequest withGlobalReplicationGroupDescription(String globalReplicationGroupDescription) { setGlobalReplicationGroupDescription(globalReplicationGroupDescription); return this; } /** * <p> * The name of the primary cluster that accepts writes and will replicate updates to the secondary cluster. * </p> * * @param primaryReplicationGroupId * The name of the primary cluster that accepts writes and will replicate updates to the secondary cluster. */ public void setPrimaryReplicationGroupId(String primaryReplicationGroupId) { this.primaryReplicationGroupId = primaryReplicationGroupId; } /** * <p> * The name of the primary cluster that accepts writes and will replicate updates to the secondary cluster. * </p> * * @return The name of the primary cluster that accepts writes and will replicate updates to the secondary cluster. */ public String getPrimaryReplicationGroupId() { return this.primaryReplicationGroupId; } /** * <p> * The name of the primary cluster that accepts writes and will replicate updates to the secondary cluster. * </p> * * @param primaryReplicationGroupId * The name of the primary cluster that accepts writes and will replicate updates to the secondary cluster. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateGlobalReplicationGroupRequest withPrimaryReplicationGroupId(String primaryReplicationGroupId) { setPrimaryReplicationGroupId(primaryReplicationGroupId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getGlobalReplicationGroupIdSuffix() != null) sb.append("GlobalReplicationGroupIdSuffix: ").append(getGlobalReplicationGroupIdSuffix()).append(","); if (getGlobalReplicationGroupDescription() != null) sb.append("GlobalReplicationGroupDescription: ").append(getGlobalReplicationGroupDescription()).append(","); if (getPrimaryReplicationGroupId() != null) sb.append("PrimaryReplicationGroupId: ").append(getPrimaryReplicationGroupId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateGlobalReplicationGroupRequest == false) return false; CreateGlobalReplicationGroupRequest other = (CreateGlobalReplicationGroupRequest) obj; if (other.getGlobalReplicationGroupIdSuffix() == null ^ this.getGlobalReplicationGroupIdSuffix() == null) return false; if (other.getGlobalReplicationGroupIdSuffix() != null && other.getGlobalReplicationGroupIdSuffix().equals(this.getGlobalReplicationGroupIdSuffix()) == false) return false; if (other.getGlobalReplicationGroupDescription() == null ^ this.getGlobalReplicationGroupDescription() == null) return false; if (other.getGlobalReplicationGroupDescription() != null && other.getGlobalReplicationGroupDescription().equals(this.getGlobalReplicationGroupDescription()) == false) return false; if (other.getPrimaryReplicationGroupId() == null ^ this.getPrimaryReplicationGroupId() == null) return false; if (other.getPrimaryReplicationGroupId() != null && other.getPrimaryReplicationGroupId().equals(this.getPrimaryReplicationGroupId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getGlobalReplicationGroupIdSuffix() == null) ? 0 : getGlobalReplicationGroupIdSuffix().hashCode()); hashCode = prime * hashCode + ((getGlobalReplicationGroupDescription() == null) ? 0 : getGlobalReplicationGroupDescription().hashCode()); hashCode = prime * hashCode + ((getPrimaryReplicationGroupId() == null) ? 0 : getPrimaryReplicationGroupId().hashCode()); return hashCode; } @Override public CreateGlobalReplicationGroupRequest clone() { return (CreateGlobalReplicationGroupRequest) super.clone(); } }
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2015 Dirk Beyer * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cpa.ifcsecurity.util; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.cpachecker.cpa.ifcsecurity.dependencytracking.Variable; /** * Used for Parsing those Variables/functions that should be checked for security violation at every state and not only at the end. */ public class ImmediateChecksParser { /** * Internal set of Variables/functions that should be checked for security violation at every state. */ private SortedSet<Variable> set=new TreeSet<>(); /** * Starts and execute the ImmediateChecksParser for parsing those Variables/functions that should be checked for security violation at every state. * @param pFile the file to be parsed. */ @SuppressWarnings("resource") public ImmediateChecksParser(LogManager pLogger,Path pFile){ set=new TreeSet<>(); List<String> contents = null; try { contents = Files.readAllLines(pFile, Charset.defaultCharset()); } catch (IOException e) { pLogger.logUserException(Level.WARNING, e, "Could not read intial security mapping from file named " + pFile); return ; } for (String strLine : contents) { if (strLine.trim().isEmpty()) { continue; } else if(strLine.contains(";")){ int sem=strLine.indexOf(";"); Variable var=new Variable(strLine.substring(0, sem)); set.add(var); } } } /** * Returns the set of Variables/function that should be checked for security violation at every state. * @return set of Variables/functions. */ public SortedSet<Variable> getSet(){ return set; } }
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.google.android.glass.sample.stopwatch; public final class R { public static final class attr { } public static final class color { public static final int black=0x7f070000; } public static final class drawable { public static final int ic_colon=0x7f020000; public static final int ic_interpunc=0x7f020001; public static final int ic_lap=0x7f020002; public static final int ic_stop=0x7f020003; } public static final class id { public static final int centi_second=0x7f0a0002; public static final int minute=0x7f0a0000; public static final int second=0x7f0a0001; public static final int seconds=0x7f0a0003; public static final int stop=0x7f0a0004; } public static final class layout { public static final int card_chronometer=0x7f030000; public static final int card_countdown=0x7f030001; } public static final class menu { public static final int stopwatch=0x7f090000; } public static final class raw { public static final int countdown_bip=0x7f050000; public static final int start=0x7f050001; } public static final class string { public static final int app_name=0x7f060000; public static final int stop=0x7f060001; } public static final class style { public static final int ChronometerComponent=0x7f080000; public static final int ChronometerIcon=0x7f080001; public static final int MenuTheme=0x7f080002; } public static final class xml { public static final int voice_trigger_start=0x7f040000; } }
package com.sunyi.algorithm.heap; /** * <p> * 最大堆 * </p> * * @author sunyi * @date 20200615 */ public class MaxHeap { public static void main(String[] args) { int[] arr = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7}; MaxHeap maxHeap = new MaxHeap(); maxHeap.heapSort(arr); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + "_"); } } public void heapSort(int arr[]) { buildHeap(arr); int temp; for (int i = arr.length - 1; i >= 1; i--) { temp = arr[i]; arr[i] = arr[0]; arr[0] = temp; heapify(arr, i, 0); } } public void buildHeap(int[] arr) { for (int i = arr.length - 1; i >= 0; i--) { heapify(arr, arr.length, i); } } public void heapify(int[] arr, int to, int i) { int largest = i; int left = left(i); int right = right(i); if (left < to && arr[left] >= arr[largest]) { largest = left; } if (right < to && arr[right] >= arr[largest]) { largest = right; } if (largest != i) { int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; heapify(arr, to, largest); } } public int left(int i) { return 2 * (i + 1) - 1; } public int right(int i) { return 2 * (i + 1); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.metastore; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.events.AddIndexEvent; import org.apache.hadoop.hive.metastore.events.AlterIndexEvent; import org.apache.hadoop.hive.metastore.events.AddPartitionEvent; import org.apache.hadoop.hive.metastore.events.AlterPartitionEvent; import org.apache.hadoop.hive.metastore.events.AlterTableEvent; import org.apache.hadoop.hive.metastore.events.ConfigChangeEvent; import org.apache.hadoop.hive.metastore.events.CreateDatabaseEvent; import org.apache.hadoop.hive.metastore.events.CreateTableEvent; import org.apache.hadoop.hive.metastore.events.DropDatabaseEvent; import org.apache.hadoop.hive.metastore.events.DropIndexEvent; import org.apache.hadoop.hive.metastore.events.DropPartitionEvent; import org.apache.hadoop.hive.metastore.events.DropTableEvent; import org.apache.hadoop.hive.metastore.events.LoadPartitionDoneEvent; /** * This abstract class needs to be extended to provide implementation of actions that needs * to be performed when a particular event occurs on a metastore. These methods * are called whenever an event occurs on metastore. Status of the event whether * it was successful or not is contained in container event object. */ public abstract class MetaStoreEventListener implements Configurable { private Configuration conf; public MetaStoreEventListener(Configuration config){ this.conf = config; } /** * @param tableEvent table event. * @throws MetaException */ public void onConfigChange(ConfigChangeEvent tableEvent) throws MetaException { } /** * @param tableEvent table event. * @throws MetaException */ public void onCreateTable (CreateTableEvent tableEvent) throws MetaException { } /** * @param tableEvent table event. * @throws MetaException */ public void onDropTable (DropTableEvent tableEvent) throws MetaException { } /** * @param add partition event * @throws MetaException */ /** * @param tableEvent alter table event * @throws MetaException */ public void onAlterTable (AlterTableEvent tableEvent) throws MetaException { } public void onAddPartition (AddPartitionEvent partitionEvent) throws MetaException { } /** * @param partitionEvent partition event * @throws MetaException */ public void onDropPartition (DropPartitionEvent partitionEvent) throws MetaException { } /** * @param partitionEvent partition event * @throws MetaException */ public void onAlterPartition (AlterPartitionEvent partitionEvent) throws MetaException { } /** * @param dbEvent database event * @throws MetaException */ public void onCreateDatabase (CreateDatabaseEvent dbEvent) throws MetaException { } /** * @param dbEvent database event * @throws MetaException */ public void onDropDatabase (DropDatabaseEvent dbEvent) throws MetaException { } /** * @param partSetDoneEvent * @throws MetaException */ public void onLoadPartitionDone(LoadPartitionDoneEvent partSetDoneEvent) throws MetaException { } /** * @param indexEvent index event * @throws MetaException */ public void onAddIndex(AddIndexEvent indexEvent) throws MetaException { } /** * @param indexEvent index event * @throws MetaException */ public void onDropIndex(DropIndexEvent indexEvent) throws MetaException { } /** * @param indexEvent index event * @throws MetaException */ public void onAlterIndex(AlterIndexEvent indexEvent) throws MetaException { } @Override public Configuration getConf() { return this.conf; } @Override public void setConf(Configuration config) { this.conf = config; } }
/* * */ package net.community.chest.jms.framework; import javax.jms.JMSException; import javax.jms.MessageConsumer; /** * <P>Copyright 2010 as per GPLv2</P> * * @author Lyor G. * @since Jun 8, 2010 1:48:11 PM */ public interface XMessageConsumer extends MessageConsumer { void setMessageSelector (String msgSelector) throws JMSException; }
package com.zoke.ipfs.model; /** * Created by wulijie on 2018/6/6. */ public class SimpleResult { public String name; public String hash; public String url; public String size; }
package perococco.jdgen.graph; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import lombok.AccessLevel; import lombok.NonNull; import lombok.RequiredArgsConstructor; import perococco.jdgen.core.Couple; import perococco.jdgen.core.Point2D; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public final class Delaunay<O> { /** * Perform a Delaunay triangulation for a set of objects by using the * <a href="https://en.wikipedia.org/wiki/Bowyer%E2%80%93Watson_algorithm#Pseudocode">Bowyer-Watson algorithm</a> * * @param objects the objects to triangulize * @param positionGetter a method that return the position of an object * @param <O> the type of the objects * @return the list of the edge of the Delaunay triangulation */ public static <O> @NonNull ImmutableList<Couple<O>> triangulize( @NonNull ImmutableCollection<O> objects, @NonNull Function<? super O, ? extends Point2D> positionGetter) { return new Delaunay<O>(objects, positionGetter).triangulize(); } private final @NonNull ImmutableCollection<O> objects; private final @NonNull Function<? super O, ? extends Point2D> positionGetter; private final @NonNull Set<Triangle> triangulation = new HashSet<>(); private Edge[] polygon = null; private Triangle superTriangle; private ImmutableList<Couple<O>> graph; private ImmutableList<Couple<O>> triangulize() { this.createSuperTriangle(); this.addSuperTriangleToTriangulation(); objects.stream() .map(positionGetter) .forEach(point -> { findBadTrianglesAndFormPolygon(point); triangulizePolygon(point); }); this.cleanUpTriangulation(); this.constructFinalGraph(); return graph; } private void createSuperTriangle() { final var sx = objects.stream().map(positionGetter).collect(Collectors.summarizingDouble(Point2D::getX)); final var sy = objects.stream().map(positionGetter).collect(Collectors.summarizingDouble(Point2D::getY)); final var xmin = sx.getMin(); final var xmax = sx.getMax(); final var ymin = sy.getMin(); final var ymax = sy.getMax(); final var epsi = (sx.getMax() - sx.getMin()) / 5.0; final var a = Point2D.of(xmin - epsi, ymin - epsi); final var b = Point2D.of(xmin + 2 * (xmax - xmin) + 3 * epsi, ymin - epsi); final var c = Point2D.of(xmin - epsi, ymin + 2 * (ymax - ymin) + 3 * epsi); this.superTriangle = new Triangle(a, b, c); } private void addSuperTriangleToTriangulation() { this.triangulation.add(superTriangle); } private void findBadTrianglesAndFormPolygon(@NonNull Point2D pointToAdd) { final var badTriangles = triangulation.stream() .filter(t -> t.isPointInsideCircumCircle(pointToAdd)) .collect(Collectors.toSet()); final var edgeCount = badTriangles.stream() .flatMap(Triangle::edgeStream) .collect(Collectors.groupingBy(e -> e, Collectors.counting())); this.polygon = edgeCount.entrySet() .stream() .filter(e -> e.getValue() == 1) .map(Map.Entry::getKey) .distinct() .toArray(Edge[]::new); triangulation.removeAll(badTriangles); } private void triangulizePolygon(@NonNull Point2D point) { Arrays.stream(polygon).map(e -> e.createTriangle(point)).forEach(triangulation::add); } private void cleanUpTriangulation() { final ImmutableSet<Point2D> pointInSuperTri = superTriangle.getVertices(); triangulation.removeIf(t -> t.edgeStream() .flatMap(Edge::vertexStream) .anyMatch(pointInSuperTri::contains)); } private void constructFinalGraph() { final Map<Point2D, O> objectsByPosition = objects.stream().collect(Collectors.toMap(positionGetter, Function.identity())); final Function<Couple<Point2D>, Couple<O>> coupleMapper = couple -> couple.map(objectsByPosition::get); graph = triangulation.stream() .flatMap(Triangle::edgeStream) .map(Edge::getVertices) .distinct() .map(coupleMapper) .collect(ImmutableList.toImmutableList()); } }
package com.kasteca.util; import androidx.test.espresso.IdlingResource; import java.util.concurrent.atomic.AtomicInteger; public final class SimpleCountingIdlingResource implements IdlingResource { private final String mResourceName; private final AtomicInteger counter = new AtomicInteger(0); // written from main thread, read from any thread. private volatile ResourceCallback resourceCallback; /** * Creates a SimpleCountingIdlingResource * * @param resourceName the resource name this resource should report to Espresso. */ public SimpleCountingIdlingResource(String resourceName) { mResourceName = resourceName; } @Override public String getName() { return mResourceName; } @Override public boolean isIdleNow() { return counter.get() == 0; } @Override public void registerIdleTransitionCallback(ResourceCallback resourceCallback) { this.resourceCallback = resourceCallback; } /** * Increments the count of in-flight transactions to the resource being monitored. */ public void increment() { counter.getAndIncrement(); } /** * Decrements the count of in-flight transactions to the resource being monitored. * * If this operation results in the counter falling below 0 - an exception is raised. * * @throws IllegalStateException if the counter is below 0. */ public void decrement() { int counterVal = counter.decrementAndGet(); if (counterVal == 0) { // we've gone from non-zero to zero. That means we're idle now! Tell espresso. if (null != resourceCallback) { resourceCallback.onTransitionToIdle(); } } if (counterVal < 0) { throw new IllegalArgumentException("Counter has been corrupted!"); } } }
package main.java.scengen.methods; import java.util.LinkedHashMap; import java.util.Map; import main.java.scengen.distribution.MultivariateDistribution; public class MonteCarlo extends ReductionMethod { MultivariateDistribution _mvDist; public MonteCarlo (MultivariateDistribution mvDist) { _mvDist = mvDist; } @Override public Map<double[], Double> getScenarios(int numScen) { Map<double[],Double> resultMap = new LinkedHashMap<>(); for (int i=0; i<numScen; i++) resultMap.put(_mvDist.getRealization(),1./numScen); return resultMap; } }
package com.lqr.biliblili.mvp.model; import android.app.Application; import com.google.gson.Gson; import com.jess.arms.di.scope.ActivityScope; import com.jess.arms.integration.IRepositoryManager; import com.jess.arms.mvp.BaseModel; import com.lqr.biliblili.mvp.contract.MainContract; import javax.inject.Inject; @ActivityScope public class MainModel extends BaseModel implements MainContract.Model { private Gson mGson; private Application mApplication; @Inject public MainModel(IRepositoryManager repositoryManager, Gson gson, Application application) { super(repositoryManager); this.mGson = gson; this.mApplication = application; } @Override public void onDestroy() { super.onDestroy(); this.mGson = null; this.mApplication = null; } }
package toothpick.smoothie.provider; import android.app.Application; import android.content.ContentResolver; import javax.inject.Provider; public class ContentResolverProvider implements Provider<ContentResolver> { Application application; public ContentResolverProvider(Application application) { this.application = application; } @Override public ContentResolver get() { return application.getContentResolver(); } }
package net.minecraft.network; import com.viaversion.viaversion.api.platform.ViaPlatform; import net.WS; import net.aLy; import net.hZ; import net.lc; public final class NetworkManager$4 { private ViaPlatform b; private hZ a; private aLy d; private WS c; public NetworkManager$4 a(ViaPlatform var1) { this.b = var1; return this; } public NetworkManager$4 a(hZ var1) { this.a = var1; return this; } public NetworkManager$4 a(WS var1) { this.c = var1; return this; } public NetworkManager$4 a(aLy var1) { this.d = var1; return this; } public lc a() { return new lc(this.b, this.a, this.d, this.c); } }
package com.daxslab.mail.mail; import java.util.Date; import java.util.List; import java.util.Map; import android.util.Log; import com.daxslab.mail.Account; import com.daxslab.mail.K9; import com.daxslab.mail.Preferences; import com.daxslab.mail.controller.MessageRetrievalListener; public abstract class Folder { protected final Account mAccount; private String status = null; private long lastChecked = 0; private long lastPush = 0; public static final int OPEN_MODE_RW=0; public static final int OPEN_MODE_RO=1; // NONE is obsolete, it will be translated to NO_CLASS for display and to INHERITED for sync and push public enum FolderClass { NONE, NO_CLASS, INHERITED, FIRST_CLASS, SECOND_CLASS } public enum FolderType { HOLDS_FOLDERS, HOLDS_MESSAGES, } protected Folder(Account account) { mAccount = account; } /** * Forces an open of the MailProvider. If the provider is already open this * function returns without doing anything. * * @param mode READ_ONLY or READ_WRITE */ public abstract void open(int mode) throws MessagingException; /** * Forces a close of the MailProvider. Any further access will attempt to * reopen the MailProvider. */ public abstract void close(); /** * @return True if further commands are not expected to have to open the * connection. */ public abstract boolean isOpen(); /** * Get the mode the folder was opened with. This may be different than the mode the open * was requested with. * @return */ public abstract int getMode(); public abstract boolean create(FolderType type) throws MessagingException; /** * Create a new folder with a specified display limit. Not abstract to allow * remote folders to not override or worry about this call if they don't care to. */ public boolean create(FolderType type, int displayLimit) throws MessagingException { return create(type); } public abstract boolean exists() throws MessagingException; /** * @return A count of the messages in the selected folder. */ public abstract int getMessageCount() throws MessagingException; public abstract int getUnreadMessageCount() throws MessagingException; public abstract int getFlaggedMessageCount() throws MessagingException; public abstract Message getMessage(String uid) throws MessagingException; /** * Fetch the shells of messages between a range of UIDs and after a given date. * @param start UID sequence start * @param end UID sequence end * @param earliestDate Date to start on * @param listener Listener to notify as we download messages. * @return List of messages * @throws MessagingException */ public abstract Message[] getMessages(int start, int end, Date earliestDate, MessageRetrievalListener listener) throws MessagingException; /** * Fetches the given list of messages. The specified listener is notified as * each fetch completes. Messages are downloaded as (as) lightweight (as * possible) objects to be filled in with later requests. In most cases this * means that only the UID is downloaded. * @param listener Listener to notify as we download messages. * @return List of messages */ public abstract Message[] getMessages(MessageRetrievalListener listener) throws MessagingException; public Message[] getMessages(MessageRetrievalListener listener, boolean includeDeleted) throws MessagingException { return getMessages(listener); } public abstract Message[] getMessages(String[] uids, MessageRetrievalListener listener) throws MessagingException; public abstract Map<String, String> appendMessages(Message[] messages) throws MessagingException; public Map<String, String> copyMessages(Message[] msgs, Folder folder) throws MessagingException { return null; } public Map<String, String> moveMessages(Message[] msgs, Folder folder) throws MessagingException { return null; } public void delete(Message[] msgs, String trashFolderName) throws MessagingException { for (Message message : msgs) { Message myMessage = getMessage(message.getUid()); myMessage.delete(trashFolderName); } } public abstract void setFlags(Message[] messages, Flag[] flags, boolean value) throws MessagingException; public abstract void setFlags(Flag[] flags, boolean value) throws MessagingException; public abstract String getUidFromMessageId(Message message) throws MessagingException; public void expunge() throws MessagingException {} /** * Populate a list of messages based upon a FetchProfile. See {@link FetchProfile} for the things that can * be fetched. * @param messages Messages to populate * @param fp Things to download * @param listener Listener to notify as we fetch messages. * @throws MessagingException */ public abstract void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener) throws MessagingException; public void fetchPart(Message message, Part part, MessageRetrievalListener listener) throws MessagingException { // This is causing trouble. Disabled for now. See issue 1733 //throw new RuntimeException("fetchPart() not implemented."); if (K9.DEBUG) Log.d(K9.LOG_TAG, "fetchPart() not implemented."); } public abstract void delete(boolean recurse) throws MessagingException; public abstract String getName(); /** * Indicated by the server "\*" ( * OK [PERMANENTFLAGS (\Answered .. \*)] Flags permitted). that * new keywords may be created */ protected boolean mCanCreateKeywords = false; /** * * @param oldPushState * @param message * @return empty string to clear the pushState, null to leave the state as-is */ public String getNewPushState(String oldPushState, Message message) { return null; } public boolean isFlagSupported(Flag flag) { return true; } public boolean supportsFetchingFlags() { return true; } @Override public String toString() { return getName(); } public long getLastChecked() { return lastChecked; } public void setLastChecked(long lastChecked) throws MessagingException { this.lastChecked = lastChecked; } public long getLastPush() { return lastPush; } public void setLastPush(long lastCheckedDisplay) throws MessagingException { this.lastPush = lastCheckedDisplay; } public long getLastUpdate() { return Math.max(getLastChecked(), getLastPush()); } public FolderClass getDisplayClass() { return FolderClass.NO_CLASS; } public FolderClass getSyncClass() { return getDisplayClass(); } public FolderClass getPushClass() { return getSyncClass(); } public void refresh(Preferences preferences) throws MessagingException { } public boolean isInTopGroup() { return false; } public String getStatus() { return status; } public void setStatus(String status) throws MessagingException { this.status = status; } public Account getAccount() { return mAccount; } public List<Message> search(String queryString, final Flag[] requiredFlags, final Flag[] forbiddenFlags) throws MessagingException { throw new MessagingException("K-9 does not support searches on this folder type"); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dromara.soul.client.springcloud.init; import org.dromara.soul.client.core.register.SoulClientRegisterRepositoryFactory; import org.dromara.soul.register.common.config.SoulRegisterCenterConfig; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.env.Environment; import java.util.Properties; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Test case for {@link ContextRegisterListener}. * * @author kaitoShy * @author dengliming */ @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public final class ContextRegisterListenerTest { @Mock private static Environment env; @Test @Ignore public void testNotFullRegister() { Properties properties = new Properties(); SoulRegisterCenterConfig mockRegisterCenter = new SoulRegisterCenterConfig(); mockRegisterCenter.setServerLists("http://127.0.0.1:58080"); mockRegisterCenter.setRegisterType("http"); mockRegisterCenter.setProps(properties); when(env.getProperty("spring.application.name")).thenReturn("spring-cloud-test"); ContextRegisterListener contextRegisterListener = new ContextRegisterListener(mockRegisterCenter, env, SoulClientRegisterRepositoryFactory.newInstance(mockRegisterCenter)); ContextRefreshedEvent contextRefreshedEvent = mock(ContextRefreshedEvent.class); contextRegisterListener.onApplicationEvent(contextRefreshedEvent); } // @Test // public void testFullRegister() { // try (MockedStatic mocked = mockStatic(RegisterUtils.class)) { // Properties properties = new Properties(); // properties.setProperty("contextPath", "/test"); // properties.setProperty("isFull", "true"); // SoulRegisterCenterConfig mockRegisterCenter = new SoulRegisterCenterConfig(); // mockRegisterCenter.setServerLists("http://127.0.0.1:8080"); // mockRegisterCenter.setRegisterType("http"); // mockRegisterCenter.setProps(properties); // when(env.getProperty("spring.application.name")).thenReturn("spring-cloud-test"); // ContextRegisterListener contextRegisterListener = new ContextRegisterListener(mockRegisterCenter, env); // ContextRefreshedEvent contextRefreshedEvent = mock(ContextRefreshedEvent.class); // contextRegisterListener.onApplicationEvent(contextRefreshedEvent); // mocked.verify(() -> RegisterUtils.doRegister(anyString(), eq("http://127.0.0.1:8080/soul-client/springcloud-register"), eq(RpcTypeEnum.SPRING_CLOUD))); // } // } }
package mk.ukim.finki.gradespreview.security.jwt; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.util.StringUtils; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * Filters incoming requests and installs a Spring Security principal if a header corresponding to a valid user is * found. */ public class JWTFilter extends GenericFilterBean { private TokenProvider tokenProvider; public JWTFilter(TokenProvider tokenProvider) { this.tokenProvider = tokenProvider; } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String jwt = resolveToken(httpServletRequest); if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) { Authentication authentication = this.tokenProvider.getAuthentication(jwt); SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(servletRequest, servletResponse); } private String resolveToken(HttpServletRequest request){ String bearerToken = request.getHeader(JWTConfigurer.AUTHORIZATION_HEADER); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7, bearerToken.length()); } return null; } }
package scott.programming.training; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; public class Application{ public int countWords(String words){ String[] separateWords = StringUtils.split(words, ' '); return (separateWords == null) ? 0 : separateWords.length; } public void greet(){ List<String> greetings = new ArrayList<>(); greetings.add("Hello"); for (String greeting:greetings){ System.out.println("Greeting: "+greeting); } } public Application(){ System.out.println("Inside Application"); } //method main(): ALWAYS the APPLICATION entry point public static void main(String[] args){ System.out.println("Starting Application"); Application app = new Application(); app.greet(); int count = app.countWords("“Data-driven” startups are the wildcatters of the new economy: they prospect for digital oil, extract it and turn it into clever new services, from analysing X-rays and CAT scans to determining where to spray herbicide on a field."); System.out.println("Word Count: " + count); } }
package com.stephentuso.welcome.util; import android.content.Context; import androidx.annotation.AttrRes; import androidx.annotation.ColorRes; import android.util.TypedValue; /** * Created by stephentuso on 11/16/15. */ public class ColorHelper { public static int getColor(Context context, @ColorRes int resId) { return context.getResources().getColor(resId); } public static int resolveColorAttribute(Context context, @AttrRes int resId, int fallback) { TypedValue value = new TypedValue(); boolean colorFound = context.getTheme().resolveAttribute(resId, value, true); return colorFound ? value.data : fallback; } }
/* * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.helidon.webserver.examples.basics; /** * Represents a simple entity - the name. */ public class Name { private final String firstName; private final String middleName; private final String lastName; /** * An naive implementation of name parser. * * @param fullName a full name */ public Name(String fullName) { String[] split = fullName.split(" "); switch (split.length) { case 0: throw new IllegalArgumentException("An empty name"); case 1: firstName = null; middleName = null; lastName = split[0]; break; case 2: firstName = split[0]; middleName = null; lastName = split[1]; break; case 3: firstName = split[0]; middleName = split[1]; lastName = split[2]; break; default: throw new IllegalArgumentException("To many name parts!"); } } public String getFirstName() { return firstName; } public String getMiddleName() { return middleName; } public String getLastName() { return lastName; } @Override public String toString() { StringBuilder result = new StringBuilder(); if (firstName != null) { result.append(firstName); } if (middleName != null) { if (result.length() > 0) { result.append(' '); } result.append(middleName); } if (lastName != null) { if (result.length() > 0) { result.append(' '); } result.append(lastName); } return result.toString(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.benchmark.driver; import com.facebook.presto.client.ClientSession; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import io.airlift.command.Command; import io.airlift.command.HelpOption; import io.airlift.log.Logging; import io.airlift.log.Logging.Level; import io.airlift.log.LoggingConfiguration; import javax.inject.Inject; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import static com.google.common.io.ByteStreams.nullOutputStream; import static io.airlift.command.SingleCommand.singleCommand; import static java.util.function.Function.identity; @Command(name = "presto-benchmark", description = "Presto benchmark driver") public class PrestoBenchmarkDriver { @Inject public HelpOption helpOption; @Inject public BenchmarkDriverOptions benchmarkDriverOptions = new BenchmarkDriverOptions(); public static void main(String[] args) throws Exception { new PrestoBenchmarkDriver().run(args); } protected void run(String[] args) throws Exception { PrestoBenchmarkDriver prestoBenchmarkDriver = singleCommand(PrestoBenchmarkDriver.class).parse(args); if (prestoBenchmarkDriver.helpOption.showHelpIfRequested()) { return; } BenchmarkDriverOptions driverOptions = prestoBenchmarkDriver.benchmarkDriverOptions; initializeLogging(driverOptions.debug); // select suites List<Suite> suites = Suite.readSuites(new File(driverOptions.suiteConfigFile)); if (!driverOptions.suites.isEmpty()) { suites = suites.stream() .filter(suite -> driverOptions.suites.contains(suite.getName())) .collect(Collectors.toList()); } suites = ImmutableList.copyOf(suites); // load queries File queriesDir = new File(driverOptions.sqlTemplateDir); List<BenchmarkQuery> allQueries = readQueries(queriesDir); // select queries to run Set<BenchmarkQuery> queries; if (driverOptions.queries.isEmpty()) { queries = suites.stream() .map(suite -> suite.selectQueries(allQueries)) .flatMap(List::stream) .collect(Collectors.toSet()); } else { queries = driverOptions.queries.stream() .map(Pattern::compile) .map(pattern -> allQueries.stream().filter(query -> pattern.matcher(query.getName()).matches())) .flatMap(identity()) .collect(Collectors.toSet()); } // create results store BenchmarkResultsStore resultsStore = getResultsStore(suites, queries); // create session ClientSession session = driverOptions.getClientSession(); try (BenchmarkDriver benchmarkDriver = new BenchmarkDriver( resultsStore, session, queries, driverOptions.warm, driverOptions.runs, driverOptions.debug, driverOptions.maxFailures, Optional.ofNullable(driverOptions.socksProxy))) { for (Suite suite : suites) { benchmarkDriver.run(suite); } } } protected BenchmarkResultsStore getResultsStore(List<Suite> suites, Set<BenchmarkQuery> queries) { return new BenchmarkResultsPrinter(suites, queries); } private static List<BenchmarkQuery> readQueries(File queriesDir) throws IOException { File[] files = queriesDir.listFiles(); if (files == null) { return ImmutableList.of(); } ImmutableList.Builder<BenchmarkQuery> queries = ImmutableList.builder(); for (File file : files) { String fileName = file.getName(); if (fileName.endsWith(".sql")) { queries.add(new BenchmarkQuery(file)); } } return queries.build(); } @SuppressWarnings("UseOfSystemOutOrSystemErr") public static void initializeLogging(boolean debug) { // unhook out and err while initializing logging or logger will print to them PrintStream out = System.out; PrintStream err = System.err; try { if (debug) { Logging logging = Logging.initialize(); logging.configure(new LoggingConfiguration()); logging.setLevel("com.facebook.presto", Level.DEBUG); } else { System.setOut(new PrintStream(nullOutputStream())); System.setErr(new PrintStream(nullOutputStream())); Logging logging = Logging.initialize(); logging.configure(new LoggingConfiguration()); logging.disableConsole(); } } catch (IOException e) { throw Throwables.propagate(e); } finally { System.setOut(out); System.setErr(err); } } }
package unibg.se4med; import org.json.JSONObject; import p3d4amb.sat.lib.shapes.ShapeSize; import p3d4amb.sat.lib.shapes.ImageShape.ImageSet; import se4med.json.BreakoutJson; import se4med.json.StereoacuityTestJson; public class DefaultAppSettings { public static String stereoTestSettings = new JSONObject().put(StereoacuityTestJson.imageSet, ImageSet.TNO) .put(StereoacuityTestJson.shapeSize, ShapeSize.MEDIUM).put(StereoacuityTestJson.stripes, false) .put(StereoacuityTestJson.nullImage, false).put(StereoacuityTestJson.screenInches, 20) .put(StereoacuityTestJson.monitorDistance, 40).put(StereoacuityTestJson.startingLevel, 6) .put(StereoacuityTestJson.changePosition, false).toString(); // BREAKOUT JSON EXAMPLE // {"name":"user11","difficulty":"0","colored":"1100","rightLensCol":"0","eye":"0","colorChange":"50", // "maxColor":255,"sound":"0","effects":"0","startingColor":"0.25","endingColor":"0.75"} public static String breakoutSettings = new JSONObject().put(BreakoutJson.difficulty, new String("0")) .put(BreakoutJson.startingColor, new String("0")).put(BreakoutJson.endingColor, new String("1")) .put(BreakoutJson.colored, new String("1000"))// Only ball is colored .put(BreakoutJson.rightLensCol, new String("0")).put(BreakoutJson.eye, new String("0")) .put(BreakoutJson.colorChange, new String("50")).put(BreakoutJson.maxColor, new String("255")) .put(BreakoutJson.effects, new String("0")).put(BreakoutJson.sound, new String("0")).toString(); public String getDefaultSettings(String id) { switch (id) { case "StereoTest": return stereoTestSettings; case "Breakout": return breakoutSettings; default: return ""; } } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|scheduler operator|. name|fair package|; end_package begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|Priority import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|Resource import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|ResourceRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|scheduler operator|. name|ClusterNodeTracker import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashSet import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_comment comment|/** * Applications place {@link ResourceRequest}s at multiple levels. This is a * helper class that allows tracking if a {@link ResourceRequest} has been * visited at a different locality level. * * This is implemented for {@link FSAppAttempt#getStarvedResourceRequests()}. * The implementation is not thread-safe. */ end_comment begin_class DECL|class|VisitedResourceRequestTracker class|class name|VisitedResourceRequestTracker block|{ DECL|field|LOG specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|VisitedResourceRequestTracker operator|. name|class argument_list|) decl_stmt|; DECL|field|map specifier|private specifier|final name|Map argument_list|< name|Priority argument_list|, name|Map argument_list|< name|Resource argument_list|, name|TrackerPerPriorityResource argument_list|> argument_list|> name|map init|= operator|new name|HashMap argument_list|<> argument_list|() decl_stmt|; DECL|field|nodeTracker specifier|private specifier|final name|ClusterNodeTracker argument_list|< name|FSSchedulerNode argument_list|> name|nodeTracker decl_stmt|; DECL|method|VisitedResourceRequestTracker ( ClusterNodeTracker<FSSchedulerNode> nodeTracker) name|VisitedResourceRequestTracker parameter_list|( name|ClusterNodeTracker argument_list|< name|FSSchedulerNode argument_list|> name|nodeTracker parameter_list|) block|{ name|this operator|. name|nodeTracker operator|= name|nodeTracker expr_stmt|; block|} comment|/** * Check if the {@link ResourceRequest} is visited before, and track it. * @param rr {@link ResourceRequest} to visit * @return true if<code>rr</code> is the first visit across all * locality levels, false otherwise */ DECL|method|visit (ResourceRequest rr) name|boolean name|visit parameter_list|( name|ResourceRequest name|rr parameter_list|) block|{ name|Priority name|priority init|= name|rr operator|. name|getPriority argument_list|() decl_stmt|; name|Resource name|capability init|= name|rr operator|. name|getCapability argument_list|() decl_stmt|; name|Map argument_list|< name|Resource argument_list|, name|TrackerPerPriorityResource argument_list|> name|subMap init|= name|map operator|. name|get argument_list|( name|priority argument_list|) decl_stmt|; if|if condition|( name|subMap operator|== literal|null condition|) block|{ name|subMap operator|= operator|new name|HashMap argument_list|<> argument_list|() expr_stmt|; name|map operator|. name|put argument_list|( name|priority argument_list|, name|subMap argument_list|) expr_stmt|; block|} name|TrackerPerPriorityResource name|tracker init|= name|subMap operator|. name|get argument_list|( name|capability argument_list|) decl_stmt|; if|if condition|( name|tracker operator|== literal|null condition|) block|{ name|tracker operator|= operator|new name|TrackerPerPriorityResource argument_list|() expr_stmt|; name|subMap operator|. name|put argument_list|( name|capability argument_list|, name|tracker argument_list|) expr_stmt|; block|} return|return name|tracker operator|. name|visit argument_list|( name|rr operator|. name|getResourceName argument_list|() argument_list|) return|; block|} DECL|class|TrackerPerPriorityResource specifier|private class|class name|TrackerPerPriorityResource block|{ DECL|field|racksWithNodesVisited specifier|private name|Set argument_list|< name|String argument_list|> name|racksWithNodesVisited init|= operator|new name|HashSet argument_list|<> argument_list|() decl_stmt|; DECL|field|racksVisted specifier|private name|Set argument_list|< name|String argument_list|> name|racksVisted init|= operator|new name|HashSet argument_list|<> argument_list|() decl_stmt|; DECL|field|anyVisited specifier|private name|boolean name|anyVisited decl_stmt|; DECL|method|visitAny () specifier|private name|boolean name|visitAny parameter_list|() block|{ if|if condition|( name|racksVisted operator|. name|isEmpty argument_list|() operator|&& name|racksWithNodesVisited operator|. name|isEmpty argument_list|() condition|) block|{ name|anyVisited operator|= literal|true expr_stmt|; block|} return|return name|anyVisited return|; block|} DECL|method|visitRack (String rackName) specifier|private name|boolean name|visitRack parameter_list|( name|String name|rackName parameter_list|) block|{ if|if condition|( name|anyVisited operator||| name|racksWithNodesVisited operator|. name|contains argument_list|( name|rackName argument_list|) condition|) block|{ return|return literal|false return|; block|} else|else block|{ name|racksVisted operator|. name|add argument_list|( name|rackName argument_list|) expr_stmt|; return|return literal|true return|; block|} block|} DECL|method|visitNode (String rackName) specifier|private name|boolean name|visitNode parameter_list|( name|String name|rackName parameter_list|) block|{ if|if condition|( name|anyVisited operator||| name|racksVisted operator|. name|contains argument_list|( name|rackName argument_list|) condition|) block|{ return|return literal|false return|; block|} else|else block|{ name|racksWithNodesVisited operator|. name|add argument_list|( name|rackName argument_list|) expr_stmt|; return|return literal|true return|; block|} block|} comment|/** * Based on whether<code>resourceName</code> is a node, rack or ANY, * check if this has been visited earlier. * * A node is considered visited if its rack or ANY have been visited. * A rack is considered visited if any nodes or ANY have been visited. * Any is considered visited if any of the nodes/racks have been visited. * * @param resourceName nodename or rackname or ANY * @return true if this is the first visit, false otherwise */ DECL|method|visit (String resourceName) specifier|private name|boolean name|visit parameter_list|( name|String name|resourceName parameter_list|) block|{ if|if condition|( name|resourceName operator|. name|equals argument_list|( name|ResourceRequest operator|. name|ANY argument_list|) condition|) block|{ return|return name|visitAny argument_list|() return|; block|} name|List argument_list|< name|FSSchedulerNode argument_list|> name|nodes init|= name|nodeTracker operator|. name|getNodesByResourceName argument_list|( name|resourceName argument_list|) decl_stmt|; name|int name|numNodes init|= name|nodes operator|. name|size argument_list|() decl_stmt|; if|if condition|( name|numNodes operator|== literal|0 condition|) block|{ name|LOG operator|. name|error argument_list|( literal|"Found ResourceRequest for a non-existent node/rack named " operator|+ name|resourceName argument_list|) expr_stmt|; return|return literal|false return|; block|} if|if condition|( name|numNodes operator|== literal|1 condition|) block|{ comment|// Found a single node. To be safe, let us verify it is a node and comment|// not a rack with a single node. name|FSSchedulerNode name|node init|= name|nodes operator|. name|get argument_list|( literal|0 argument_list|) decl_stmt|; if|if condition|( name|node operator|. name|getNodeName argument_list|() operator|. name|equals argument_list|( name|resourceName argument_list|) condition|) block|{ return|return name|visitNode argument_list|( name|node operator|. name|getRackName argument_list|() argument_list|) return|; block|} block|} comment|// At this point, it is not ANY or a node. Must be a rack return|return name|visitRack argument_list|( name|resourceName argument_list|) return|; block|} block|} block|} end_class end_unit
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.test.mock.mockito; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.example.ExampleService; import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; import org.springframework.boot.test.mock.mockito.example.FailingExampleService; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; /** * Test {@link MockBean @MockBean} on a test class can be used to replace existing beans. * * @author Phillip Webb */ @ExtendWith(SpringExtension.class) @MockBean(ExampleService.class) class MockBeanOnTestClassForExistingBeanIntegrationTests { @Autowired private ExampleServiceCaller caller; @Test void testMocking() { given(this.caller.getService().greeting()).willReturn("Boot"); assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); } @Configuration(proxyBeanMethods = false) @Import({ ExampleServiceCaller.class, FailingExampleService.class }) static class Config { } }
package com.dscglbajaj.lunchboxpartner.models; public class Distributor { private String name; private String hostelName; private int status; }
import org.junit.Test; import javax.swing.*; import java.io.File; import static org.junit.Assert.*; public class SearchAllForWordWorkerTest { File fileName = new File("C:\\Users\\Mathe\\Documents\\SCHOOL\\Test Folder\\big.txt"); @Test public void Tester() throws Exception { JTextArea jA = new JTextArea(""); SearchAllForWordWorker s1 = new SearchAllForWordWorker("ebook",fileName,jA,false,false,0); s1.searchForWordCase(fileName,""); s1.searchForWholeWord(fileName,""); String dir = "" + s1.checkDir(); String expectedDir = "C:\\Users\\Mathe\\Documents\\SCHOOL\\Test Folder\\big.txt"; boolean test1 = s1.checkSearchWholeWord(); boolean test2 = s1.checkSearchWordCase(); boolean expected1 = true; /** DUE TO SOME VALUES THAT ARE EXCLUDED*/ boolean expected2 = true; assertEquals(expectedDir,dir); assertEquals(expected1,test1); assertEquals(expected2,test2); } }
package io.muun.apollo.data.net.base; import io.muun.apollo.data.logging.LoggingRequestTracker; import io.muun.apollo.data.serialization.SerializationUtils; import io.muun.apollo.domain.errors.AmountTooSmallError; import io.muun.apollo.domain.errors.CountryNotSupportedError; import io.muun.apollo.domain.errors.DeprecatedClientVersionError; import io.muun.apollo.domain.errors.EmailAlreadyUsedError; import io.muun.apollo.domain.errors.EmailNotRegisteredError; import io.muun.apollo.domain.errors.ExchangeRateWindowTooOldError; import io.muun.apollo.domain.errors.ExpiredActionLinkError; import io.muun.apollo.domain.errors.ExpiredSessionError; import io.muun.apollo.domain.errors.ExpiredVerificationCodeError; import io.muun.apollo.domain.errors.IncorrectPasswordError; import io.muun.apollo.domain.errors.InsufficientFundsError; import io.muun.apollo.domain.errors.InvalidActionLinkError; import io.muun.apollo.domain.errors.InvalidAddressError; import io.muun.apollo.domain.errors.InvalidChallengeSignatureError; import io.muun.apollo.domain.errors.InvalidJsonError; import io.muun.apollo.domain.errors.InvalidPhoneNumberError; import io.muun.apollo.domain.errors.InvalidRecoveryCodeV2Error; import io.muun.apollo.domain.errors.InvalidVerificationCodeError; import io.muun.apollo.domain.errors.PhoneNumberAlreadyUsedError; import io.muun.apollo.domain.errors.RevokedVerificationCodeError; import io.muun.apollo.domain.errors.TooManyRequestsError; import io.muun.apollo.domain.errors.TooManyWrongVerificationCodesError; import io.muun.common.Optional; import io.muun.common.api.error.Error; import io.muun.common.exception.HttpException; import io.muun.common.net.HeaderUtils; import io.muun.common.net.NetworkRetry; import io.muun.common.net.ServerRetry; import io.muun.common.rx.ObservableFn; import androidx.annotation.NonNull; import com.fasterxml.jackson.core.JsonProcessingException; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.CallAdapter; import retrofit2.Invocation; import rx.Completable; import rx.Observable; import rx.Observable.Transformer; import rx.Single; import timber.log.Timber; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Map; import java.util.UUID; import javax.validation.constraints.NotNull; public class RxCallAdapterWrapper<R> implements CallAdapter<R, Object> { private static final Transformer HTTP_EXCEPTION_TRANSFORMER; private static final Transformer JSON_DESERIALIZATION_TRANSFORMER; private static final Transformer IO_EXCEPTION_TRANSFORMER; private static final Transformer SPECIAL_HTTP_EXCEPTIONS_TRANSFORMER; static { HTTP_EXCEPTION_TRANSFORMER = ObservableFn.replaceTypedError( retrofit2.HttpException.class, error -> { final Error apiError = deserializeApiError(error).orElse(null); final String idempotencyKey = error.response().raw().request() .header(HeaderUtils.IDEMPOTENCY_KEY); if (idempotencyKey != null) { LoggingRequestTracker.INSTANCE .reportRecentErrorResponse(idempotencyKey, apiError); } if (apiError != null && error.code() < 500) { // We managed to parse a valid APIError that corresponds to a client-side // failure. Upper layers may want to react appropriately: return new HttpException(apiError); } else { // Server-side failures are not very useful to differentiate in Apollo. We // emit a single class with a predefined message: return new ServerFailureException(error); } } ); // Jackson's Json deserialization errors are all IOExceptions, but don't want to retry // since they won't succeed unless we fix the (code) problem. Also, let's throw a specific // error so we can handle it separately. JSON_DESERIALIZATION_TRANSFORMER = ObservableFn.replaceTypedError( JsonProcessingException.class, InvalidJsonError::new ); // Use replaceTypedErrorExact to avoid replacing Jackson errors (subclasses of IOException) // TODO find a better way to deal with this? IO_EXCEPTION_TRANSFORMER = ObservableFn.replaceTypedErrorExact( IOException.class, NetworkException::new ); SPECIAL_HTTP_EXCEPTIONS_TRANSFORMER = ObservableFn.replaceTypedError( HttpException.class, error -> { switch (error.getErrorCode()) { case DEPRECATED_CLIENT_VERSION: return new DeprecatedClientVersionError(); case EXPIRED_SESSION: return new ExpiredSessionError(); case INVALID_PHONE_NUMBER: return new InvalidPhoneNumberError(); case COUNTRY_NOT_SUPPORTED: return new CountryNotSupportedError(); case INVALID_VERIFICATION_CODE: return new InvalidVerificationCodeError(); case REVOKED_VERIFICATION_CODE: return new RevokedVerificationCodeError(); case EXPIRED_VERIFICATION_CODE: return new ExpiredVerificationCodeError(); case TOO_MANY_WRONG_VERIFICATION_CODES: return new TooManyWrongVerificationCodesError(); // that's a mouthful :) case PHONE_NUMBER_ALREADY_USED: return new PhoneNumberAlreadyUsedError(); case EMAIL_ALREADY_USED: return new EmailAlreadyUsedError(); case EMAIL_NOT_REGISTERED: return new EmailNotRegisteredError(); case INSUFFICIENT_CLIENT_FUNDS: return new InsufficientFundsError(); case INVALID_ADDRESS: return new InvalidAddressError(); case INVALID_PASSWORD: return new IncorrectPasswordError(); case INVALID_CHALLENGE_SIGNATURE: return new InvalidChallengeSignatureError(); case AMOUNT_SMALLER_THAN_DUST: return new AmountTooSmallError(-1); // symbolic, this shouldn't happen case EXCHANGE_RATE_WINDOW_TOO_OLD: return new ExchangeRateWindowTooOldError(); case EMAIL_LINK_EXPIRED: return new ExpiredActionLinkError(); case EMAIL_LINK_INVALID: return new InvalidActionLinkError(); case RECOVERY_CODE_V2_NOT_SET_UP: return new InvalidRecoveryCodeV2Error(); case HTTP_TOO_MANY_REQUESTS: return new TooManyRequestsError(); default: return error; } } ); } private static Optional<Error> deserializeApiError(retrofit2.HttpException error) { try { final ResponseBody responseBody = error.response().errorBody(); if (responseBody == null) { return Optional.empty(); } final Error apiError = SerializationUtils.deserializeJson( Error.class, responseBody.string() ); return Optional.of(apiError); } catch (IOException | IllegalArgumentException ignored) { // This HTTP response doesn't seem generated by Houston. Perhaps a proxy // or reverse-proxy failed to deliver the request. Timber.e(error); return Optional.empty(); } } private final CallAdapter<R, ?> wrapped; private final Map<Long, String> idempotencyKeyForThreadHack; private final boolean isSingle; private final boolean isCompletable; /** * Constructor. */ public RxCallAdapterWrapper( CallAdapter<R, ?> wrapped, Map<Long, String> idempotencyKeyForThreadHack, boolean isSingle, boolean isCompletable) { this.wrapped = wrapped; this.idempotencyKeyForThreadHack = idempotencyKeyForThreadHack; this.isSingle = isSingle; this.isCompletable = isCompletable; } @Override public Type responseType() { return wrapped.responseType(); } @SuppressWarnings("unchecked") @Override public Object adapt(@NonNull Call<R> call) { final String url = call.request().url().toString(); final String idempotencyKey = UUID.randomUUID().toString(); // In order to use the same idempotency key for all the retries in the same request chain, // we need to relate all the calls in the idempotency key header interceptor. This is // difficult because the retry logic is done at the call adapter level (retrofit), and the // idempotency key header is added at the interceptor level (okhttp). // // Since retrofit doesn't expose any hook into the request creation process, we can't send // any information from the call adapter to the interceptor through the request object, as // recommended here: // https://publicobject.com/2016/01/17/sneaking-data-into-an-okhttp-interceptor/ // // To circumvent this limitation, we make an awful hack: each time we re-subscribe to the // observer (ie. on each retry), we keep track of the thread id and annotate it with the // idempotency key. Since we know that the interceptor will be run in the same thread, we // can ask for the key annotated for the thread in which the interceptor is being run. final NetworkRetry networkRetryConfig = getAnnotation(call, NetworkRetry.class); final ServerRetry serverRetryConfig = getAnnotation(call, ServerRetry.class); final HttpRetryTransformer retryTransformer = new HttpRetryTransformer( networkRetryConfig, serverRetryConfig ); final Transformer attachUrlTransformer = ObservableFn.replaceTypedError( NetworkException.class, original -> new NetworkException(url, original) ); final Observable<?> result = getRequestObservable(call) .doOnSubscribe(() -> idempotencyKeyForThreadHack.put( Thread.currentThread().getId(), idempotencyKey )) .compose(HTTP_EXCEPTION_TRANSFORMER) .compose(SPECIAL_HTTP_EXCEPTIONS_TRANSFORMER) .compose(JSON_DESERIALIZATION_TRANSFORMER) .compose(IO_EXCEPTION_TRANSFORMER) .compose(retryTransformer) .compose(attachUrlTransformer) .doOnNext(ignored -> reportSuccessResponse(idempotencyKey)); return getResponseObservable(result); } private void reportSuccessResponse(String idempotencyKey) { LoggingRequestTracker.INSTANCE.reportRecentSuccessResponse(idempotencyKey); } @SuppressWarnings("unchecked") private Observable<?> getRequestObservable(@NotNull Call<R> call) { if (isSingle) { return ((CallAdapter<R, Single>) wrapped).adapt(call).toObservable(); } if (isCompletable) { return ((CallAdapter<R, Completable>) wrapped).adapt(call).toObservable(); } return ((CallAdapter<R, Observable>) wrapped).adapt(call); } private Object getResponseObservable(Observable<?> result) { if (isSingle) { return result.toSingle(); } if (isCompletable) { return result.toCompletable(); } return result; } private <T extends Annotation> T getAnnotation(final Call<R> call, final Class<T> aClass) { final Invocation invocation = call.request().tag(Invocation.class); if (invocation != null) { return invocation.method().getAnnotation(aClass); } return null; } }
package org.competition.leetcode.linkedlist; public class DeleteNthNode { public ListNode twoPointerApproach(ListNode head, int n) { ListNode dummy = new ListNode(0, head); ListNode first = dummy; ListNode second = dummy; for(int i=0;i<n+1;i++) { first = first.next();// measure N steps } while(first != null) { first = first.next();// measure till end second = second.next();// will go from (end - N) } second.next(second.next().next()); return dummy.next(); } public ListNode deleteNthNodeFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0); dummy.next(head); int length = 0; ListNode first = head; while (first != null) { length++; first = first.next(); } length = length - n; first = dummy; while (length > 0) { length--; first = first.next(); } first.next(first.next().next()); return dummy.next(); } }
/* * Copyright (c) 2016 Nick Guo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.nick.hook.android.media; import android.mtp.MtpConstants; import java.util.HashMap; import java.util.Locale; import dev.nick.hook.annotation.CopyFrom; /** * MediaScanner helper class. */ @CopyFrom("android.media.MediaFile") public class MediaFile { // Audio file types public static final int FILE_TYPE_MP3 = 1; public static final int FILE_TYPE_M4A = 2; public static final int FILE_TYPE_WAV = 3; public static final int FILE_TYPE_AMR = 4; public static final int FILE_TYPE_AWB = 5; public static final int FILE_TYPE_WMA = 6; public static final int FILE_TYPE_OGG = 7; public static final int FILE_TYPE_AAC = 8; public static final int FILE_TYPE_MKA = 9; public static final int FILE_TYPE_FLAC = 10; private static final int FIRST_AUDIO_FILE_TYPE = FILE_TYPE_MP3; private static final int LAST_AUDIO_FILE_TYPE = FILE_TYPE_FLAC; // MIDI file types public static final int FILE_TYPE_MID = 11; public static final int FILE_TYPE_SMF = 12; public static final int FILE_TYPE_IMY = 13; private static final int FIRST_MIDI_FILE_TYPE = FILE_TYPE_MID; private static final int LAST_MIDI_FILE_TYPE = FILE_TYPE_IMY; // Video file types public static final int FILE_TYPE_MP4 = 21; public static final int FILE_TYPE_M4V = 22; public static final int FILE_TYPE_3GPP = 23; public static final int FILE_TYPE_3GPP2 = 24; public static final int FILE_TYPE_WMV = 25; public static final int FILE_TYPE_ASF = 26; public static final int FILE_TYPE_MKV = 27; public static final int FILE_TYPE_MP2TS = 28; public static final int FILE_TYPE_AVI = 29; public static final int FILE_TYPE_WEBM = 30; private static final int FIRST_VIDEO_FILE_TYPE = FILE_TYPE_MP4; private static final int LAST_VIDEO_FILE_TYPE = FILE_TYPE_WEBM; // More video file types public static final int FILE_TYPE_MP2PS = 200; private static final int FIRST_VIDEO_FILE_TYPE2 = FILE_TYPE_MP2PS; private static final int LAST_VIDEO_FILE_TYPE2 = FILE_TYPE_MP2PS; // Image file types public static final int FILE_TYPE_JPEG = 31; public static final int FILE_TYPE_GIF = 32; public static final int FILE_TYPE_PNG = 33; public static final int FILE_TYPE_BMP = 34; public static final int FILE_TYPE_WBMP = 35; public static final int FILE_TYPE_WEBP = 36; private static final int FIRST_IMAGE_FILE_TYPE = FILE_TYPE_JPEG; private static final int LAST_IMAGE_FILE_TYPE = FILE_TYPE_WEBP; // Playlist file types public static final int FILE_TYPE_M3U = 41; public static final int FILE_TYPE_PLS = 42; public static final int FILE_TYPE_WPL = 43; public static final int FILE_TYPE_HTTPLIVE = 44; private static final int FIRST_PLAYLIST_FILE_TYPE = FILE_TYPE_M3U; private static final int LAST_PLAYLIST_FILE_TYPE = FILE_TYPE_HTTPLIVE; // Drm file types public static final int FILE_TYPE_FL = 51; private static final int FIRST_DRM_FILE_TYPE = FILE_TYPE_FL; private static final int LAST_DRM_FILE_TYPE = FILE_TYPE_FL; // Other popular file types public static final int FILE_TYPE_TEXT = 100; public static final int FILE_TYPE_HTML = 101; public static final int FILE_TYPE_PDF = 102; public static final int FILE_TYPE_XML = 103; public static final int FILE_TYPE_MS_WORD = 104; public static final int FILE_TYPE_MS_EXCEL = 105; public static final int FILE_TYPE_MS_POWERPOINT = 106; public static final int FILE_TYPE_ZIP = 107; public static class MediaFileType { public final int fileType; public final String mimeType; MediaFileType(int fileType, String mimeType) { this.fileType = fileType; this.mimeType = mimeType; } } private static final HashMap<String, MediaFileType> sFileTypeMap = new HashMap<String, MediaFileType>(); private static final HashMap<String, Integer> sMimeTypeMap = new HashMap<String, Integer>(); // maps file extension to MTP format code private static final HashMap<String, Integer> sFileTypeToFormatMap = new HashMap<String, Integer>(); // maps mime type to MTP format code private static final HashMap<String, Integer> sMimeTypeToFormatMap = new HashMap<String, Integer>(); // maps MTP format code to mime type private static final HashMap<Integer, String> sFormatToMimeTypeMap = new HashMap<Integer, String>(); static void addFileType(String extension, int fileType, String mimeType) { sFileTypeMap.put(extension, new MediaFileType(fileType, mimeType)); sMimeTypeMap.put(mimeType, Integer.valueOf(fileType)); } static void addFileType(String extension, int fileType, String mimeType, int mtpFormatCode) { addFileType(extension, fileType, mimeType); sFileTypeToFormatMap.put(extension, Integer.valueOf(mtpFormatCode)); sMimeTypeToFormatMap.put(mimeType, Integer.valueOf(mtpFormatCode)); sFormatToMimeTypeMap.put(mtpFormatCode, mimeType); } static { addFileType("MP3", FILE_TYPE_MP3, "audio/mpeg", MtpConstants.FORMAT_MP3); addFileType("MPGA", FILE_TYPE_MP3, "audio/mpeg", MtpConstants.FORMAT_MP3); addFileType("M4A", FILE_TYPE_M4A, "audio/mp4", MtpConstants.FORMAT_MPEG); addFileType("WAV", FILE_TYPE_WAV, "audio/x-wav", MtpConstants.FORMAT_WAV); addFileType("AMR", FILE_TYPE_AMR, "audio/amr"); addFileType("AWB", FILE_TYPE_AWB, "audio/amr-wb"); addFileType("WMA", FILE_TYPE_WMA, "audio/x-ms-wma", MtpConstants.FORMAT_WMA); addFileType("OGG", FILE_TYPE_OGG, "audio/ogg", MtpConstants.FORMAT_OGG); addFileType("OGG", FILE_TYPE_OGG, "application/ogg", MtpConstants.FORMAT_OGG); addFileType("OGA", FILE_TYPE_OGG, "application/ogg", MtpConstants.FORMAT_OGG); addFileType("AAC", FILE_TYPE_AAC, "audio/aac", MtpConstants.FORMAT_AAC); addFileType("AAC", FILE_TYPE_AAC, "audio/aac-adts", MtpConstants.FORMAT_AAC); addFileType("MKA", FILE_TYPE_MKA, "audio/x-matroska"); addFileType("MID", FILE_TYPE_MID, "audio/midi"); addFileType("MIDI", FILE_TYPE_MID, "audio/midi"); addFileType("XMF", FILE_TYPE_MID, "audio/midi"); addFileType("RTTTL", FILE_TYPE_MID, "audio/midi"); addFileType("SMF", FILE_TYPE_SMF, "audio/sp-midi"); addFileType("IMY", FILE_TYPE_IMY, "audio/imelody"); addFileType("RTX", FILE_TYPE_MID, "audio/midi"); addFileType("OTA", FILE_TYPE_MID, "audio/midi"); addFileType("MXMF", FILE_TYPE_MID, "audio/midi"); addFileType("MPEG", FILE_TYPE_MP4, "video/mpeg", MtpConstants.FORMAT_MPEG); addFileType("MPG", FILE_TYPE_MP4, "video/mpeg", MtpConstants.FORMAT_MPEG); addFileType("MP4", FILE_TYPE_MP4, "video/mp4", MtpConstants.FORMAT_MPEG); addFileType("M4V", FILE_TYPE_M4V, "video/mp4", MtpConstants.FORMAT_MPEG); addFileType("3GP", FILE_TYPE_3GPP, "video/3gpp", MtpConstants.FORMAT_3GP_CONTAINER); addFileType("3GPP", FILE_TYPE_3GPP, "video/3gpp", MtpConstants.FORMAT_3GP_CONTAINER); addFileType("3G2", FILE_TYPE_3GPP2, "video/3gpp2", MtpConstants.FORMAT_3GP_CONTAINER); addFileType("3GPP2", FILE_TYPE_3GPP2, "video/3gpp2", MtpConstants.FORMAT_3GP_CONTAINER); addFileType("MKV", FILE_TYPE_MKV, "video/x-matroska"); addFileType("WEBM", FILE_TYPE_WEBM, "video/webm"); addFileType("TS", FILE_TYPE_MP2TS, "video/mp2ts"); addFileType("AVI", FILE_TYPE_AVI, "video/avi"); addFileType("WMV", FILE_TYPE_WMV, "video/x-ms-wmv", MtpConstants.FORMAT_WMV); addFileType("ASF", FILE_TYPE_ASF, "video/x-ms-asf"); addFileType("JPG", FILE_TYPE_JPEG, "image/jpeg", MtpConstants.FORMAT_EXIF_JPEG); addFileType("JPEG", FILE_TYPE_JPEG, "image/jpeg", MtpConstants.FORMAT_EXIF_JPEG); addFileType("GIF", FILE_TYPE_GIF, "image/gif", MtpConstants.FORMAT_GIF); addFileType("PNG", FILE_TYPE_PNG, "image/png", MtpConstants.FORMAT_PNG); addFileType("BMP", FILE_TYPE_BMP, "image/x-ms-bmp", MtpConstants.FORMAT_BMP); addFileType("WBMP", FILE_TYPE_WBMP, "image/vnd.wap.wbmp"); addFileType("WEBP", FILE_TYPE_WEBP, "image/webp"); addFileType("M3U", FILE_TYPE_M3U, "audio/x-mpegurl", MtpConstants.FORMAT_M3U_PLAYLIST); addFileType("M3U", FILE_TYPE_M3U, "application/x-mpegurl", MtpConstants.FORMAT_M3U_PLAYLIST); addFileType("PLS", FILE_TYPE_PLS, "audio/x-scpls", MtpConstants.FORMAT_PLS_PLAYLIST); addFileType("WPL", FILE_TYPE_WPL, "application/vnd.ms-wpl", MtpConstants.FORMAT_WPL_PLAYLIST); addFileType("M3U8", FILE_TYPE_HTTPLIVE, "application/vnd.apple.mpegurl"); addFileType("M3U8", FILE_TYPE_HTTPLIVE, "audio/mpegurl"); addFileType("M3U8", FILE_TYPE_HTTPLIVE, "audio/x-mpegurl"); addFileType("FL", FILE_TYPE_FL, "application/x-android-drm-fl"); addFileType("TXT", FILE_TYPE_TEXT, "text/plain", MtpConstants.FORMAT_TEXT); addFileType("HTM", FILE_TYPE_HTML, "text/html", MtpConstants.FORMAT_HTML); addFileType("HTML", FILE_TYPE_HTML, "text/html", MtpConstants.FORMAT_HTML); addFileType("PDF", FILE_TYPE_PDF, "application/pdf"); addFileType("DOC", FILE_TYPE_MS_WORD, "application/msword", MtpConstants.FORMAT_MS_WORD_DOCUMENT); addFileType("XLS", FILE_TYPE_MS_EXCEL, "application/vnd.ms-excel", MtpConstants.FORMAT_MS_EXCEL_SPREADSHEET); addFileType("PPT", FILE_TYPE_MS_POWERPOINT, "application/mspowerpoint", MtpConstants.FORMAT_MS_POWERPOINT_PRESENTATION); addFileType("FLAC", FILE_TYPE_FLAC, "audio/flac", MtpConstants.FORMAT_FLAC); addFileType("ZIP", FILE_TYPE_ZIP, "application/zip"); addFileType("MPG", FILE_TYPE_MP2PS, "video/mp2p"); addFileType("MPEG", FILE_TYPE_MP2PS, "video/mp2p"); } public static boolean isAudioFileType(int fileType) { return ((fileType >= FIRST_AUDIO_FILE_TYPE && fileType <= LAST_AUDIO_FILE_TYPE) || (fileType >= FIRST_MIDI_FILE_TYPE && fileType <= LAST_MIDI_FILE_TYPE)); } public static boolean isVideoFileType(int fileType) { return (fileType >= FIRST_VIDEO_FILE_TYPE && fileType <= LAST_VIDEO_FILE_TYPE) || (fileType >= FIRST_VIDEO_FILE_TYPE2 && fileType <= LAST_VIDEO_FILE_TYPE2); } public static boolean isImageFileType(int fileType) { return (fileType >= FIRST_IMAGE_FILE_TYPE && fileType <= LAST_IMAGE_FILE_TYPE); } public static boolean isPlayListFileType(int fileType) { return (fileType >= FIRST_PLAYLIST_FILE_TYPE && fileType <= LAST_PLAYLIST_FILE_TYPE); } public static boolean isDrmFileType(int fileType) { return (fileType >= FIRST_DRM_FILE_TYPE && fileType <= LAST_DRM_FILE_TYPE); } public static MediaFileType getFileType(String path) { int lastDot = path.lastIndexOf('.'); if (lastDot < 0) return null; return sFileTypeMap.get(path.substring(lastDot + 1).toUpperCase(Locale.ROOT)); } public static boolean isMimeTypeMedia(String mimeType) { int fileType = getFileTypeForMimeType(mimeType); return isAudioFileType(fileType) || isVideoFileType(fileType) || isImageFileType(fileType) || isPlayListFileType(fileType); } // generates a title based on file name public static String getFileTitle(String path) { // extract file name after last slash int lastSlash = path.lastIndexOf('/'); if (lastSlash >= 0) { lastSlash++; if (lastSlash < path.length()) { path = path.substring(lastSlash); } } // truncate the file extension (if any) int lastDot = path.lastIndexOf('.'); if (lastDot > 0) { path = path.substring(0, lastDot); } return path; } public static int getFileTypeForMimeType(String mimeType) { Integer value = sMimeTypeMap.get(mimeType); return (value == null ? 0 : value.intValue()); } public static String getMimeTypeForFile(String path) { MediaFileType mediaFileType = getFileType(path); return (mediaFileType == null ? null : mediaFileType.mimeType); } public static int getFormatCode(String fileName, String mimeType) { if (mimeType != null) { Integer value = sMimeTypeToFormatMap.get(mimeType); if (value != null) { return value.intValue(); } } int lastDot = fileName.lastIndexOf('.'); if (lastDot > 0) { String extension = fileName.substring(lastDot + 1).toUpperCase(Locale.ROOT); Integer value = sFileTypeToFormatMap.get(extension); if (value != null) { return value.intValue(); } } return MtpConstants.FORMAT_UNDEFINED; } public static String getMimeTypeForFormatCode(int formatCode) { return sFormatToMimeTypeMap.get(formatCode); } }
/* Tencent is pleased to support the open source community by making Hippy available. * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencent.mtt.hippy.serialization.exception; @SuppressWarnings("unused") public class DataCloneOutOfRangeException extends DataCloneOutOfValueException { public DataCloneOutOfRangeException(int excepted) { super(excepted); } }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.kythe.common; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; public class FormattingLogger { private Logger logger; public FormattingLogger() { this(Logger.getAnonymousLogger()); } public FormattingLogger(Class<?> cls) { String suffix = ""; while (cls.isAnonymousClass()) { suffix = ".<anonymous_class>" + suffix; if (cls.getEnclosingMethod() != null) { suffix = "." + cls.getEnclosingMethod().getName() + suffix; } cls = cls.getEnclosingClass(); } this.logger = Logger.getLogger(cls.getCanonicalName() + suffix); this.logger.addHandler(new SetSourceClassHandler(cls.getCanonicalName())); } public FormattingLogger(Logger logger) { this.logger = logger; } public static FormattingLogger getLogger(Class<?> cls) { return new FormattingLogger(cls); } public void finestfmt(String message, Object... args) { logger.log(Level.FINEST, String.format(message, args)); } public void finerfmt(String message, Object... args) { logger.log(Level.FINER, String.format(message, args)); } public void finefmt(String message, Object... args) { logger.log(Level.FINE, String.format(message, args)); } public void infofmt(String message, Object... args) { logger.log(Level.INFO, String.format(message, args)); } public void configfmt(String message, Object... args) { logger.log(Level.CONFIG, String.format(message, args)); } public void warningfmt(String message, Object... args) { logger.log(Level.WARNING, String.format(message, args)); } public void severefmt(String message, Object... args) { logger.log(Level.SEVERE, String.format(message, args)); } public void finestfmt(Throwable thrown, String message, Object... args) { finest(thrown, String.format(message, args)); } public void finerfmt(Throwable thrown, String message, Object... args) { finer(thrown, String.format(message, args)); } public void finefmt(Throwable thrown, String message, Object... args) { fine(thrown, String.format(message, args)); } public void configfmt(Throwable thrown, String message, Object... args) { config(thrown, String.format(message, args)); } public void warningfmt(Throwable thrown, String message, Object... args) { warning(thrown, String.format(message, args)); } public void infofmt(Throwable thrown, String message, Object... args) { info(thrown, String.format(message, args)); } public void severefmt(Throwable thrown, String message, Object... args) { severe(thrown, String.format(message, args)); } public void finest(Throwable thrown, String message) { logger.log(Level.FINEST, message, thrown); } public void finer(Throwable thrown, String message) { logger.log(Level.FINER, message, thrown); } public void fine(Throwable thrown, String message) { logger.log(Level.FINE, message, thrown); } public void config(Throwable thrown, String message) { logger.log(Level.CONFIG, message, thrown); } public void warning(Throwable thrown, String message) { logger.log(Level.WARNING, message, thrown); } public void info(Throwable thrown, String message) { logger.log(Level.INFO, message, thrown); } public void severe(Throwable thrown, String message) { logger.log(Level.SEVERE, message, thrown); } public void finest(String message) { logger.finest(message); } public void finer(String message) { logger.finer(message); } public void fine(String message) { logger.fine(message); } public void config(String message) { logger.config(message); } public void warning(String message) { logger.warning(message); } public void info(String message) { logger.info(message); } public void severe(String message) { logger.severe(message); } /** Simple handler that sets the sourceClassName of each {@link LogRecord}. */ private static class SetSourceClassHandler extends Handler { private final String sourceClass; public SetSourceClassHandler(String sourceClass) { this.sourceClass = sourceClass; } @Override public void publish(LogRecord record) { record.setSourceClassName(sourceClass); } @Override public void flush() {} @Override public void close() {} } }
package ru.sstu.se20.DAL.DAO; import ru.sstu.se20.DAL.Entities.ResultImagesEntity; public interface IResultImagesDAO extends IOperations<ResultImagesEntity> { }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hama.bsp; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.mapred.InvalidInputException; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.net.Node; import org.apache.hadoop.net.NodeBase; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.StringUtils; public abstract class FileInputFormat<K, V> implements InputFormat<K, V> { public static final Log LOG = LogFactory.getLog(FileInputFormat.class); private static final double SPLIT_SLOP = 1.1; // 10% slop private static final PathFilter hiddenFileFilter = new PathFilter() { @Override public boolean accept(Path p) { String name = p.getName(); return !name.startsWith("_") && !name.startsWith("."); } }; /** * Proxy PathFilter that accepts a path only if all filters given in the * constructor do. Used by the listPaths() to apply the built-in * hiddenFileFilter together with a user provided one (if any). */ private static class MultiPathFilter implements PathFilter { private List<PathFilter> filters; public MultiPathFilter(List<PathFilter> filters) { this.filters = filters; } @Override public boolean accept(Path path) { for (PathFilter filter : filters) { if (!filter.accept(path)) { return false; } } return true; } } @Override public abstract RecordReader<K, V> getRecordReader(InputSplit split, BSPJob job) throws IOException; /** * Set a PathFilter to be applied to the input paths for the BSP job. * * @param filter the PathFilter class use for filtering the input paths. */ public static void setInputPathFilter(BSPJob conf, Class<? extends PathFilter> filter) { conf.getConfiguration().setClass("bsp.input.pathFilter.class", filter, PathFilter.class); } /** * Get a PathFilter instance of the filter set for the input paths. * * @return the PathFilter instance set for the job, NULL if none has been set. */ public static PathFilter getInputPathFilter(BSPJob conf) { Class<? extends PathFilter> filterClass = conf.getConfiguration().getClass( "bsp.input.pathFilter.class", null, PathFilter.class); return (filterClass != null) ? ReflectionUtils.newInstance(filterClass, conf.getConfiguration()) : null; } /** * List input directories. Subclasses may override to, e.g., select only files * matching a regular expression. * * @param job the job to list input paths for * @return array of FileStatus objects * @throws IOException if zero items. */ protected FileStatus[] listStatus(BSPJob job) throws IOException { Path[] dirs = getInputPaths(job); if (dirs.length == 0) { throw new IOException("No input paths specified in job"); } List<FileStatus> result = new ArrayList<FileStatus>(); List<IOException> errors = new ArrayList<IOException>(); // creates a MultiPathFilter with the hiddenFileFilter and the // user provided one (if any). List<PathFilter> filters = new ArrayList<PathFilter>(); filters.add(hiddenFileFilter); PathFilter jobFilter = getInputPathFilter(job); if (jobFilter != null) { filters.add(jobFilter); } PathFilter inputFilter = new MultiPathFilter(filters); for (Path p : dirs) { FileSystem fs = p.getFileSystem(job.getConfiguration()); FileStatus[] matches = null; try { matches = fs.globStatus(p, inputFilter); } catch (Exception e) { LOG.info(p + "\n" + e.toString()); } if (matches == null) { errors.add(new IOException("Input path does not exist: " + p)); } else if (matches.length == 0) { errors.add(new IOException("Input Pattern " + p + " matches 0 files")); } else { for (FileStatus globStat : matches) { if (globStat.isDir()) { Collections.addAll(result, fs.listStatus(globStat.getPath(), inputFilter)); } else { result.add(globStat); } } } } if (!errors.isEmpty()) { throw new InvalidInputException(errors); } LOG.info("Total input paths to process : " + result.size()); return result.toArray(new FileStatus[result.size()]); } /** * Splits files returned by {@link #listStatus(BSPJob)} when they're too big. <br/> * numSplits will be ignored by the framework. */ @Override public InputSplit[] getSplits(BSPJob job, int numSplits) throws IOException { long minSize = Math.max(getFormatMinSplitSize(), getMinSplitSize(job)); long maxSize = getMaxSplitSize(job); // generate splits List<InputSplit> splits = new ArrayList<InputSplit>(); FileStatus[] files = listStatus(job); for (FileStatus file : files) { Path path = file.getPath(); FileSystem fs = path.getFileSystem(job.getConfiguration()); long length = file.getLen(); BlockLocation[] blkLocations = fs.getFileBlockLocations(file, 0, length); if ((length != 0) && isSplitable(job, path)) { long blockSize = file.getBlockSize(); long splitSize = computeSplitSize(blockSize, minSize, maxSize); long bytesRemaining = length; while (((double) bytesRemaining) / splitSize > SPLIT_SLOP) { int blkIndex = getBlockIndex(blkLocations, length - bytesRemaining); splits.add(new FileSplit(path, length - bytesRemaining, splitSize, blkLocations[blkIndex].getHosts())); bytesRemaining -= splitSize; } if (bytesRemaining != 0) { splits .add(new FileSplit(path, length - bytesRemaining, bytesRemaining, blkLocations[blkLocations.length - 1].getHosts())); } } else if (length != 0) { splits.add(new FileSplit(path, 0, length, blkLocations[0].getHosts())); } else { // Create empty hosts array for zero length files splits.add(new FileSplit(path, 0, length, new String[0])); } } // Save the number of input files in the job-conf job.getConfiguration().setLong("bsp.input.files", files.length); LOG.debug("Total # of splits: " + splits.size()); return splits.toArray(new InputSplit[splits.size()]); } /** * @return true if the file is splittable (default), false if not. */ protected boolean isSplitable(BSPJob job, Path path) { return true; } /** * Get the lower bound on split size imposed by the format. * * @return the number of bytes of the minimal split for this format */ protected long getFormatMinSplitSize() { return 1; } /** * Set the minimum input split size * * @param job the job to modify * @param size the minimum size */ public static void setMinInputSplitSize(Job job, long size) { job.getConfiguration().setLong("bsp.min.split.size", size); } /** * Get the minimum split size * * @param job the job * @return the minimum number of bytes that can be in a split */ public static long getMinSplitSize(BSPJob job) { return job.getConfiguration().getLong("bsp.min.split.size", 1L); } /** * Set the maximum split size * * @param job the job to modify * @param size the maximum split size */ public static void setMaxInputSplitSize(Job job, long size) { job.getConfiguration().setLong("bsp.max.split.size", size); } /** * Get the maximum split size. * * @param context the job to look at. * @return the maximum number of bytes a split can include */ public static long getMaxSplitSize(BSPJob context) { return context.getConfiguration().getLong("bsp.max.split.size", Long.MAX_VALUE); } protected long computeTotalSize(BSPJob job, FileStatus[] files) throws IOException { long totalSize = 0L; for (int i = 0; i < files.length; i++) { // check we have valid files FileStatus file = files[i]; if (file.isDir()) { final Path path = file.getPath(); if (path.getName().equals("hama-partitions") || (job.get("bsp.partitioning.dir") != null && path.getName() .equals(job.get("bsp.partitioning.dir")))) { // if we find the partitioning dir, just remove it. LOG.warn("Removing already existing partitioning directory " + path); FileSystem fileSystem = path.getFileSystem(job.getConfiguration()); if (!fileSystem.delete(path, true)) { LOG.error("Remove failed."); } // remove this file from our initial list files[i] = null; } else { throw new IOException("Not a file (dir): " + path); } } totalSize += file.getLen(); } return totalSize; } protected long computeGoalSize(int numSplits, long totalSize) { // The minus 1 is for the remainder. return totalSize / (numSplits <= 1 ? 1 : numSplits - 1); } protected long computeSplitSize(long goalSize, long minSize, long blockSize) { if (goalSize > blockSize) { return Math.max(minSize, Math.max(goalSize, blockSize)); } else { return Math.max(minSize, Math.min(goalSize, blockSize)); } } protected int getBlockIndex(BlockLocation[] blkLocations, long offset) { for (int i = 0; i < blkLocations.length; i++) { // is the offset inside this block? if ((blkLocations[i].getOffset() <= offset) && (offset < blkLocations[i].getOffset() + blkLocations[i].getLength())) { return i; } } BlockLocation last = blkLocations[blkLocations.length - 1]; long fileLength = last.getOffset() + last.getLength() - 1; throw new IllegalArgumentException("Offset " + offset + " is outside of file (0.." + fileLength + ")"); } /** * Sets the given comma separated paths as the list of inputs for the BSP job. * * @param conf Configuration of the job * @param commaSeparatedPaths Comma separated paths to be set as the list of * inputs for the BSP job. */ public static void setInputPaths(BSPJob conf, String commaSeparatedPaths) { setInputPaths(conf, StringUtils.stringToPath(getPathStrings(commaSeparatedPaths))); } /** * Add the given comma separated paths to the list of inputs for the BSP job. * * @param conf The configuration of the job * @param commaSeparatedPaths Comma separated paths to be added to the list of * inputs for the BSP job. */ public static void addInputPaths(BSPJob conf, String commaSeparatedPaths) { for (String str : getPathStrings(commaSeparatedPaths)) { addInputPath(conf, new Path(str)); } } /** * Set the array of {@link Path}s as the list of inputs for the BSP job. * * @param conf Configuration of the job. * @param inputPaths the {@link Path}s of the input directories/files for the * BSP job. */ public static void setInputPaths(BSPJob conf, Path... inputPaths) { Path path = new Path(conf.getWorkingDirectory(), inputPaths[0]); StringBuffer str = new StringBuffer(StringUtils.escapeString(path .toString())); for (int i = 1; i < inputPaths.length; i++) { str.append(StringUtils.COMMA_STR); path = new Path(conf.getWorkingDirectory(), inputPaths[i]); str.append(StringUtils.escapeString(path.toString())); } conf.set("bsp.input.dir", str.toString()); } /** * Add a {@link Path} to the list of inputs for the BSP job. * * @param conf The configuration of the job * @param p {@link Path} to be addaiaied to the list of inputs for the BSP job. */ public static void addInputPath(BSPJob conf, Path p) { Path path = new Path(conf.getWorkingDirectory(), p); String dirStr = StringUtils.escapeString(path.toString()); String dirs = conf.get("bsp.input.dir"); conf.set("bsp.input.dir", dirs == null ? dirStr : dirs + StringUtils.COMMA_STR + dirStr); } // This method escapes commas in the glob pattern of the given paths. private static String[] getPathStrings(String commaSeparatedPaths) { int length = commaSeparatedPaths.length(); int curlyOpen = 0; int pathStart = 0; boolean globPattern = false; List<String> pathStrings = new ArrayList<String>(); for (int i = 0; i < length; i++) { char ch = commaSeparatedPaths.charAt(i); switch (ch) { case '{': { curlyOpen++; if (!globPattern) { globPattern = true; } break; } case '}': { curlyOpen--; if (curlyOpen == 0 && globPattern) { globPattern = false; } break; } case ',': { if (!globPattern) { pathStrings.add(commaSeparatedPaths.substring(pathStart, i)); pathStart = i + 1; } break; } } } pathStrings.add(commaSeparatedPaths.substring(pathStart, length)); return pathStrings.toArray(new String[pathStrings.size()]); } /** * Get the list of input {@link Path}s for the BSP job. * * @param conf The configuration of the job * @return the list of input {@link Path}s for the BSP job. */ public static Path[] getInputPaths(BSPJob conf) { String dirs = conf.getConfiguration().get("bsp.input.dir", ""); String[] list = StringUtils.split(dirs); Path[] result = new Path[list.length]; for (int i = 0; i < list.length; i++) { result[i] = new Path(StringUtils.unEscapeString(list[i])); } return result; } private static void sortInDescendingOrder(List<NodeInfo> mylist) { Collections.sort(mylist, new Comparator<NodeInfo>() { @Override public int compare(NodeInfo obj1, NodeInfo obj2) { if (obj1 == null || obj2 == null) return -1; if (obj1.getValue() == obj2.getValue()) { return 0; } else { return ((obj1.getValue() < obj2.getValue()) ? 1 : -1); } } }); } /** * This function identifies and returns the hosts that contribute most for a * given split. For calculating the contribution, rack locality is treated on * par with host locality, so hosts from racks that contribute the most are * preferred over hosts on racks that contribute less * * @param blkLocations The list of block locations * @param offset * @param pSplitSize * @return array of hosts that contribute most to this split * @throws IOException */ protected String[] getSplitHosts(BlockLocation[] blkLocations, long offset, long pSplitSize, NetworkTopology clusterMap) throws IOException { long splitSize = pSplitSize; int startIndex = getBlockIndex(blkLocations, offset); long bytesInThisBlock = blkLocations[startIndex].getOffset() + blkLocations[startIndex].getLength() - offset; // If this is the only block, just return if (bytesInThisBlock >= splitSize) { return blkLocations[startIndex].getHosts(); } long bytesInFirstBlock = bytesInThisBlock; int index = startIndex + 1; splitSize -= bytesInThisBlock; while (splitSize > 0) { bytesInThisBlock = Math.min(splitSize, blkLocations[index++].getLength()); splitSize -= bytesInThisBlock; } long bytesInLastBlock = bytesInThisBlock; int endIndex = index - 1; Map<Node, NodeInfo> hostsMap = new IdentityHashMap<Node, NodeInfo>(); Map<Node, NodeInfo> racksMap = new IdentityHashMap<Node, NodeInfo>(); String[] allTopos = new String[0]; // Build the hierarchy and aggregate the contribution of // bytes at each level. See TestGetSplitHosts.java for (index = startIndex; index <= endIndex; index++) { // Establish the bytes in this block if (index == startIndex) { bytesInThisBlock = bytesInFirstBlock; } else if (index == endIndex) { bytesInThisBlock = bytesInLastBlock; } else { bytesInThisBlock = blkLocations[index].getLength(); } allTopos = blkLocations[index].getTopologyPaths(); // If no topology information is available, just // prefix a fakeRack if (allTopos.length == 0) { allTopos = fakeRacks(blkLocations, index); } // NOTE: This code currently works only for one level of // hierarchy (rack/host). However, it is relatively easy // to extend this to support aggregation at different // levels for (String topo : allTopos) { Node node, parentNode; NodeInfo nodeInfo, parentNodeInfo; node = clusterMap.getNode(topo); if (node == null) { node = new NodeBase(topo); clusterMap.add(node); } nodeInfo = hostsMap.get(node); if (nodeInfo == null) { nodeInfo = new NodeInfo(node); hostsMap.put(node, nodeInfo); parentNode = node.getParent(); parentNodeInfo = racksMap.get(parentNode); if (parentNodeInfo == null) { parentNodeInfo = new NodeInfo(parentNode); racksMap.put(parentNode, parentNodeInfo); } parentNodeInfo.addLeaf(nodeInfo); } else { nodeInfo = hostsMap.get(node); parentNode = node.getParent(); parentNodeInfo = racksMap.get(parentNode); } nodeInfo.addValue(index, bytesInThisBlock); parentNodeInfo.addValue(index, bytesInThisBlock); } // for all topos } // for all indices return identifyHosts(allTopos.length, racksMap); } private static String[] identifyHosts(int replicationFactor, Map<Node, NodeInfo> racksMap) { String[] retVal = new String[replicationFactor]; List<NodeInfo> rackList = new LinkedList<NodeInfo>(); rackList.addAll(racksMap.values()); // Sort the racks based on their contribution to this split sortInDescendingOrder(rackList); boolean done = false; int index = 0; // Get the host list for all our aggregated items, sort // them and return the top entries for (NodeInfo ni : rackList) { Set<NodeInfo> hostSet = ni.getLeaves(); List<NodeInfo> hostList = new LinkedList<NodeInfo>(); hostList.addAll(hostSet); // Sort the hosts in this rack based on their contribution sortInDescendingOrder(hostList); for (NodeInfo host : hostList) { // Strip out the port number from the host name retVal[index++] = host.node.getName().split(":")[0]; if (index == replicationFactor) { done = true; break; } } if (done == true) { break; } } return retVal; } private static String[] fakeRacks(BlockLocation[] blkLocations, int index) throws IOException { String[] allHosts = blkLocations[index].getHosts(); String[] allTopos = new String[allHosts.length]; for (int i = 0; i < allHosts.length; i++) { allTopos[i] = NetworkTopology.DEFAULT_RACK + "/" + allHosts[i]; } return allTopos; } private static class NodeInfo { final Node node; final Set<Integer> blockIds; final Set<NodeInfo> leaves; private long value; NodeInfo(Node node) { this.node = node; blockIds = new HashSet<Integer>(); leaves = new HashSet<NodeInfo>(); } long getValue() { return value; } void addValue(int blockIndex, long value) { if (blockIds.add(blockIndex) == true) { this.value += value; } } Set<NodeInfo> getLeaves() { return leaves; } void addLeaf(NodeInfo nodeInfo) { leaves.add(nodeInfo); } } }
package org.aprestos.labs.apis.springboot2.statemanager; public class StateManagerException extends Exception { private static final long serialVersionUID = 1L; public StateManagerException() { super(); } public StateManagerException(String arg0) { super(arg0); } public StateManagerException(Throwable arg0) { super(arg0); } public StateManagerException(String arg0, Throwable arg1) { super(arg0, arg1); } }
package com.github.monkeywie.proxyee.intercept.common; import com.github.monkeywie.proxyee.intercept.HttpProxyIntercept; import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptPipeline; import io.netty.channel.Channel; import io.netty.handler.codec.http.*; import io.netty.util.ReferenceCountUtil; public abstract class FullResponseIntercept extends HttpProxyIntercept { /** * default max content length size is 8MB */ private static final int DEFAULT_MAX_CONTENT_LENGTH = 1024 * 1024 * 8; private int maxContentLength; private Boolean isMatch; public FullResponseIntercept() { this(DEFAULT_MAX_CONTENT_LENGTH); } public FullResponseIntercept(int maxContentLength) { this.maxContentLength = maxContentLength; } @Override public final void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) throws Exception { if (httpResponse instanceof FullHttpResponse) { FullHttpResponse fullHttpResponse = (FullHttpResponse) httpResponse; // 判断是第一个处理FullResponse的拦截器是否匹配 boolean isFirstMatch = isMatch != null && isMatch == true; // 判断后续的拦截器是否匹配 boolean isAfterMatch = isFirstMatch ? false : matchHandle(pipeline.getHttpRequest(), pipeline.getHttpResponse(), pipeline); if (isFirstMatch || isAfterMatch) { handleResponse(pipeline.getHttpRequest(), fullHttpResponse, pipeline); if (fullHttpResponse.headers().contains(HttpHeaderNames.CONTENT_LENGTH)) { httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, fullHttpResponse.content().readableBytes()); } } if (isFirstMatch) { proxyChannel.pipeline().remove("decompress"); proxyChannel.pipeline().remove("aggregator"); } } else { this.isMatch = matchHandle(pipeline.getHttpRequest(), pipeline.getHttpResponse(), pipeline); if (this.isMatch) { proxyChannel.pipeline().addAfter("httpCodec", "decompress", new HttpContentDecompressor()); proxyChannel.pipeline() .addAfter("decompress", "aggregator", new HttpObjectAggregator(maxContentLength)); proxyChannel.pipeline().fireChannelRead(httpResponse); return; } } pipeline.afterResponse(clientChannel, proxyChannel, httpResponse); } @Deprecated /** * 剥离到工具类中了:{@link com.github.monkeywie.proxyee.util#isHtml(HttpRequest, HttpResponse)} */ protected boolean isHtml(HttpRequest httpRequest, HttpResponse httpResponse) { String accept = httpRequest.headers().get(HttpHeaderNames.ACCEPT); String contentType = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE); return httpResponse.status().code() == 200 && accept != null && accept .matches("^.*text/html.*$") && contentType != null && contentType .matches("^text/html.*$"); } private boolean matchHandle(HttpRequest httpRequest, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) { boolean isMatch = match(httpRequest, httpResponse, pipeline); if (httpRequest instanceof FullHttpRequest) { FullHttpRequest fullHttpRequest = (FullHttpRequest) httpRequest; if (fullHttpRequest.content().refCnt() > 0) { ReferenceCountUtil.release(fullHttpRequest); } } return isMatch; } /** * 匹配到的响应会解码成FullResponse */ public abstract boolean match(HttpRequest httpRequest, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline); /** * 拦截并处理响应 */ public void handleResponse(HttpRequest httpRequest, FullHttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) { } }
package com.epam.lab.controllers; import com.epam.lab.constants.Constants; import com.epam.lab.models.Comment; import com.epam.lab.models.Dashboard; import com.epam.lab.models.Task; import com.epam.lab.models.User; import com.epam.lab.services.CommentService; import com.epam.lab.services.DashboardService; import com.epam.lab.services.TaskService; import com.epam.lab.services.UserService; import com.epam.lab.util.StringConcat; import org.apache.log4j.LogManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * This class represents dashboard controller. */ @Controller public class DashboardController { /** * This field represents logger */ private static final Logger LOGGER = LogManager.getLogger(DashboardController.class); /** * This field represents dashboard id */ private static int dasboardId; /** * This field represents task id */ private static int taskId; /** * This field represents dashboard's service */ @Autowired private DashboardService dashboardService; /** * This field represents user's service */ @Autowired private UserService userService; /** * This field represents task's service */ @Autowired private TaskService taskService; /** * This field represents comments's service */ @Autowired private CommentService commentService; /** * This method describes logic of opening dashboard * @return ModelAndView */ @RequestMapping(value = "/dashboard") public ModelAndView openDashboard() { ModelAndView modelAndView = new ModelAndView(); List<Dashboard> dashboards = new ArrayList<>(); List<User> users = new ArrayList<>(); try { dashboards = dashboardService.getDashboards(); users = userService.getUsers(Constants.USER); } catch (SQLException e) { LOGGER.error(Constants.ERROR_OPEN_DASHBOARD, e); e.printStackTrace(); } modelAndView.addObject(Constants.DASHBOARDS, dashboards); modelAndView.addObject(Constants.USERS, users); modelAndView.setViewName(Constants.DASHBOARD); return modelAndView; } /** * This method describes logic of adding new Dashboard * @param dashboard Dashboard in input * @param result BindingResult in input * @param request HttpServletRequest in input * @return ModelAndView */ @RequestMapping(value = "/add_dashboard") public ModelAndView addDashboard(@ModelAttribute Dashboard dashboard, BindingResult result, HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView(); String userName = request.getParameter(Constants.USERNAME); try { dashboard.setAuthor(userName); dashboardService.addDashboard(dashboard); } catch (SQLException e) { LOGGER.error(Constants.ERROR_ADD_DASHBOARD, e); e.printStackTrace(); } modelAndView.setViewName(Constants.DASHBOARD_REDIRECT); return modelAndView; } /** * This method describes logic of deleting dashboard * @param id int in input * @param dashboard Dashboard in input * @param result BindingResult in input * @return ModelAndView */ @RequestMapping(value = "/delete_dashboard{id}") public ModelAndView deleteDashboard(@PathVariable int id, @ModelAttribute Dashboard dashboard, BindingResult result) { ModelAndView modelAndView = new ModelAndView(); try { dashboard.setId(id); dashboardService.deleteDashboard(dashboard); } catch (SQLException e) { LOGGER.error(Constants.ERROR_DELETE_DASHBOARD, e); e.printStackTrace(); } modelAndView.setViewName(Constants.DASHBOARD_REDIRECT); return modelAndView; } /** * This method describes logic if viewing dashboard * @param id int in input * @return ModelAndView */ @RequestMapping(value = "/view_dashboard{id}") public ModelAndView viewDashboard(@PathVariable int id) { ModelAndView modelAndView = new ModelAndView(); dasboardId = id; List<User> users; List<Task> tasks; try { Dashboard dashboard = dashboardService.getDashboard(id); users = userService.getUsers(Constants.USER); tasks = taskService.getTasks(id); modelAndView.addObject(Constants.TASKS, tasks); modelAndView.addObject(Constants.USERS, users); modelAndView.addObject(Constants.DASHBOARD, dashboard); } catch (SQLException e) { LOGGER.error(Constants.ERROR_DISPLAY_DASHBOARD, e); e.printStackTrace(); } modelAndView.setViewName(Constants.VIEW_DASHBOARD); return modelAndView; } /** * This method describes logic of editing dashboard * @param id int in input * @param dashboard Dashboard in input * @param request HttpServletRequest in input * @return ModelAndView */ @RequestMapping(value = "/edit_dashboard{id}") public ModelAndView editDashboard(@PathVariable int id, @ModelAttribute Dashboard dashboard, HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView(); String username = request.getParameter(Constants.USERNAME); try { dashboard.setId(id); dashboard.setAuthor(username); dashboardService.editDashboard(dashboard); } catch (SQLException e) { LOGGER.error(Constants.ERROR_EDIT_DASHBOARD, e); e.printStackTrace(); } StringConcat stringConcat = (str1, int1) -> str1 + int1; modelAndView.setViewName(stringConcat.sconcat(Constants.VIEW_DASHBOARD_REDIRECT, id)); return modelAndView; } /** * This method describes logic of adding tasks * @param task Task in input * @param result BindingResult in input * @param request HttpServletRequest in input * @return ModelAndView */ @RequestMapping(value = "/add_task") public ModelAndView addTask(@ModelAttribute Task task, BindingResult result, HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView(); String username = request.getParameter(Constants.USERNAME); try { task.setDashboardId(dasboardId); task.setAuthor(username); taskService.addTask(task); } catch (SQLException e) { LOGGER.error(Constants.ERROR_ADD_TASK, e); e.printStackTrace(); } StringConcat stringConcat = (str1, int1) -> str1 + int1; modelAndView.setViewName(stringConcat.sconcat(Constants.VIEW_DASHBOARD_REDIRECT, dasboardId)); return modelAndView; } /** * This method describes logic of deleting task * @param taskId int in input * @param task Task in input * @param result BindingResult in input * @return ModelAndView */ @RequestMapping(value = "/delete_task{taskId}") public ModelAndView deleteTask(@PathVariable int taskId, @ModelAttribute Task task, BindingResult result) { ModelAndView modelAndView = new ModelAndView(); try { task.setId(taskId); taskService.deleteTask(task); } catch (SQLException e) { LOGGER.error(Constants.ERROR_DELETE_TASK, e); e.printStackTrace(); } StringConcat stringConcat = (str1, int1) -> str1 + int1; modelAndView.setViewName(stringConcat.sconcat(Constants.VIEW_DASHBOARD_REDIRECT, dasboardId)); return modelAndView; } /** * This method describes logic of viewing tasks * @param id int in input * @return ModelAndView */ @RequestMapping(value = "view_task{id}") public ModelAndView viewTask(@PathVariable int id) { ModelAndView modelAndView = new ModelAndView(); taskId = id; List<User> users = new ArrayList<>(); List<Comment> comments = new ArrayList<>(); User user = null; Task task = null; try { user = userService.getUser(Constants.LOGIN_USER); // task = taskService.getTask(id); users = userService.getUsers(Constants.USER); comments = commentService.getComments(id); } catch (SQLException e) { LOGGER.error(Constants.ERROR_VIEW_TASK, e); e.printStackTrace(); } modelAndView.addObject(Constants.USER_NAME, user); modelAndView.addObject(Constants.TASK, task); modelAndView.addObject(Constants.DASHBOARD_ID, dasboardId); modelAndView.addObject(Constants.USERS, users); modelAndView.addObject(Constants.COMMENTS, comments); modelAndView.setViewName(Constants.VIEW_TASK); return modelAndView; } /** * This method describes logic of editing tasks * @param taskId int in input * @param task Task in input * @param request HttpServletRequest in input * @return ModelAndView */ @RequestMapping(value = "/edit_task{taskId}") public ModelAndView editTask(@PathVariable int taskId, @ModelAttribute Task task, HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView(); String username = request.getParameter(Constants.USERNAME); try { task.setDashboardId(dasboardId); task.setId(taskId); task.setAuthor(username); taskService.editTask(task); } catch (SQLException e) { LOGGER.error(Constants.ERROR_EDIT_TASK, e); e.printStackTrace(); } StringConcat stringConcat = (str1, int1) -> str1 + int1; modelAndView.setViewName(stringConcat.sconcat(Constants.VIEW_TASK_REDIRECT, taskId)); return modelAndView; } /** * This method describes logic of adding comment. * @param comment Comment in input * @param request HttpServletRequest in input * @return ModelAndView */ @RequestMapping(value = "/add_comment") public ModelAndView addComment(@ModelAttribute Comment comment, HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView(); String username = request.getParameter(Constants.USERNAME); SimpleDateFormat format = new SimpleDateFormat(Constants.DATE_PATTERN); String date = format.format(new Date(System.currentTimeMillis())); try { comment.setTask_id(taskId); comment.setLogin(username); comment.setDate(date); commentService.addComment(comment); } catch (SQLException e) { LOGGER.error(Constants.ERROR_ADD_COMMENT, e); e.printStackTrace(); } StringConcat stringConcat = (str1, int1) -> str1 + int1; modelAndView.setViewName(stringConcat.sconcat(Constants.VIEW_TASK_REDIRECT, taskId)); return modelAndView; } /** * This method describes logic of deleting comment. * @param id int in input * @param comment Comment in input * @return ModelAndView */ @RequestMapping(value = "/delete_comment{id}") public ModelAndView deleteComment(@PathVariable int id, @ModelAttribute Comment comment) { ModelAndView modelAndView = new ModelAndView(); try { comment.setId(id); commentService.deleteComment(comment); } catch (SQLException e) { LOGGER.error(Constants.ERROR_DELETE_COMMENT, e); } StringConcat stringConcat = (str1, int1) -> str1 + int1; modelAndView.setViewName(stringConcat.sconcat(Constants.VIEW_TASK_REDIRECT, taskId)); return modelAndView; } /** * This method describes logic of editing comment. * @param commentId int in input * @param request HttpServletRequest in input * @param comment Comment in input * @return ModelAndView */ @RequestMapping(value = "/edit_comment{commentId}") public ModelAndView editComment(@PathVariable int commentId, HttpServletRequest request, @ModelAttribute Comment comment) { ModelAndView modelAndView = new ModelAndView(); String login = request.getParameter(Constants.ED_LOGIN); String date = request.getParameter(Constants.ED_DATE); String text = request.getParameter(Constants.ED_TEXT_COMMENT); try { comment.setId(commentId); comment.setLogin(login); comment.setDate(date); comment.setTask_id(taskId); comment.setComment(text); commentService.editComment(comment); } catch (SQLException e) { LOGGER.error(Constants.ERROR_EDIT_COMMENT, e); e.printStackTrace(); } StringConcat stringConcat = (str1, int1) -> str1 + int1; modelAndView.setViewName(stringConcat.sconcat(Constants.VIEW_TASK_REDIRECT, taskId)); return modelAndView; } @ModelAttribute private Comment getComment() { return new Comment(); } @ModelAttribute private Task getTask() { return new Task(); } @ModelAttribute private Dashboard getDashboard() { return new Dashboard(); } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.models.extensions.DeviceAndAppManagementRoleAssignment; import com.microsoft.graph.requests.extensions.IRoleScopeTagCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IRoleScopeTagRequestBuilder; import com.microsoft.graph.requests.extensions.RoleScopeTagCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.RoleScopeTagRequestBuilder; import java.util.Arrays; import java.util.EnumSet; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequestBuilder; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Device And App Management Role Assignment Request Builder. */ public class DeviceAndAppManagementRoleAssignmentRequestBuilder extends BaseRequestBuilder implements IDeviceAndAppManagementRoleAssignmentRequestBuilder { /** * The request builder for the DeviceAndAppManagementRoleAssignment * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public DeviceAndAppManagementRoleAssignmentRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } /** * Creates the request * * @param requestOptions the options for this request * @return the IDeviceAndAppManagementRoleAssignmentRequest instance */ public IDeviceAndAppManagementRoleAssignmentRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the request with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for this request * @return the IDeviceAndAppManagementRoleAssignmentRequest instance */ public IDeviceAndAppManagementRoleAssignmentRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { return new com.microsoft.graph.requests.extensions.DeviceAndAppManagementRoleAssignmentRequest(getRequestUrl(), getClient(), requestOptions); } /** * Gets the request builder for RoleDefinition * * @return the IRoleDefinitionWithReferenceRequestBuilder instance */ public IRoleDefinitionWithReferenceRequestBuilder roleDefinition() { return new RoleDefinitionWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("roleDefinition"), getClient(), null); } public IRoleScopeTagCollectionWithReferencesRequestBuilder roleScopeTags() { return new RoleScopeTagCollectionWithReferencesRequestBuilder(getRequestUrlWithAdditionalSegment("roleScopeTags"), getClient(), null); } public IRoleScopeTagWithReferenceRequestBuilder roleScopeTags(final String id) { return new RoleScopeTagWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("roleScopeTags") + "/" + id, getClient(), null); } }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk.internal.protocolparser.dynamicimpl; import org.chromium.sdk.internal.protocolparser.JsonProtocolModelParseException; import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException; import org.chromium.sdk.internal.protocolparser.dynamicimpl.JavaCodeGenerator.MethodScope; /** * An implementation of JsonSubtypeCondition* annotations. Basically it only holds all parameters * and delegates actual condition evaluating to {@link #conditionLogic}. */ class FieldCondition { private final String propertyName; private final QuickParser<?> quickParser; private final FieldConditionLogic conditionLogic; FieldCondition(String propertyName, QuickParser<?> quickParser, FieldConditionLogic conditionLogic) throws JsonProtocolModelParseException { if (conditionLogic.requiresQuickParser() && quickParser == null) { throw new JsonProtocolModelParseException( "The choose condition does not work with the type of " + propertyName); } this.propertyName = propertyName; this.quickParser = quickParser; this.conditionLogic = conditionLogic; } String getPropertyName() { return propertyName; } /** * @param hasValue whether field exists in JSON object (however its value may be null) * @param unparsedValue value of the field if hasValue is true or undefined otherwise */ boolean checkValue(boolean hasValue, Object unparsedValue) throws JsonProtocolParseException { return conditionLogic.checkValue(hasValue, unparsedValue, quickParser); } public void writeCheckJava(MethodScope methodScope, String valueRef, String hasValueRef, String resultRef) { conditionLogic.writeCheckJava(methodScope, valueRef, hasValueRef, resultRef, quickParser); } }
package app.coronawarn.datadonation.services.edus.otp; import static app.coronawarn.datadonation.common.config.UrlConstants.OTP; import static app.coronawarn.datadonation.common.config.UrlConstants.SURVEY; import app.coronawarn.datadonation.common.persistence.domain.OneTimePassword; import app.coronawarn.datadonation.common.persistence.service.OtpService; import app.coronawarn.datadonation.common.persistence.service.OtpTestGenerationResponse; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(SURVEY) @Profile("generate-otp") public class GenerateOtpController { /** * The route to the Event-driven User Surveys endpoint for OTP testing. */ private static final Logger logger = LoggerFactory.getLogger(GenerateOtpController.class); @Autowired private final OtpService otpService; public GenerateOtpController(OtpService otpService) { this.otpService = otpService; logger.warn("DON'T USE PROFILE 'generate-otp' IN PRODUCTION ENVIRONMENT!"); } /** * Generate a list of OTPs for testing purpose. * * @return Response that contains a list with new generated OTPs. */ @GetMapping(value = OTP + "/{number}/{validity}") public ResponseEntity<List<OtpTestGenerationResponse>> generateOtp( @PathVariable(name = "number") Integer number, @PathVariable("validity") Integer validity) { List<OtpTestGenerationResponse> generatedOtps = new ArrayList<>(); for (int i = 0; i < number; i++) { String password = UUID.randomUUID().toString(); ZonedDateTime expirationTime = otpService.createOtp(new OneTimePassword(password), validity); OtpTestGenerationResponse otpTestGenerationResponse = new OtpTestGenerationResponse(expirationTime, password); generatedOtps.add(otpTestGenerationResponse); } return ResponseEntity.status(HttpStatus.OK).body(generatedOtps); } }
/** * Copyright (c) 2011-2020, JFXtras * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the organization nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL JFXRAS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package jfxtras.icalendarfx.content; public abstract class ContentLineBase implements ContentLineStrategy { final Orderer orderer; public ContentLineBase(Orderer orderer) { this.orderer = orderer; } }
package cc.mrbird.febs.common.doc.gateway.handler; import cc.mrbird.febs.common.doc.gateway.properties.FebsDocGatewayProperties; import org.apache.commons.lang3.StringUtils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; import springfox.documentation.swagger.web.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; /** * @author luo */ @RestController public class FebsDocGatewayHandler { private SecurityConfiguration securityConfiguration; private UiConfiguration uiConfiguration; private SwaggerResourcesProvider swaggerResources; private FebsDocGatewayProperties properties; public void setSecurityConfiguration(SecurityConfiguration securityConfiguration) { this.securityConfiguration = securityConfiguration; } public void setUiConfiguration(UiConfiguration uiConfiguration) { this.uiConfiguration = uiConfiguration; } public void setSwaggerResources(SwaggerResourcesProvider swaggerResources) { this.swaggerResources = swaggerResources; } public void setProperties(FebsDocGatewayProperties properties) { this.properties = properties; } @GetMapping("/swagger-resources/configuration/security") public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() { return Mono.just(new ResponseEntity<>( Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK)); } @GetMapping("/swagger-resources/configuration/ui") public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() { return Mono.just(new ResponseEntity<>( Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK)); } @GetMapping("/swagger-resources") public Mono<ResponseEntity<List<SwaggerResource>>> swaggerResources() { List<SwaggerResource> swaggerResources = this.swaggerResources.get(); List<SwaggerResource> filterList = new ArrayList<>(); String resources = properties.getResources(); String[] resourcesArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(resources, ","); if (resourcesArray != null && resources.length() > 0) { boolean include = false; for (SwaggerResource resource : swaggerResources) { if (Arrays.stream(resourcesArray).anyMatch(r -> StringUtils.equalsIgnoreCase(r, resource.getName()))) { include = true; } if (include) { filterList.add(resource); } } return Mono.just((new ResponseEntity<>(filterList, HttpStatus.OK))); } return Mono.just((new ResponseEntity<>(swaggerResources, HttpStatus.OK))); } }
package org.jboss.resteasy.test.core.basic.resource; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; @Path("/") public class ApplicationPropertiesConfigResource { @Context private Configuration configuration; @GET @Path("/getconfigproperty") public String getProperty(@QueryParam("prop") String prop) { String value = (String) configuration.getProperty(prop); return value; } }
package synfron.reshaper.burp.ui.components.rules; import lombok.SneakyThrows; import synfron.reshaper.burp.core.events.IEventListener; import synfron.reshaper.burp.core.events.PropertyChangedArgs; import synfron.reshaper.burp.ui.models.rules.RuleModel; import synfron.reshaper.burp.ui.utils.DocumentActionListener; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.font.TextAttribute; import java.net.URI; import java.util.Map; public class RuleComponent extends JPanel { private final RuleModel model; private JCheckBox isEnabled; private JCheckBox autoRun; private JTextField ruleName; private JButton save; private final IEventListener<PropertyChangedArgs> modelPropertyChangedListener = this::onModelPropertyChanged; public RuleComponent(RuleModel model) { this.model = model; model.getPropertyChangedEvent().add(modelPropertyChangedListener); initComponent(); } private void initComponent() { setLayout(new BorderLayout()); add(getRuleNameBox(), BorderLayout.PAGE_START); add(getRuleOperations(), BorderLayout.CENTER); add(getActionBar(), BorderLayout.PAGE_END); } private Component getRuleOperations() { return new RuleOperationsContainerComponent(model); } private void setSaveButtonState() { if (model.isSaved()) { save.setEnabled(false); save.setText("Saved"); } else { save.setEnabled(true); save.setText("Save"); } } private Component getRuleNameBox() { JPanel container = new JPanel(); container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); container.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); ruleName = new JTextField(); ruleName.setText(model.getName()); ruleName.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); ruleName.setAlignmentX(Component.LEFT_ALIGNMENT); ruleName.setColumns(20); ruleName.setMaximumSize(ruleName.getPreferredSize()); ruleName.getDocument().addDocumentListener(new DocumentActionListener(this::onRuleNameChanged)); container.add(new JLabel("Rule Name")); container.add(ruleName); return container; } private Component getGitHubLink() { JLabel githubLink = new JLabel("Help"); githubLink.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); Font font = githubLink.getFont(); Map attributes = font.getAttributes(); attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); githubLink.setFont(font.deriveFont(attributes)); githubLink.addMouseListener(new MouseListener() { private Color originalColor = githubLink.getForeground(); @SneakyThrows @Override public void mouseClicked(MouseEvent e) { Desktop.getDesktop().browse(new URI("https://synfron.github.io/ReshaperForBurp")); } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) { githubLink.setForeground(new Color(0, 0, 0xC0)); } @Override public void mouseExited(MouseEvent e) { githubLink.setForeground(originalColor); } }); return githubLink; } private Component getActionBar() { JPanel actionBar = new JPanel(new BorderLayout()); JPanel buttonSection = new JPanel(new FlowLayout(FlowLayout.RIGHT)); autoRun = new JCheckBox("Auto Run"); isEnabled = new JCheckBox("Enabled"); save = new JButton("Save"); setSaveButtonState(); autoRun.setSelected(model.isAutoRun()); isEnabled.setSelected(model.isEnabled()); autoRun.addActionListener(this::onAutoRun); isEnabled.addActionListener(this::onEnabled); save.addActionListener(this::onSave); buttonSection.add(autoRun); buttonSection.add(isEnabled); buttonSection.add(save); actionBar.add(getGitHubLink(), BorderLayout.LINE_START); actionBar.add(buttonSection, BorderLayout.LINE_END); return actionBar; } private void onModelPropertyChanged(PropertyChangedArgs propertyChangedArgs) { if ("saved".equals(propertyChangedArgs.getName())) { setSaveButtonState(); } } private void onAutoRun(ActionEvent actionEvent) { model.setAutoRun(autoRun.isSelected()); } private void onRuleNameChanged(ActionEvent actionEvent) { model.setName(ruleName.getText()); } private void onEnabled(ActionEvent actionEvent) { model.setEnabled(isEnabled.isSelected()); } private void onSave(ActionEvent actionEvent) { if (!model.persist()) { JOptionPane.showMessageDialog(this, String.join("\n", model.validate()), "Validation Error", JOptionPane.ERROR_MESSAGE); } } }
package ch.cevi.db.client.gui.actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import ch.cevi.db.client.configuration.Texts; import ch.cevi.db.client.gui.AboutDialog; import ch.cevi.db.client.gui.MainWindow; public class AboutAction extends AbstractAction { private static final long serialVersionUID = 7720672914222472305L; private MainWindow mainWindow; public AboutAction(MainWindow mainWindow) { super(Texts.getTranslatedText(Texts.MENU_HELP_MENU_ABOUT_ITEM)); this.mainWindow = mainWindow; } @Override public void actionPerformed(ActionEvent e) { AboutDialog connectDialog = new AboutDialog(mainWindow); connectDialog.setLocationRelativeTo(mainWindow); connectDialog.setVisible(true); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.linkis.manager.engineplugin.jdbc.executer; import org.apache.linkis.storage.domain.*; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; public class JDBCHelper { protected String helper(ResultSet rs, int dataType, int col) throws SQLException { String retVal = null; Integer intObj; switch (dataType) { case Types.DATE: java.sql.Date date = rs.getDate(col); retVal = date.toString(); break; case Types.TIME: java.sql.Time time = rs.getTime(col); retVal = time.toString(); break; case Types.TIMESTAMP: java.sql.Timestamp timestamp = rs.getTimestamp(col); retVal = timestamp.toString(); break; case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: retVal = rs.getString(col); break; case Types.NUMERIC: case Types.DECIMAL: java.math.BigDecimal numeric = rs.getBigDecimal(col, 10); retVal = numeric.toString(); break; case Types.BIT: boolean bit = rs.getBoolean(col); Boolean boolObj = new Boolean(bit); retVal = boolObj.toString(); break; case Types.TINYINT: byte tinyint = rs.getByte(col); intObj = new Integer(tinyint); retVal = intObj.toString(); break; case Types.SMALLINT: short smallint = rs.getShort(col); intObj = new Integer(smallint); retVal = intObj.toString(); break; case Types.INTEGER: int integer = rs.getInt(col); intObj = new Integer(integer); retVal = intObj.toString(); break; case Types.BIGINT: long bigint = rs.getLong(col); Long longObj = new Long(bigint); retVal = longObj.toString(); break; case Types.REAL: float real = rs.getFloat(col); Float floatObj = new Float(real); retVal = floatObj.toString(); break; case Types.FLOAT: case Types.DOUBLE: double longreal = rs.getDouble(col); Double doubleObj = new Double(longreal); retVal = doubleObj.toString(); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: byte[] binary = rs.getBytes(col); retVal = new String(binary); break; default: break; } return retVal; } public static String getTypeStr(int type) { String retVal = null; Integer intObj; switch (type) { case Types.NULL: retVal = NullType.typeName(); break; case Types.VARCHAR: retVal = StringType.typeName(); break; case Types.BOOLEAN: retVal = BooleanType.typeName(); break; case Types.TINYINT: retVal = TinyIntType.typeName(); break; case Types.SMALLINT: retVal = ShortIntType.typeName(); break; case Types.INTEGER: retVal = IntType.typeName(); break; case Types.LONGNVARCHAR: retVal = LongType.typeName(); break; case Types.LONGVARCHAR: retVal = StringType.typeName(); break; case Types.FLOAT: retVal = FloatType.typeName(); break; case Types.DOUBLE: retVal = DoubleType.typeName(); break; case Types.CHAR: retVal = CharType.typeName(); break; case Types.DATE: retVal = DateType.typeName(); break; case Types.TIMESTAMP: retVal = TimestampType.typeName(); break; case Types.BINARY: retVal = BinaryType.typeName(); break; case Types.DECIMAL: retVal = DecimalType.typeName(); break; case Types.ARRAY: retVal = ArrayType.typeName(); break; case Types.STRUCT: retVal = StructType.typeName(); break; case Types.BIGINT: retVal = LongType.typeName(); break; case Types.REAL: retVal = DoubleType.typeName(); break; default: break; } return retVal; } }
package slack.android.api.models; public class MatchMessage { private String type; private String user; private String username; private String ts; private String team; private MatchMessageChannel channel; private String permalink; private MatchMessageNext previous; private MatchMessageNext previous2; private MatchMessageNext next; private MatchMessageNext next2; private String text; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getTs() { return ts; } public void setTs(String ts) { this.ts = ts; } public String getTeam() { return team; } public void setTeam(String team) { this.team = team; } public MatchMessageChannel getChannel() { return channel; } public void setChannel(MatchMessageChannel channel) { this.channel = channel; } public String getPermalink() { return permalink; } public void setPermalink(String permalink) { this.permalink = permalink; } public MatchMessageNext getPrevious() { return previous; } public void setPrevious(MatchMessageNext previous) { this.previous = previous; } public MatchMessageNext getPrevious2() { return previous2; } public void setPrevious2(MatchMessageNext previous2) { this.previous2 = previous2; } public MatchMessageNext getNext() { return next; } public void setNext(MatchMessageNext next) { this.next = next; } public MatchMessageNext getNext2() { return next2; } public void setNext2(MatchMessageNext next2) { this.next2 = next2; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
/* * Copyright (C) 2015 Alberto Irurueta Carro (alberto@irurueta.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irurueta.ar.calibration.estimators; import com.irurueta.geometry.Point2D; import com.irurueta.geometry.estimators.LockedException; import com.irurueta.numerical.robust.RobustEstimatorMethod; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class RadialDistortionRobustEstimatorTest { @Test public void testCreate() { // test create with method // test RANSAC RadialDistortionRobustEstimator estimator = RadialDistortionRobustEstimator.create( RobustEstimatorMethod.RANSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertNull(estimator.getDistortedPoints()); assertNull(estimator.getUndistortedPoints()); assertNull(estimator.getDistortionCenter()); assertFalse(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.RANSAC); // test LMedS estimator = RadialDistortionRobustEstimator.create( RobustEstimatorMethod.LMedS); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertNull(estimator.getDistortedPoints()); assertNull(estimator.getUndistortedPoints()); assertNull(estimator.getDistortionCenter()); assertFalse(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.LMedS); // test MSAC estimator = RadialDistortionRobustEstimator.create( RobustEstimatorMethod.MSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertNull(estimator.getDistortedPoints()); assertNull(estimator.getUndistortedPoints()); assertNull(estimator.getDistortionCenter()); assertFalse(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.MSAC); // test PROSAC estimator = RadialDistortionRobustEstimator.create( RobustEstimatorMethod.PROSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertNull(estimator.getDistortedPoints()); assertNull(estimator.getUndistortedPoints()); assertNull(estimator.getDistortionCenter()); assertFalse(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.PROSAC); // test PROMedS estimator = RadialDistortionRobustEstimator.create( RobustEstimatorMethod.PROMedS); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertNull(estimator.getDistortedPoints()); assertNull(estimator.getUndistortedPoints()); assertNull(estimator.getDistortionCenter()); assertFalse(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.PROMedS); // test create with points, quality scores, center and method final List<Point2D> distortedPoints = new ArrayList<>(); final List<Point2D> undistortedPoints = new ArrayList<>(); final double[] qualityScores = new double[ RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS]; for (int i = 0; i < RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS; i++) { distortedPoints.add(Point2D.create()); undistortedPoints.add(Point2D.create()); } final Point2D center = Point2D.create(); // test RANSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, center, RobustEstimatorMethod.RANSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.RANSAC); // test LMedS estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, center, RobustEstimatorMethod.LMedS); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.LMedS); // test MSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, center, RobustEstimatorMethod.MSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.MSAC); // test PROSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, center, RobustEstimatorMethod.PROSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertSame(estimator.getQualityScores(), qualityScores); assertEquals(estimator.getMethod(), RobustEstimatorMethod.PROSAC); // test PROMedS estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, center, RobustEstimatorMethod.PROMedS); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertSame(estimator.getQualityScores(), qualityScores); assertEquals(estimator.getMethod(), RobustEstimatorMethod.PROMedS); // test create with points, center and method // test RANSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, center, RobustEstimatorMethod.RANSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.RANSAC); // test LMedS estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, center, RobustEstimatorMethod.LMedS); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.LMedS); // test MSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, center, RobustEstimatorMethod.MSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.MSAC); // test PROSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, center, RobustEstimatorMethod.PROSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.PROSAC); // test PROMedS estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, center, RobustEstimatorMethod.PROMedS); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.PROMedS); // test create with points, quality scores and method // test RANSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, RobustEstimatorMethod.RANSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.RANSAC); // test LMedS estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, RobustEstimatorMethod.LMedS); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.LMedS); // test MSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, RobustEstimatorMethod.MSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.MSAC); // test PROSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, RobustEstimatorMethod.PROSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertSame(estimator.getQualityScores(), qualityScores); assertEquals(estimator.getMethod(), RobustEstimatorMethod.PROSAC); // test PROMedS estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, RobustEstimatorMethod.PROMedS); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertSame(estimator.getQualityScores(), qualityScores); assertEquals(estimator.getMethod(), RobustEstimatorMethod.PROMedS); // test create with points and method // test RANSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, RobustEstimatorMethod.RANSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.RANSAC); // test LMedS estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, RobustEstimatorMethod.LMedS); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.LMedS); // test MSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, RobustEstimatorMethod.MSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.MSAC); // test PROSAC estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, RobustEstimatorMethod.PROSAC); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.PROSAC); // test PROMedS estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, RobustEstimatorMethod.PROMedS); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RobustEstimatorMethod.PROMedS); // test create with default method estimator = RadialDistortionRobustEstimator.create(); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertNull(estimator.getDistortedPoints()); assertNull(estimator.getUndistortedPoints()); assertNull(estimator.getDistortionCenter()); assertFalse(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RadialDistortionRobustEstimator.DEFAULT_ROBUST_METHOD); // test create with points and quality scores estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertSame(estimator.getQualityScores(), qualityScores); assertEquals(estimator.getMethod(), RadialDistortionRobustEstimator.DEFAULT_ROBUST_METHOD); // test create with points estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertNull(estimator.getDistortionCenter()); assertTrue(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RadialDistortionRobustEstimator.DEFAULT_ROBUST_METHOD); // test create with points, quality scores and center estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, qualityScores, center); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertTrue(estimator.isReady()); assertSame(estimator.getQualityScores(), qualityScores); assertEquals(estimator.getMethod(), RadialDistortionRobustEstimator.DEFAULT_ROBUST_METHOD); // test create with points and center estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, center); // check correctness assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); assertFalse(estimator.isLocked()); assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); assertSame(estimator.getDistortedPoints(), distortedPoints); assertSame(estimator.getUndistortedPoints(), undistortedPoints); assertSame(estimator.getDistortionCenter(), center); assertTrue(estimator.arePointsAvailable()); assertFalse(estimator.isReady()); assertNull(estimator.getQualityScores()); assertEquals(estimator.getMethod(), RadialDistortionRobustEstimator.DEFAULT_ROBUST_METHOD); } @Test public void testAreValidPoints() { final List<Point2D> distortedPoints = new ArrayList<>(); final List<Point2D> undistortedPoints = new ArrayList<>(); for (int i = 0; i < RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS; i++) { distortedPoints.add(Point2D.create()); undistortedPoints.add(Point2D.create()); } final List<Point2D> emptyPoints = new ArrayList<>(); assertTrue(RadialDistortionRobustEstimator.areValidPoints( distortedPoints, undistortedPoints)); assertFalse(RadialDistortionRobustEstimator.areValidPoints(emptyPoints, undistortedPoints)); assertFalse(RadialDistortionRobustEstimator.areValidPoints(emptyPoints, emptyPoints)); assertFalse(RadialDistortionRobustEstimator.areValidPoints(null, undistortedPoints)); assertFalse(RadialDistortionRobustEstimator.areValidPoints( distortedPoints, null)); } @Test public void testGetSetListener() throws LockedException { final List<Point2D> distortedPoints = new ArrayList<>(); final List<Point2D> undistortedPoints = new ArrayList<>(); for (int i = 0; i < RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS; i++) { distortedPoints.add(Point2D.create()); undistortedPoints.add(Point2D.create()); } final RadialDistortionRobustEstimatorListener listener = new RadialDistortionRobustEstimatorListener() { @Override public void onEstimateStart( final RadialDistortionRobustEstimator estimator) { } @Override public void onEstimateEnd( final RadialDistortionRobustEstimator estimator) { } @Override public void onEstimateNextIteration( final RadialDistortionRobustEstimator estimator, final int iteration) { } @Override public void onEstimateProgressChange( final RadialDistortionRobustEstimator estimator, final float progress) { } }; final RadialDistortionRobustEstimator estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints); // check default value assertNull(estimator.getListener()); assertFalse(estimator.isListenerAvailable()); // set new value estimator.setListener(listener); // check correctness assertSame(estimator.getListener(), listener); assertTrue(estimator.isListenerAvailable()); } @Test public void testGetSetProgressDelta() throws LockedException { final List<Point2D> distortedPoints = new ArrayList<>(); final List<Point2D> undistortedPoints = new ArrayList<>(); for (int i = 0; i < RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS; i++) { distortedPoints.add(Point2D.create()); undistortedPoints.add(Point2D.create()); } final RadialDistortionRobustEstimator estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints); // check default value assertEquals(estimator.getProgressDelta(), RadialDistortionRobustEstimator.DEFAULT_PROGRESS_DELTA, 0.0); // set new value estimator.setProgressDelta(0.5f); // check correctness assertEquals(estimator.getProgressDelta(), 0.5, 0.0); } @Test public void testGetSetConfidence() throws LockedException { final List<Point2D> distortedPoints = new ArrayList<>(); final List<Point2D> undistortedPoints = new ArrayList<>(); for (int i = 0; i < RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS; i++) { distortedPoints.add(Point2D.create()); undistortedPoints.add(Point2D.create()); } final RadialDistortionRobustEstimator estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints); // check default value assertEquals(estimator.getConfidence(), RadialDistortionRobustEstimator.DEFAULT_CONFIDENCE, 0.0); // set new value estimator.setConfidence(0.5f); // check correctness assertEquals(estimator.getConfidence(), 0.5, 0.0); } @Test public void testGetSetMaxIterations() throws LockedException { final List<Point2D> distortedPoints = new ArrayList<>(); final List<Point2D> undistortedPoints = new ArrayList<>(); for (int i = 0; i < RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS; i++) { distortedPoints.add(Point2D.create()); undistortedPoints.add(Point2D.create()); } final RadialDistortionRobustEstimator estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints); // check default value assertEquals(estimator.getMaxIterations(), RadialDistortionRobustEstimator.DEFAULT_MAX_ITERATIONS); // set new value estimator.setMaxIterations(10); // check correctness assertEquals(estimator.getMaxIterations(), 10); } @Test public void testGetSetPoints() throws LockedException { final List<Point2D> distortedPoints1 = new ArrayList<>(); final List<Point2D> undistortedPoints1 = new ArrayList<>(); final List<Point2D> distortedPoints2 = new ArrayList<>(); final List<Point2D> undistortedPoints2 = new ArrayList<>(); for (int i = 0; i < RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS; i++) { distortedPoints1.add(Point2D.create()); undistortedPoints1.add(Point2D.create()); distortedPoints2.add(Point2D.create()); undistortedPoints2.add(Point2D.create()); } final List<Point2D> emptyPoints = new ArrayList<>(); final RadialDistortionRobustEstimator estimator = RadialDistortionRobustEstimator.create(distortedPoints1, undistortedPoints1); // check correctness assertSame(estimator.getDistortedPoints(), distortedPoints1); assertSame(estimator.getUndistortedPoints(), undistortedPoints1); assertTrue(estimator.arePointsAvailable()); // set new value estimator.setPoints(distortedPoints2, undistortedPoints2); // check correctness assertSame(estimator.getDistortedPoints(), distortedPoints2); assertSame(estimator.getUndistortedPoints(), undistortedPoints2); assertTrue(estimator.arePointsAvailable()); // Force IllegalArgumentException try { estimator.setPoints(emptyPoints, undistortedPoints2); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { estimator.setPoints(emptyPoints, emptyPoints); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { estimator.setPoints(null, undistortedPoints2); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } try { estimator.setPoints(distortedPoints2, null); fail("IllegalArgumentException expected but not thrown"); } catch (final IllegalArgumentException ignore) { } } @Test public void testGetSetDistortionCenter() throws LockedException { final List<Point2D> distortedPoints = new ArrayList<>(); final List<Point2D> undistortedPoints = new ArrayList<>(); for (int i = 0; i < RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS; i++) { distortedPoints.add(Point2D.create()); undistortedPoints.add(Point2D.create()); } final Point2D center = Point2D.create(); final RadialDistortionRobustEstimator estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints); // check default value assertNull(estimator.getDistortionCenter()); // set new value estimator.setDistortionCenter(center); // check correctness assertSame(estimator.getDistortionCenter(), center); } @Test public void testGetSetQualityScores() throws LockedException { final List<Point2D> distortedPoints = new ArrayList<>(); final List<Point2D> undistortedPoints = new ArrayList<>(); final double[] qualityScores = new double[ RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS]; for (int i = 0; i < RadialDistortionRobustEstimator.MIN_NUMBER_OF_POINTS; i++) { distortedPoints.add(Point2D.create()); undistortedPoints.add(Point2D.create()); } final RadialDistortionRobustEstimator estimator = RadialDistortionRobustEstimator.create(distortedPoints, undistortedPoints, RobustEstimatorMethod.RANSAC); // check default value assertNull(estimator.getQualityScores()); // set new value estimator.setQualityScores(qualityScores); // check correctness assertNull(estimator.getQualityScores()); } }
package com.yuewawa.showhelper.biz.impl; import android.content.Context; import com.yuewawa.showhelper.biz.IFollowedShowBiz; import com.yuewawa.showhelper.dao.gen.FollowedShowDao; import com.yuewawa.showhelper.db.GreenDaoHelper; import com.yuewawa.showhelper.entity.FollowedShow; import java.util.List; /** * Created by Administrator on 2016-10-07. */ public class FollowedShowBiz implements IFollowedShowBiz{ private FollowedShowDao followedShowDao; public FollowedShowBiz(Context context) { followedShowDao = GreenDaoHelper.getInstance().getDaoSession(context).getFollowedShowDao(); } @Override public List<FollowedShow> getAllFollowedShows(Long userId) { String whereSql = "WHERE USER_ID=?"; return followedShowDao.queryRaw(whereSql, String.valueOf(userId)); } }
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.env.python.testing; import com.jetbrains.env.PyProcessWithConsoleTestTask; import com.jetbrains.env.ut.PyScriptTestProcessRunner; import com.jetbrains.python.tools.sdkTools.SdkCreationType; import org.jetbrains.annotations.NotNull; import org.junit.Assert; /** * Runs test with setup/teardown (script shall be test_test.py) and checks it works * * @author Ilya.Kazakevich */ abstract class SetupTearDownTestTask<T extends PyScriptTestProcessRunner<?>> extends PyProcessWithConsoleTestTask<T> { SetupTearDownTestTask() { super("testRunner/env/setup_teardown/", SdkCreationType.SDK_PACKAGES_ONLY); } @Override protected final void checkTestResults(@NotNull final T runner, @NotNull final String stdout, @NotNull final String stderr, @NotNull final String all) { if (runner.getCurrentRerunStep() == 0) { Assert.assertEquals(runner.getFormattedTestTree(), 1, runner.getFailedTestsCount()); Assert.assertEquals(runner.getFormattedTestTree(), 1, runner.getPassedTestsCount()); Assert.assertEquals(runner.getFormattedTestTree(), 2, runner.getAllTestsCount()); } else { Assert.assertEquals(runner.getFormattedTestTree(), 1, runner.getFailedTestsCount()); Assert.assertEquals(runner.getFormattedTestTree(), 0, runner.getPassedTestsCount()); Assert.assertEquals(runner.getFormattedTestTree(), 1, runner.getAllTestsCount()); } } }
package io.resttestgen.implementation.oracle; import io.resttestgen.core.testing.Oracle; import io.resttestgen.core.testing.TestResult; import io.resttestgen.core.testing.TestSequence; public class SchemaValidationOracle extends Oracle { @Override public TestResult assertTestSequence(TestSequence testSequence) { throw new InternalError("The SchemaValidationOracle is not available yet."); } }
/* * MIT License * * Copyright (c) 2021 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.diagnostics; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.diagnostics.TraceListener; import system.diagnostics.TraceListenerCollection; import system.Array; /** * The base .NET class managing System.Diagnostics.TraceListenerCollection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Diagnostics.TraceListenerCollection" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Diagnostics.TraceListenerCollection</a> */ public class TraceListenerCollection extends NetObjectEnumerable { /** * Fully assembly qualified name: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 */ public static final String assemblyFullName = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; /** * Assembly name: System */ public static final String assemblyShortName = "System"; /** * Qualified class name: System.Diagnostics.TraceListenerCollection */ public static final String className = "System.Diagnostics.TraceListenerCollection"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public TraceListenerCollection(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link TraceListenerCollection}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link TraceListenerCollection} instance * @throws java.lang.Throwable in case of error during cast operation */ public static TraceListenerCollection cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new TraceListenerCollection(from.getJCOInstance()); } // Constructors section public TraceListenerCollection() throws Throwable { } // Methods section public boolean Contains(TraceListener listener) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Invoke("Contains", listener == null ? null : listener.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int Add(TraceListener listener) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ArgumentOutOfRangeException, system.configuration.ConfigurationException, system.configuration.ConfigurationErrorsException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Invoke("Add", listener == null ? null : listener.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int IndexOf(TraceListener listener) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Invoke("IndexOf", listener == null ? null : listener.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void AddRange(TraceListener[] value) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.NotSupportedException, system.configuration.ConfigurationException, system.ArgumentOutOfRangeException, system.configuration.ConfigurationErrorsException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("AddRange", (java.lang.Object)toObjectFromArray(value)); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void AddRange(TraceListenerCollection value) throws Throwable, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.ArgumentException, system.NotSupportedException, system.configuration.ConfigurationException, system.configuration.ConfigurationErrorsException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("AddRange", value == null ? null : value.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void Clear() throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("Clear"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void CopyTo(TraceListener[] listeners, int index) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("CopyTo", toObjectFromArray(listeners), index); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void Insert(int index, TraceListener listener) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ArgumentOutOfRangeException, system.configuration.ConfigurationException, system.configuration.ConfigurationErrorsException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("Insert", index, listener == null ? null : listener.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void Remove(TraceListener listener) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("Remove", listener == null ? null : listener.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void Remove(java.lang.String name) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("Remove", name); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void RemoveAt(int index) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("RemoveAt", index); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIList method available in IList to obtain an object with an invocable method */ @Deprecated public boolean Contains(NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIList to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIList method available in IList to obtain an object with an invocable method */ @Deprecated public int Add(NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIList to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIList method available in IList to obtain an object with an invocable method */ @Deprecated public int IndexOf(NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIList to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIList method available in IList to obtain an object with an invocable method */ @Deprecated public void Insert(int index, NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIList to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIList method available in IList to obtain an object with an invocable method */ @Deprecated public void Remove(NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIList to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToICollection method available in ICollection to obtain an object with an invocable method */ @Deprecated public void CopyTo(Array array, int index) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToICollection to obtain the full interface."); } // Properties section public int getCount() throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("Count"); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Instance Events section }
/******************************************************************************* * Software Name : RCS IMS Stack * * Copyright (C) 2010-2016 Orange. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.gsma.rcs.core.ims.service.capability; import com.gsma.rcs.core.ims.service.ImsServiceError; /** * Capability error * * @author jexa7410 */ public class CapabilityError extends ImsServiceError { static final long serialVersionUID = 1L; /** * Options has failed */ public final static int OPTIONS_FAILED = CAPABILITY_ERROR_CODES + 1; /** * Constructor * * @param code Error code */ public CapabilityError(int code) { super(code); } /** * Constructor * * @param code Error code * @param msg Detail message */ public CapabilityError(int code, String msg) { super(code, msg); } /** * Constructor * * @param code Error code * @param cause the cause (which is saved for later retrieval by the Throwable.getCause() * method). (A null value is permitted, and indicates that the cause is nonexistent * or unknown.) */ public CapabilityError(int code, Throwable cause) { super(code, cause); } }
package com.mi.http.adapterfactory; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; final class FakeTypeAdapterRuntimeTypeWrapper<T> extends TypeAdapter<T> { private final Gson context; private final TypeAdapter<T> delegate; private final Type type; FakeTypeAdapterRuntimeTypeWrapper(Gson context, TypeAdapter<T> delegate, Type type) { this.context = context; this.delegate = delegate; this.type = type; } @Override public T read(JsonReader in) throws IOException { return delegate.read(in); } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public void write(JsonWriter out, T value) throws IOException { // Order of preference for choosing type adapters // First preference: a type adapter registered for the runtime type // Second preference: a type adapter registered for the declared type // Third preference: reflective type adapter for the runtime type (if it is a sub class of the declared type) // Fourth preference: reflective type adapter for the declared type TypeAdapter chosen = delegate; Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value); if (runtimeType != type) { TypeAdapter runtimeTypeAdapter = context.getAdapter(TypeToken.get(runtimeType)); if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) { // The user registered a type adapter for the runtime type, so we will use that chosen = runtimeTypeAdapter; } else if (!(delegate instanceof ReflectiveTypeAdapterFactory.Adapter)) { // The user registered a type adapter for Base class, so we prefer it over the // reflective type adapter for the runtime type chosen = delegate; } else { // Use the type adapter for runtime type chosen = runtimeTypeAdapter; } } chosen.write(out, value); } /** * Finds a compatible runtime type if it is more specific */ private Type getRuntimeTypeIfMoreSpecific(Type type, Object value) { if (value != null && (type == Object.class || type instanceof TypeVariable<?> || type instanceof Class<?>)) { type = value.getClass(); } return type; } }
package gumtree.spoon.builder; import java.util.HashMap; import java.util.List; import java.util.Map; import com.github.gumtreediff.actions.model.Action; import com.github.gumtreediff.tree.ITree; import com.github.gumtreediff.tree.TreeContext; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import gumtree.spoon.diff.operations.Operation; import spoon.reflect.declaration.CtElement; /** * * Creates a JSON representation of a Spoon Java abstract syntaxt tree. * * @author Matias Martinez * */ public class Json4SpoonGenerator { public enum JSON_PROPERTIES { label, type, op, children; }; @SuppressWarnings("rawtypes") public JsonObject getJSONasJsonObject(CtElement element) { SpoonGumTreeBuilder builder = new SpoonGumTreeBuilder(); ITree generatedTree = builder.getTree(element); TreeContext tcontext = builder.getTreeContext(); return this.getJSONasJsonObject(tcontext, generatedTree); } public String getJSONasString(CtElement element) { SpoonGumTreeBuilder builder = new SpoonGumTreeBuilder(); ITree generatedTree = builder.getTree(element); TreeContext tcontext = builder.getTreeContext(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(this.getJSONasJsonObject(tcontext, generatedTree)) + "\n"; } private JsonObject getJSONasJsonObject(TreeContext context, ITree tree) { JsonObject o = new JsonObject(); o.addProperty(JSON_PROPERTIES.label.toString(), tree.getLabel()); o.addProperty(JSON_PROPERTIES.type.toString(), context.getTypeLabel(tree)); JsonArray nodeChildens = new JsonArray(); o.add(JSON_PROPERTIES.children.toString(), nodeChildens); for (ITree tch : tree.getChildren()) { JsonObject childJSon = getJSONasJsonObject(context, tch); if (childJSon != null) nodeChildens.add(childJSon); } return o; } /** * Decorates a node with the affected operator, if any. * * @param context * @param tree * @param operations * @return */ public JsonObject getJSONasJsonObject(TreeContext context, ITree tree, List<Operation> operations) { // Collect all nodes and get the operator Map<ITree, Operation> nodesAffectedByOps = new HashMap<>(); for (Operation operation : operations) { nodesAffectedByOps.put(operation.getAction().getNode(), operation); } return getJSONasJsonObject(context, tree, operations, nodesAffectedByOps); } @SuppressWarnings("unused") private JsonObject getJSONasJsonObject(TreeContext context, ITree tree, List<Operation> operations, Map<ITree, Operation> nodesAffectedByOps) { JsonObject o = new JsonObject(); o.addProperty(JSON_PROPERTIES.label.toString(), tree.getLabel()); o.addProperty(JSON_PROPERTIES.type.toString(), context.getTypeLabel(tree)); if (nodesAffectedByOps.containsKey(tree)) { Operation<Action> operationOverTree = nodesAffectedByOps.get(tree); o.addProperty(JSON_PROPERTIES.op.toString(), operationOverTree.getAction().getName()); } JsonArray nodeChildens = new JsonArray(); o.add(JSON_PROPERTIES.children.toString(), nodeChildens); for (ITree tch : tree.getChildren()) { JsonObject childJSon = getJSONasJsonObject(context, tch, operations); if (childJSon != null) nodeChildens.add(childJSon); } return o; } }
package org.springframework.web.bind.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; /** * Annotation which indicates that a method parameter should be bound to an HTTP cookie. * * The method parameter may be declared as type {@link javax.servlet.http.Cookie} * or as cookie value type (String, int, etc.). * * @author Sam Brannen * @since 3.0 * @see RequestMapping * @see RequestParam * @see RequestHeader * @see org.springframework.web.bind.annotation.RequestMapping */ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CookieValue { /** * Alias for {@link #name}. */ @AliasFor("name") String value() default ""; /** * The name of the cookie to bind to. * @since 4.2 */ @AliasFor("value") String name() default ""; /** * Whether the cookie is required. * Defaults to {@code true}, leading to an exception being thrown * if the cookie is missing in the request. Switch this to * {@code false} if you prefer a {@code null} value if the cookie is * not present in the request. * Alternatively, provide a {@link #defaultValue}, which implicitly * sets this flag to {@code false}. */ boolean required() default true; /** * The default value to use as a fallback. * Supplying a default value implicitly sets {@link #required} to * {@code false}. */ String defaultValue() default ValueConstants.DEFAULT_NONE; }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.plugin.cassandra; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.airlift.json.JsonCodec; import io.airlift.slice.Slice; import io.prestosql.plugin.cassandra.util.CassandraCqlUtils; import io.prestosql.spi.PrestoException; import io.prestosql.spi.connector.ColumnHandle; import io.prestosql.spi.connector.ColumnMetadata; import io.prestosql.spi.connector.ConnectorInsertTableHandle; import io.prestosql.spi.connector.ConnectorMetadata; import io.prestosql.spi.connector.ConnectorNewTableLayout; import io.prestosql.spi.connector.ConnectorOutputMetadata; import io.prestosql.spi.connector.ConnectorOutputTableHandle; import io.prestosql.spi.connector.ConnectorSession; import io.prestosql.spi.connector.ConnectorTableHandle; import io.prestosql.spi.connector.ConnectorTableMetadata; import io.prestosql.spi.connector.ConnectorTableProperties; import io.prestosql.spi.connector.Constraint; import io.prestosql.spi.connector.ConstraintApplicationResult; import io.prestosql.spi.connector.NotFoundException; import io.prestosql.spi.connector.SchemaNotFoundException; import io.prestosql.spi.connector.SchemaTableName; import io.prestosql.spi.connector.SchemaTablePrefix; import io.prestosql.spi.connector.TableNotFoundException; import io.prestosql.spi.predicate.TupleDomain; import io.prestosql.spi.statistics.ComputedStatistics; import io.prestosql.spi.type.Type; import javax.inject.Inject; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.prestosql.plugin.cassandra.CassandraType.toCassandraType; import static io.prestosql.plugin.cassandra.util.CassandraCqlUtils.cqlNameToSqlName; import static io.prestosql.plugin.cassandra.util.CassandraCqlUtils.validSchemaName; import static io.prestosql.plugin.cassandra.util.CassandraCqlUtils.validTableName; import static io.prestosql.spi.StandardErrorCode.NOT_SUPPORTED; import static io.prestosql.spi.StandardErrorCode.PERMISSION_DENIED; import static java.lang.String.format; import static java.util.Locale.ENGLISH; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; public class CassandraMetadata implements ConnectorMetadata { private final CassandraSession cassandraSession; private final CassandraPartitionManager partitionManager; private final boolean allowDropTable; private final JsonCodec<List<ExtraColumnMetadata>> extraColumnMetadataCodec; @Inject public CassandraMetadata( CassandraSession cassandraSession, CassandraPartitionManager partitionManager, JsonCodec<List<ExtraColumnMetadata>> extraColumnMetadataCodec, CassandraClientConfig config) { this.partitionManager = requireNonNull(partitionManager, "partitionManager is null"); this.cassandraSession = requireNonNull(cassandraSession, "cassandraSession is null"); this.allowDropTable = requireNonNull(config, "config is null").getAllowDropTable(); this.extraColumnMetadataCodec = requireNonNull(extraColumnMetadataCodec, "extraColumnMetadataCodec is null"); } @Override public List<String> listSchemaNames(ConnectorSession session) { return cassandraSession.getCaseSensitiveSchemaNames().stream() .map(name -> name.toLowerCase(ENGLISH)) .collect(toImmutableList()); } @Override public CassandraTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName) { requireNonNull(tableName, "tableName is null"); try { return cassandraSession.getTable(tableName).getTableHandle(); } catch (TableNotFoundException | SchemaNotFoundException e) { // table was not found return null; } } private static SchemaTableName getTableName(ConnectorTableHandle tableHandle) { return ((CassandraTableHandle) tableHandle).getSchemaTableName(); } @Override public ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle tableHandle) { requireNonNull(tableHandle, "tableHandle is null"); return getTableMetadata(getTableName(tableHandle)); } private ConnectorTableMetadata getTableMetadata(SchemaTableName tableName) { CassandraTable table = cassandraSession.getTable(tableName); List<ColumnMetadata> columns = table.getColumns().stream() .map(CassandraColumnHandle::getColumnMetadata) .collect(toList()); return new ConnectorTableMetadata(tableName, columns); } @Override public List<SchemaTableName> listTables(ConnectorSession session, Optional<String> schemaName1) { ImmutableList.Builder<SchemaTableName> tableNames = ImmutableList.builder(); List<String> schemaNames = listSchemas(session, schemaName1); for (String schemaName : schemaNames) { try { for (String tableName : cassandraSession.getCaseSensitiveTableNames(schemaName)) { tableNames.add(new SchemaTableName(schemaName, tableName.toLowerCase(ENGLISH))); } } catch (SchemaNotFoundException e) { // schema disappeared during listing operation } } return tableNames.build(); } private List<String> listSchemas(ConnectorSession session, Optional<String> schemaName) { return schemaName.map(ImmutableList::of) .orElseGet(() -> (ImmutableList<String>) listSchemaNames(session)); } @Override public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle) { requireNonNull(session, "session is null"); requireNonNull(tableHandle, "tableHandle is null"); CassandraTable table = cassandraSession.getTable(getTableName(tableHandle)); ImmutableMap.Builder<String, ColumnHandle> columnHandles = ImmutableMap.builder(); for (CassandraColumnHandle columnHandle : table.getColumns()) { columnHandles.put(cqlNameToSqlName(columnHandle.getName()).toLowerCase(ENGLISH), columnHandle); } return columnHandles.build(); } @Override public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) { requireNonNull(prefix, "prefix is null"); ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder(); for (SchemaTableName tableName : listTables(session, prefix)) { try { columns.put(tableName, getTableMetadata(tableName).getColumns()); } catch (NotFoundException e) { // table disappeared during listing operation } } return columns.build(); } private List<SchemaTableName> listTables(ConnectorSession session, SchemaTablePrefix prefix) { if (!prefix.getTable().isPresent()) { return listTables(session, prefix.getSchema()); } return ImmutableList.of(prefix.toSchemaTableName()); } @Override public ColumnMetadata getColumnMetadata(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle columnHandle) { return ((CassandraColumnHandle) columnHandle).getColumnMetadata(); } @Override public boolean usesLegacyTableLayouts() { return false; } @Override public Optional<ConstraintApplicationResult<ConnectorTableHandle>> applyFilter(ConnectorSession session, ConnectorTableHandle tableHandle, Constraint constraint) { CassandraTableHandle handle = (CassandraTableHandle) tableHandle; CassandraPartitionResult partitionResult = partitionManager.getPartitions(handle, constraint.getSummary()); String clusteringKeyPredicates = ""; TupleDomain<ColumnHandle> unenforcedConstraint; if (partitionResult.isUnpartitioned()) { unenforcedConstraint = partitionResult.getUnenforcedConstraint(); } else { CassandraClusteringPredicatesExtractor clusteringPredicatesExtractor = new CassandraClusteringPredicatesExtractor( cassandraSession.getTable(handle.getSchemaTableName()).getClusteringKeyColumns(), partitionResult.getUnenforcedConstraint(), cassandraSession.getCassandraVersion()); clusteringKeyPredicates = clusteringPredicatesExtractor.getClusteringKeyPredicates(); unenforcedConstraint = clusteringPredicatesExtractor.getUnenforcedConstraints(); } Optional<List<CassandraPartition>> currentPartitions = handle.getPartitions(); if (currentPartitions.isPresent() && // TODO: we should skip only when new table handle does not narrow down enforced predicate currentPartitions.get().containsAll(partitionResult.getPartitions()) && handle.getClusteringKeyPredicates().equals(clusteringKeyPredicates)) { return Optional.empty(); } return Optional.of( new ConstraintApplicationResult<>(new CassandraTableHandle( handle.getSchemaName(), handle.getTableName(), Optional.of(partitionResult.getPartitions()), clusteringKeyPredicates), unenforcedConstraint)); } @Override public ConnectorTableProperties getTableProperties(ConnectorSession session, ConnectorTableHandle table) { return new ConnectorTableProperties(); } @Override public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting) { throw new PrestoException(NOT_SUPPORTED, "CREATE TABLE not yet supported for Cassandra"); } @Override public void dropTable(ConnectorSession session, ConnectorTableHandle tableHandle) { checkArgument(tableHandle instanceof CassandraTableHandle, "tableHandle is not an instance of CassandraTableHandle"); if (!allowDropTable) { throw new PrestoException(PERMISSION_DENIED, "DROP TABLE is disabled in this Cassandra catalog"); } CassandraTableHandle cassandraTableHandle = (CassandraTableHandle) tableHandle; if (cassandraSession.isMaterializedView(cassandraTableHandle.getSchemaTableName())) { throw new PrestoException(NOT_SUPPORTED, "Dropping materialized views not yet supported"); } cassandraSession.execute(format("DROP TABLE \"%s\".\"%s\"", cassandraTableHandle.getSchemaName(), cassandraTableHandle.getTableName())); } @Override public void renameTable(ConnectorSession session, ConnectorTableHandle tableHandle, SchemaTableName newTableName) { throw new PrestoException(NOT_SUPPORTED, "Renaming tables not yet supported for Cassandra"); } @Override public ConnectorOutputTableHandle beginCreateTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, Optional<ConnectorNewTableLayout> layout) { ImmutableList.Builder<String> columnNames = ImmutableList.builder(); ImmutableList.Builder<Type> columnTypes = ImmutableList.builder(); ImmutableList.Builder<ExtraColumnMetadata> columnExtra = ImmutableList.builder(); columnExtra.add(new ExtraColumnMetadata("id", true)); for (ColumnMetadata column : tableMetadata.getColumns()) { columnNames.add(column.getName()); columnTypes.add(column.getType()); columnExtra.add(new ExtraColumnMetadata(column.getName(), column.isHidden())); } // get the root directory for the database SchemaTableName table = tableMetadata.getTable(); String schemaName = cassandraSession.getCaseSensitiveSchemaName(table.getSchemaName()); String tableName = table.getTableName(); List<String> columns = columnNames.build(); List<Type> types = columnTypes.build(); StringBuilder queryBuilder = new StringBuilder(format("CREATE TABLE \"%s\".\"%s\"(id uuid primary key", schemaName, tableName)); for (int i = 0; i < columns.size(); i++) { String name = columns.get(i); Type type = types.get(i); queryBuilder.append(", ") .append(name) .append(" ") .append(toCassandraType(type, cassandraSession.getProtocolVersion()).name().toLowerCase(ENGLISH)); } queryBuilder.append(") "); // encode column ordering in the cassandra table comment field since there is no better place to store this String columnMetadata = extraColumnMetadataCodec.toJson(columnExtra.build()); queryBuilder.append("WITH comment='").append(CassandraSession.PRESTO_COMMENT_METADATA).append(" ").append(columnMetadata).append("'"); // We need to create the Cassandra table before commit because the record needs to be written to the table. cassandraSession.execute(queryBuilder.toString()); return new CassandraOutputTableHandle( schemaName, tableName, columnNames.build(), columnTypes.build()); } @Override public Optional<ConnectorOutputMetadata> finishCreateTable(ConnectorSession session, ConnectorOutputTableHandle tableHandle, Collection<Slice> fragments, Collection<ComputedStatistics> computedStatistics) { return Optional.empty(); } @Override public ConnectorInsertTableHandle beginInsert(ConnectorSession session, ConnectorTableHandle tableHandle) { CassandraTableHandle table = (CassandraTableHandle) tableHandle; if (cassandraSession.isMaterializedView(table.getSchemaTableName())) { throw new PrestoException(NOT_SUPPORTED, "Inserting into materialized views not yet supported"); } SchemaTableName schemaTableName = new SchemaTableName(table.getSchemaName(), table.getTableName()); List<CassandraColumnHandle> columns = cassandraSession.getTable(schemaTableName).getColumns(); List<String> columnNames = columns.stream().map(CassandraColumnHandle::getName).map(CassandraCqlUtils::validColumnName).collect(Collectors.toList()); List<Type> columnTypes = columns.stream().map(CassandraColumnHandle::getType).collect(Collectors.toList()); return new CassandraInsertTableHandle( validSchemaName(table.getSchemaName()), validTableName(table.getTableName()), columnNames, columnTypes); } @Override public Optional<ConnectorOutputMetadata> finishInsert(ConnectorSession session, ConnectorInsertTableHandle insertHandle, Collection<Slice> fragments, Collection<ComputedStatistics> computedStatistics) { return Optional.empty(); } }
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.route53recoveryreadiness.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.route53recoveryreadiness.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * GetCellReadinessSummaryRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetCellReadinessSummaryRequestMarshaller { private static final MarshallingInfo<String> CELLNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("cellName").build(); private static final MarshallingInfo<Integer> MAXRESULTS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("maxResults").build(); private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("nextToken").build(); private static final GetCellReadinessSummaryRequestMarshaller instance = new GetCellReadinessSummaryRequestMarshaller(); public static GetCellReadinessSummaryRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(GetCellReadinessSummaryRequest getCellReadinessSummaryRequest, ProtocolMarshaller protocolMarshaller) { if (getCellReadinessSummaryRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getCellReadinessSummaryRequest.getCellName(), CELLNAME_BINDING); protocolMarshaller.marshall(getCellReadinessSummaryRequest.getMaxResults(), MAXRESULTS_BINDING); protocolMarshaller.marshall(getCellReadinessSummaryRequest.getNextToken(), NEXTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
/* Copyright (c) 2008-2016 Petr Svenda <petr@svenda.com> LICENSE TERMS The free distribution and use of this software in both source and binary form is allowed (with or without changes) provided that: 1. distributions of this source code include the above copyright notice, this list of conditions and the following disclaimer; 2. distributions in binary form include the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other associated materials; 3. the copyright holder's name is not used to endorse products built using this software without specific written permission. ALTERNATIVELY, provided that this notice is retained in full, this product may be distributed under the terms of the GNU General Public License (GPL), in which case the provisions of the GPL apply INSTEAD OF those given above. DISCLAIMER This software is provided 'as is' with no explicit or implied warranties in respect of its properties, including, but not limited to, correctness and/or fitness for purpose. Please, report any bugs to author <petr@svenda.com> */ package algtestprocess; import static algtestprocess.JCinfohtml.*; import static algtestprocess.RunTime.*; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Collections; /** * Class provide generation of scalability graphs which shows dependency between length of processed data and operation time. * @author rk */ public class ScalabilityGraph { public static final String descFunctionsFile = "desc.txt"; public static void beginScalabilityHTML(FileOutputStream file, String title) throws IOException { String toFile = ""; toFile += "<html lang=\"en\">\n"; toFile += " <head>\n"; toFile += "\t<meta charset=\"utf-8\">\n" + "\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n"+ "\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n"; toFile += "\t<meta name=\"description\" content=\"The JCAlgTest is a tool designed for automatic gathering various performance properties of Java cards. \">\n" + "\t<meta name=\"author\" content=\"JCAlgTest\">\n" + "\t<title>"+title+"</title>\n"; toFile += "\t<link href=\"../dist/css/bootstrap.min.css\" rel=\"stylesheet\">\n" + "<script type=\"text/javascript\" src=\"../dist/jquery-2.2.3.min.js\"></script>\n" + "\t<link href=\"../assets/css/ie10-viewport-bug-workaround.css\" rel=\"stylesheet\">\n" + "\t<link rel=\"stylesheet\" type=\"text/css\" href=\"../dist/style.css\">\n"; toFile += " </head>\n\n"; toFile += " <body style=\"margin-top:50px; padding:20px\">\n\n"; toFile += " \t<nav class=\"navbar navbar-inverse navbar-fixed-top\">\n\t\t<div class=\"container-fluid\">\n\t\t<script type=\"text/javascript\" src=\"../header-1.js\"></script>\n\t\t</div>\n\t</nav>\n\n"; file.write(toFile.getBytes()); } private static HashMap<String, String> loadDescription() throws IOException { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(descFunctionsFile)); } catch (IOException e) { // System.out.println("INFO: Description of functions file not found"); } String[] lineArray; String line; HashMap<String, String> descMap = new HashMap<>(); if (reader != null) { String name = ""; Snippet snippet = new Snippet(); while ((line = reader.readLine()) != null) { if (!(line.trim().isEmpty())) { if(line.contains("/////")){ if(!(name.isEmpty())){ descMap.put(name, snippet.getSnippet()); snippet.clear(); } name = line.substring(5).trim(); } else { snippet.addline(line); } } } } return descMap; } public static void parseGraphsPage(List<String> lines, FileOutputStream file, String nameOfCard, Boolean toponly) throws FileNotFoundException, IOException { List<String> topFunctions = new ArrayList<>(); List<String> usedFunctions = new ArrayList<>(); //List<String> dFunctions = new ArrayList<>(); if(toponly) loadTopFunctions(topFunctions, null); StringBuilder toFile = new StringBuilder(); StringBuilder chart = new StringBuilder(); //end of test details (1st div), end of beginning (2nd div) toFile.append("</br></div>\n</div>\n\t<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n"); toFile.append("\n<script>\ngoogle.charts.load('current', {packages: ['corechart']});\n</script>\n"); Integer lp = 0; String methodName = ""; while (lp < lines.size() - 20) { if (lines.get(lp).contains("method name:")) { methodName = lines.get(lp).split(";")[1]; if (methodName.startsWith(" ")) { methodName = methodName.substring(1); } if ((topFunctions.contains(methodName)) || (topFunctions.size() == 0)) { chart.append("\t<script type=\"text/javascript\">\n" + "\tgoogle.setOnLoadCallback(drawFancyVisualization);\n" + "\tfunction drawFancyVisualization() {\n" + "\t\tvar data = new google.visualization.DataTable();\n" + "\t\tdata.addColumn('number', 'length of data (bytes)');\n" + "\t\tdata.addColumn('number', 'Time (ms)');\n" + "\t\tdata.addColumn({type:'number', role:'interval'});\n" + "\t\tdata.addColumn({type:'number', role:'interval'});\n" + "\t\tdata.addColumn({type:'string', role:'annotation'});\n" + "\t\tdata.addColumn({type:'boolean',role:'certainty'});\n" + "\t\tdata.addRows(["); while (lp < lines.size() - 6) { if (lines.get(lp).contains(methodName)) { lp = parseOneForGraph(lines, chart, lp); } else if (lines.get(lp).contains("method name:")) { break; } else { lp++; } } chart.append("]);\n\n" + "\tvar options = {\n" // + "\t\ttitle: '" + methodName + "',\n" //+ "\t\ttitleTextStyle: {fontSize: 15},\n" + "\t\tbackgroundColor: \"transparent\",\n" + "\t\thAxis: {title: 'length of data (bytes)', viewWindow: {min: 0, max: "+ (chart.toString().contains("512") ? "530" : "265") +"} },\n" + "\t\tvAxis: {title: 'duration of operation (ms)' },\n" + "\t\tlegend:'none',};\n\n" + "\tvar chart = new google.visualization.LineChart(document.getElementById('" + methodName.replaceAll(" ", "_") + "'));\n" + "\tchart.draw(data, options);\n" + "\t}\n\t</script>\n"); if (!(chart.toString().contains("data.addRows([]);"))) { usedFunctions.add(methodName); toFile.append(chart.toString()); } chart.delete(0, chart.length() - 1); } else { lp++; } } else { lp++; } } HashMap<String, String> descMap = loadDescription(); BigDecimal sec = new BigDecimal(2 + usedFunctions.size()*0.15); sec = sec.setScale(2, BigDecimal.ROUND_HALF_UP); toFile.append("<div class=\"row\">\n"); for (String usedFunction : usedFunctions) { toFile.append("\t<div class=\"graph\">\n"); toFile.append("\t<h4 style=\"margin-left:40px\">"+usedFunction+"</h4>\n"); if(descMap.containsKey(usedFunction)){ toFile.append("\t<div style=\"margin-left: 40px;\">"); toFile.append(descMap.get(usedFunction)); toFile.append("\n\t</div>\n"); } if(descMap.containsKey(usedFunction)) toFile.append("\t<div id=\"" + usedFunction.replaceAll(" ", "_") + "\" style=\"min-height:400px; margin-top:-50px;\">"); else toFile.append("\t<div id=\"" + usedFunction.replaceAll(" ", "_") + "\" style=\"min-height:479px; margin-top:-50px;\">"); // <h4 style=\"text-align: center;\">" + usedFunction + "</h4> toFile.append("<p style=\"text-align: center; margin-top:70px\"><strong>GRAPH IS LOADING. </br></br> THIS MAY TAKE <u>"+ sec +"</u> SECONDS DEPENDING ON THE NUMBER OF GRAPHS.</strong></p></div>\n"); toFile.append("\t</div>\n\n"); } toFile.append("</div>\n<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n"); //quick links to generated charts at the beginning of html file String toFileBegin; toFileBegin = "<div class=\"col-md-7 col-xs-7\">\n"; toFileBegin += "<h3>Quick links | number of graphs: "+usedFunctions.size()+" | est. load time: "+ sec +" s</h3>\n<ul style=\"list-style-type: circle;\">\n"; for (String usedFunction : usedFunctions) { toFileBegin += "\t<li>" + "<a href=\"#" + usedFunction.replaceAll(" ", "_") + "\">" + usedFunction + "</a>" + "</li>\n"; } toFileBegin += "</ul>\n</div>\n"; addCardInfo(file, nameOfCard); file.write(toFileBegin.getBytes()); //quick links written //test details generated at the beginning of html file detailsBasic(lines, file); //details written file.write("\t\t</div>\n\t\t<div class=\"row\">\n".getBytes()); file.write(toFile.toString().getBytes()); //charts written file.write("\t\t</div>\n\t</div>".getBytes()); } private static void addCardInfo(FileOutputStream file, String name) throws IOException{ StringBuilder toFile = new StringBuilder(); toFile.append("\t<div class=\"container-fluid\">\n\t\t<div class=\"row\">\n"); toFile.append("\t\t\t<h1>Run time results - "+name+"</h1>\n"); toFile.append("\t\t\t<p>The performance of the card and given algorithm changes with the length of processed data. Here we provide detailed performance for relevant methods expected to process input with variable lengths (e.g., Cipher.doFinal()). We measured the execution time for data lengths of 16, 32, 64, 128, 256 and 512 bytes and visualize in a graph. Multiple measurements of the same method and fixed data length are performed to capture its variability. Read more about how the measurement was done <a href=\"scalability.html\">here</a>.\n</p>\n"); file.write(toFile.toString().getBytes()); } public static String generateScalabilityFile(String input, String outDir, Boolean toponly) throws IOException { StringBuilder cardName = new StringBuilder(); String cardNameFile = "noname_scalability"; List<String> lines = initalize(input, cardName); //load lines to from file to List String resultsDir = new File(outDir).getParentFile().toString(); if (!(cardName.toString().equals("")) && !(cardName.toString().equals(" "))){ cardNameFile = cardName.toString().replaceAll(" ", ""); cardNameFile = cardNameFile.replaceAll("_", ""); } new File(outDir + "/scalability").mkdirs(); FileOutputStream file = new FileOutputStream(outDir + "/scalability/" + cardNameFile + ".html"); beginScalabilityHTML(file, "JCAlgTest - Scalability graph - " + cardName.toString()); parseGraphsPage(lines, file, cardName.toString(), toponly); endRunTimeHTML(file); //System.out.println("Make sure that CSS file & JS files (\"Source\" folder) is present in output folder."); return cardName.toString(); } public static List<String> generateScalabilityFolder(String dir, String outDir, Boolean toponly) throws IOException { List<String> files = listFilesForFolder(new File(dir)); List<String> namesOfCards = new ArrayList<>(); //load data from input files (fixed-size perf data) and store name of card for(String filePath : files) namesOfCards.add(generateScalabilityFile(filePath, outDir, toponly)); return namesOfCards; } public static void generateScalabilityMain(String dir, String outDir, List<String> namesOfCards) throws IOException { FileOutputStream page = new FileOutputStream(outDir + "/scalability/scalability.html"); beginRunTimeHTML(page, "JCAlgTest - Scalability graphs"); StringBuilder toFile = new StringBuilder(); toFile.append("\t<div class=\"container\">\n"); toFile.append("\t\t<div class=\"row\">\n"); toFile.append("\t\t<h1>Algorithm performance for different length of processed data</h1>\n<br>\n"); toFile.append("\t\t\t<img src=\"../pics/scalability_example.png\" alt=\"Run time table example\" class=\"img-responsive\" align=\"right\" style=\"margin-left:20px; max-width:45%\">\n"); toFile.append("\t\t<p>The performance of the card and given algorithm changes with the length of processed data. Here we provide detailed performance for relevant methods expected to process input with variable lengths (e.g., Cipher.doFinal()). We measured the execution time for data lengths of 16, 32, 64, 128, 256 and 512 bytes and visualize in a graph. Multiple measurements of the same method and fixed data length are performed to capture its variability. </p>\n"); toFile.append("\t\t<p>We also included measurements of several methods usually used together in single sequence (e.g., set key, init the engine and sign the data). Note that resulting time is not simply the sum of operations measured separately as JavaCard Virtual Machine itself influence the results same way as caching and other optimizations do for ordinary CPUs. Used key values are randomly generated to prevent JCVM optimizations by skipping already performed initialization.</p>\n"); toFile.append("\t\t<p>Note that as many algorithms are block-based, you will experience almost the same execution time until the length of the process data exceeds the length of internal algorithm block (e.g, 64 bytes for SHA-2 hash) after which significantly more operations are executed to process another full block. Similar behavior but with a different underlying cause can be observed when the length in processed data exceeds the length of engine's internal memory buffers. Finally, it often makes sense to concatenate multiple independent blocks into a buffer and then call processing method only once as actual processing (e.g., encryption) is only part of the operation - context switch between card's main processor and crypto co-processor may be significant.</p><br>\n"); toFile.append("\t\t<div class=\"alert alert-warning\" role=\"alert\">It may take a few seconds to load all graphs on page.<br> Click on the target smart card to display its length-dependent performance. If you would like to see measurements of all operations please visit <a href=\"../run_time/execution-time.html\">Performance details page</a>.\n </div>\n"); toFile.append("\t\t\t</div>\n"); toFile.append("\t\t<div>\n"); toFile.append("\t\t<h3>List of tested Java Cards: </h3>\n"); toFile.append("\t\t<ul class=\"list-group\">\n"); for(String name : namesOfCards){ String cardNameFile = name; if (!(cardNameFile.equals("")) && !(cardNameFile.equals(" "))){ cardNameFile = cardNameFile.replaceAll(" ", ""); cardNameFile = cardNameFile.replaceAll("_", ""); } toFile.append("\t\t\t<li class=\"list-group-item\"><a href=\""+cardNameFile+".html\">"+name+"</a></li>\n"); } toFile.append("\t\t</ul>\n"); toFile.append("\t\t</div>\n"); toFile.append("\t</div>\n"); page.write(toFile.toString().getBytes()); endRunTimeHTML(page); page.close(); } public static void runScalability(String dir, String outDir, Boolean toponly) throws FileNotFoundException, IOException{ List<String> namesOfCards = generateScalabilityFolder(dir, outDir, false); // sort cards by names Collections.sort(namesOfCards); generateScalabilityMain(dir, outDir, namesOfCards); // System.out.println("ADD all necessary scripts (header-1.js, RadarChart.js) to new generated folder."); } /* public static void main(String [] args) throws FileNotFoundException, IOException{ String dir = "D:/JCAlgTest/variable/"; List<String> namesOfCards = generateScalabilityFolder(dir, false); generateScalabilityMain(dir, namesOfCards); // System.out.println("ADD all necessary scripts (header-1.js, RadarChart.js) to new generated folder."); }*/ }