code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: cloud.proto
package io.particle.firmwareprotos.ctrl.cloud;
public final class Cloud {
private Cloud() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
/**
* <pre>
* Make sure values of this enum match the values defined for the diagnostic info
* </pre>
*
* Protobuf enum {@code particle.ctrl.cloud.ConnectionStatus}
*/
public enum ConnectionStatus
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <code>DISCONNECTED = 0;</code>
*/
DISCONNECTED(0),
/**
* <code>CONNECTING = 1;</code>
*/
CONNECTING(1),
/**
* <code>CONNECTED = 2;</code>
*/
CONNECTED(2),
/**
* <code>DISCONNECTING = 3;</code>
*/
DISCONNECTING(3),
UNRECOGNIZED(-1),
;
/**
* <code>DISCONNECTED = 0;</code>
*/
public static final int DISCONNECTED_VALUE = 0;
/**
* <code>CONNECTING = 1;</code>
*/
public static final int CONNECTING_VALUE = 1;
/**
* <code>CONNECTED = 2;</code>
*/
public static final int CONNECTED_VALUE = 2;
/**
* <code>DISCONNECTING = 3;</code>
*/
public static final int DISCONNECTING_VALUE = 3;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static ConnectionStatus valueOf(int value) {
return forNumber(value);
}
public static ConnectionStatus forNumber(int value) {
switch (value) {
case 0: return DISCONNECTED;
case 1: return CONNECTING;
case 2: return CONNECTED;
case 3: return DISCONNECTING;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<ConnectionStatus>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
ConnectionStatus> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<ConnectionStatus>() {
public ConnectionStatus findValueByNumber(int number) {
return ConnectionStatus.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.getDescriptor().getEnumTypes().get(0);
}
private static final ConnectionStatus[] VALUES = values();
public static ConnectionStatus valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private ConnectionStatus(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:particle.ctrl.cloud.ConnectionStatus)
}
public interface GetConnectionStatusRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:particle.ctrl.cloud.GetConnectionStatusRequest)
com.google.protobuf.MessageOrBuilder {
}
/**
* <pre>
* Get the cloud connection status
* </pre>
*
* Protobuf type {@code particle.ctrl.cloud.GetConnectionStatusRequest}
*/
public static final class GetConnectionStatusRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:particle.ctrl.cloud.GetConnectionStatusRequest)
GetConnectionStatusRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetConnectionStatusRequest.newBuilder() to construct.
private GetConnectionStatusRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetConnectionStatusRequest() {
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private GetConnectionStatusRequest(
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;
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.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 io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.class, io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.Builder.class);
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
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 io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest)) {
return super.equals(obj);
}
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest other = (io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest) obj;
boolean result = true;
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest 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 io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest 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 io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
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;
}
/**
* <pre>
* Get the cloud connection status
* </pre>
*
* Protobuf type {@code particle.ctrl.cloud.GetConnectionStatusRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:particle.ctrl.cloud.GetConnectionStatusRequest)
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.class, io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.Builder.class);
}
// Construct using io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest getDefaultInstanceForType() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.getDefaultInstance();
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest build() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest buildPartial() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest result = new io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest(this);
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest) {
return mergeFrom((io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest other) {
if (other == io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest.getDefaultInstance()) return this;
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:particle.ctrl.cloud.GetConnectionStatusRequest)
}
// @@protoc_insertion_point(class_scope:particle.ctrl.cloud.GetConnectionStatusRequest)
private static final io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest();
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetConnectionStatusRequest>
PARSER = new com.google.protobuf.AbstractParser<GetConnectionStatusRequest>() {
public GetConnectionStatusRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetConnectionStatusRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GetConnectionStatusRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetConnectionStatusRequest> getParserForType() {
return PARSER;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface GetConnectionStatusReplyOrBuilder extends
// @@protoc_insertion_point(interface_extends:particle.ctrl.cloud.GetConnectionStatusReply)
com.google.protobuf.MessageOrBuilder {
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
int getStatusValue();
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus getStatus();
}
/**
* Protobuf type {@code particle.ctrl.cloud.GetConnectionStatusReply}
*/
public static final class GetConnectionStatusReply extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:particle.ctrl.cloud.GetConnectionStatusReply)
GetConnectionStatusReplyOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetConnectionStatusReply.newBuilder() to construct.
private GetConnectionStatusReply(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetConnectionStatusReply() {
status_ = 0;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private GetConnectionStatusReply(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
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;
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
int rawValue = input.readEnum();
status_ = rawValue;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.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 io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusReply_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.class, io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.Builder.class);
}
public static final int STATUS_FIELD_NUMBER = 1;
private int status_;
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public int getStatusValue() {
return status_;
}
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus getStatus() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus result = io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.valueOf(status_);
return result == null ? io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (status_ != io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.DISCONNECTED.getNumber()) {
output.writeEnum(1, status_);
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (status_ != io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.DISCONNECTED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, status_);
}
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 io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply)) {
return super.equals(obj);
}
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply other = (io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply) obj;
boolean result = true;
result = result && status_ == other.status_;
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + STATUS_FIELD_NUMBER;
hash = (53 * hash) + status_;
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply 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 io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply 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 io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
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 particle.ctrl.cloud.GetConnectionStatusReply}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:particle.ctrl.cloud.GetConnectionStatusReply)
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReplyOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusReply_fieldAccessorTable
.ensureFieldAccessorsInitialized(
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.class, io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.Builder.class);
}
// Construct using io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
status_ = 0;
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply getDefaultInstanceForType() {
return io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.getDefaultInstance();
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply build() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply buildPartial() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply result = new io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply(this);
result.status_ = status_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply) {
return mergeFrom((io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply other) {
if (other == io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply.getDefaultInstance()) return this;
if (other.status_ != 0) {
setStatusValue(other.getStatusValue());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int status_ = 0;
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public int getStatusValue() {
return status_;
}
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public Builder setStatusValue(int value) {
status_ = value;
onChanged();
return this;
}
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus getStatus() {
io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus result = io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.valueOf(status_);
return result == null ? io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus.UNRECOGNIZED : result;
}
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public Builder setStatus(io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus value) {
if (value == null) {
throw new NullPointerException();
}
status_ = value.getNumber();
onChanged();
return this;
}
/**
* <code>.particle.ctrl.cloud.ConnectionStatus status = 1;</code>
*/
public Builder clearStatus() {
status_ = 0;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:particle.ctrl.cloud.GetConnectionStatusReply)
}
// @@protoc_insertion_point(class_scope:particle.ctrl.cloud.GetConnectionStatusReply)
private static final io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply();
}
public static io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetConnectionStatusReply>
PARSER = new com.google.protobuf.AbstractParser<GetConnectionStatusReply>() {
public GetConnectionStatusReply parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetConnectionStatusReply(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GetConnectionStatusReply> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetConnectionStatusReply> getParserForType() {
return PARSER;
}
public io.particle.firmwareprotos.ctrl.cloud.Cloud.GetConnectionStatusReply getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_particle_ctrl_cloud_GetConnectionStatusReply_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\013cloud.proto\022\023particle.ctrl.cloud\032\020exte" +
"nsions.proto\"#\n\032GetConnectionStatusReque" +
"st:\005\210\265\030\254\002\"Q\n\030GetConnectionStatusReply\0225\n" +
"\006status\030\001 \001(\0162%.particle.ctrl.cloud.Conn" +
"ectionStatus*V\n\020ConnectionStatus\022\020\n\014DISC" +
"ONNECTED\020\000\022\016\n\nCONNECTING\020\001\022\r\n\tCONNECTED\020" +
"\002\022\021\n\rDISCONNECTING\020\003B\'\n%io.particle.firm" +
"wareprotos.ctrl.cloudb\006proto3"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
io.particle.firmwareprotos.ctrl.Extensions.getDescriptor(),
}, assigner);
internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_particle_ctrl_cloud_GetConnectionStatusRequest_descriptor,
new java.lang.String[] { });
internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_particle_ctrl_cloud_GetConnectionStatusReply_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_particle_ctrl_cloud_GetConnectionStatusReply_descriptor,
new java.lang.String[] { "Status", });
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(io.particle.firmwareprotos.ctrl.Extensions.typeId);
com.google.protobuf.Descriptors.FileDescriptor
.internalUpdateFileDescriptor(descriptor, registry);
io.particle.firmwareprotos.ctrl.Extensions.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
spark/photon-tinker-android
|
firmwareprotos/src/main/java/io/particle/firmwareprotos/ctrl/cloud/Cloud.java
|
Java
|
apache-2.0
| 42,941 |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
/* global ActiveXObject:false */
// Provides control sap.m.PDFViewer.
sap.ui.define([
"jquery.sap.global",
"./library",
"sap/ui/core/Control",
"sap/ui/Device",
"sap/m/PDFViewerRenderManager",
"sap/m/MessageBox"
],
function (jQuery, library, Control, Device, PDFViewerRenderManager, MessageBox) {
"use strict";
var aAllowedMimeTypes = Object.freeze([
"application/pdf",
"application/x-google-chrome-pdf"
]);
function isSupportedMimeType(sMimeType) {
var iFoundIndex = aAllowedMimeTypes.indexOf(sMimeType);
return iFoundIndex > -1;
}
/**
* Definition of PDFViewer control
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* This control enables you to display PDF documents within your app.
* It can be embedded in your user interface layout, or you can set it to open in a popup dialog.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.50.8
*
* @constructor
* @public
* @alias sap.m.PDFViewer
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var PDFViewer = Control.extend("sap.m.PDFViewer",
/** @lends sap.m.PDFViewer.prototype */
{
metadata: {
library: "sap.m",
properties: {
/**
* Defines the height of the PDF viewer control, respective to the height of
* the parent container. Can be set to a percent, pixel, or em value.
*/
height: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: "100%"},
/**
* Defines the width of the PDF viewer control, respective to the width of the
* parent container. Can be set to a percent, pixel, or em value.
*/
width: {type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: "100%"},
/**
* Specifies the path to the PDF file to display. Can be set to a relative or
* an absolute path.
*/
source: {type: "sap.ui.core.URI", group: "Misc", defaultValue: null},
/**
* A custom error message that is displayed when the PDF file cannot be loaded.
* @deprecated As of version 1.50.0, replaced by {@link sap.m.PDFViewer#getErrorPlaceholderMessage()}.
*/
errorMessage: {type: "string", group: "Misc", defaultValue: null, deprecated: true},
/**
* A custom text that is displayed instead of the PDF file content when the PDF
* file cannot be loaded.
*/
errorPlaceholderMessage: {type: "string", group: "Misc", defaultValue: null},
/**
* A custom title for the PDF viewer popup dialog. Works only if the PDF viewer
* is set to open in a popup dialog.
* @deprecated As of version 1.50.0, replaced by {@link sap.m.PDFViewer#getTitle()}.
*/
popupHeaderTitle: {type: "string", group: "Misc", defaultValue: null, deprecated: true},
/**
* A custom title for the PDF viewer.
*/
title: {type: "string", group: "Misc", defaultValue: null},
/**
* Shows or hides the download button.
*/
showDownloadButton: {type: "boolean", group: "Misc", defaultValue: true}
},
aggregations: {
/**
* A custom control that can be used instead of the error message specified by the
* errorPlaceholderMessage property.
*/
errorPlaceholder: {type: "sap.ui.core.Control", multiple: false},
/**
* A multiple aggregation for buttons that can be added to the footer of the popup
* dialog. Works only if the PDF viewer is set to open in a popup dialog.
*/
popupButtons: {type: "sap.m.Button", multiple: true, singularName: "popupButton"}
},
events: {
/**
* This event is fired when a PDF file is loaded. If the PDF is loaded in smaller chunks,
* this event is fired as often as defined by the browser's plugin. This may happen after
* a couple chunks are processed.
*/
loaded: {},
/**
* This event is fired when there is an error loading the PDF file.
*/
error: {},
/**
* This event is fired when the PDF viewer control cannot check the loaded content. For
* example, the default configuration of the Mozilla Firefox browser may not allow checking
* the loaded content. This may also happen when the source PDF file is stored in a different
* domain.
* If you want no error message to be displayed when this event is fired, call the
* preventDefault() method inside the event handler.
*/
sourceValidationFailed: {}
}
}
});
/**
* @returns {boolean}
* @private
*/
PDFViewer._isPdfPluginEnabled = function () {
var bIsEnabled = true;
if (Device.browser.firefox) {
// https://bugzilla.mozilla.org/show_bug.cgi?id=1293406
// mimeType is missing for firefox even though it is enabled
return bIsEnabled;
}
if (Device.browser.internet_explorer) {
// hacky code how to recognize that pdf plugin is installed and enabled
try {
/* eslint-disable no-new */
new ActiveXObject("AcroPDF.PDF");
/* eslint-enable no-new */
} catch (e) {
bIsEnabled = false;
}
return bIsEnabled;
}
var aMimeTypes = navigator.mimeTypes;
bIsEnabled = aAllowedMimeTypes.some(function (sAllowedMimeType) {
var oMimeTypeItem = aMimeTypes.namedItem(sAllowedMimeType);
return oMimeTypeItem !== null;
});
return bIsEnabled;
};
/**
* Lifecycle method
*
* @private
*/
PDFViewer.prototype.init = function () {
// helper object that holds the references of nested objects
this._objectsRegister = {};
// state variable that shows the state of popup (rendering of pdf in popup requires it)
this._bIsPopupOpen = false;
this._initPopupControl();
this._initPopupDownloadButtonControl();
this._initPlaceholderMessagePageControl();
this._initToolbarDownloadButtonControl();
this._initOverflowToolbarControl();
this._initControlState();
};
/**
* Setup state variables to default state
*
* @private
*/
PDFViewer.prototype._initControlState = function () {
// state property that control if the embedded pdf should or should not rendered.
this._bRenderPdfContent = true;
// detect that beforeunload was fired (IE only)
this._bOnBeforeUnloadFired = false;
};
PDFViewer.prototype.setWidth = function (sWidth) {
this.setProperty("width", sWidth, true);
var oDomRef = this.$();
if (oDomRef === null) {
return this;
}
oDomRef.css("width", this._getRenderWidth());
return this;
};
PDFViewer.prototype.setHeight = function (sHeight) {
this.setProperty("height", sHeight, true);
var oDomRef = this.$();
if (oDomRef === null) {
return this;
}
oDomRef.css("height", this._getRenderHeight());
return this;
};
PDFViewer.prototype.onBeforeRendering = function () {
// IE things
// because of the detecting error state in IE (double call of unload listener)
// it is important to reset the flag before each render
// otherwise it wrongly detects error state (the unload listener is called once even in valid use case)
this._bOnBeforeUnloadFired = false;
};
/**
* Lifecycle method
*
* @private
*/
PDFViewer.prototype.onAfterRendering = function () {
var fnInitIframeElement = function () {
// cant use attachBrowserEvent because it attach event to component root node (this.$())
// load event does not bubble so it has to be bind directly to iframe element
var oIframeElement = this._getIframeDOMElement();
var oIframeContentWindow = jQuery(oIframeElement.get(0).contentWindow);
if (Device.browser.internet_explorer) {
// being special does not mean useful
// https://connect.microsoft.com/IE/feedback/details/809377/ie-11-load-event-doesnt-fired-for-pdf-in-iframe
// onerror does not works on IE. Therefore readyonstatechange and unload events are used for error detection.
// When invalid response is received (404, etc.), readystatechange is not fired but unload is.
// When valid response is received, then readystatechange and 'complete' state of target's element is received.
oIframeContentWindow.on("beforeunload", this._onBeforeUnloadListener.bind(this));
oIframeContentWindow.on("readystatechange", this._onReadyStateChangeListener.bind(this));
// some error codes load html file and fires loadEvent
oIframeElement.on("load", this._onLoadIEListener.bind(this));
} else {
// normal browsers supports load events as specification said
oIframeElement.on("load", this._onLoadListener.bind(this));
}
oIframeElement.on("error", this._onErrorListener.bind(this));
var sParametrizedSource = this.getSource();
var iCrossPosition = this.getSource().indexOf("#");
if (iCrossPosition > -1) {
sParametrizedSource = sParametrizedSource.substr(0, iCrossPosition);
}
sParametrizedSource += "#view=FitH";
if (jQuery.sap.validateUrl(sParametrizedSource)) {
oIframeElement.attr("src", encodeURI(sParametrizedSource));
} else {
this._fireErrorEvent();
}
}.bind(this);
try {
this.setBusy(true);
fnInitIframeElement();
} catch (error) {
this.setBusy(false);
}
};
/**
* @private
*/
PDFViewer.prototype._fireErrorEvent = function () {
this._renderErrorState();
this.fireEvent("error", {}, true);
};
/**
* @private
*/
PDFViewer.prototype._renderErrorState = function () {
var oDownloadButton = this._objectsRegister.getToolbarDownloadButtonControl();
oDownloadButton.setEnabled(false);
var oDownloadButton = this._objectsRegister.getPopupDownloadButtonControl();
oDownloadButton.setEnabled(false);
this.setBusy(false);
this._bRenderPdfContent = false;
// calls controls invalidate because the error state should be render.
// It is controlled by the state variable called _bRenderPdfContent
// The main invalidate set the state of the control to the default and tries to load and render pdf
Control.prototype.invalidate.call(this);
};
/**
* @private
*/
PDFViewer.prototype._fireLoadedEvent = function () {
this._bRenderPdfContent = true;
this.setBusy(false);
try {
this._getIframeDOMElement().removeClass("sapMPDFViewerLoading");
} catch (err) {
jQuery.log.fatal("Iframe not founded in loaded event");
jQuery.log.fatal(err);
}
this.fireEvent("loaded");
};
/**
* @param oEvent
* @private
*/
PDFViewer.prototype._onLoadListener = function (oEvent) {
try {
var oTarget = jQuery(oEvent.target),
bContinue = true;
// Firefox
// https://bugzilla.mozilla.org/show_bug.cgi?id=911444
// because of the embedded pdf plugin in firefox it is not possible to check contentType of the iframe document
// if the content is pdf. If the content is not a pdf and it is from the same origin, it can be accessed.
// Other browsers allow access to the mimeType of the iframe's document if the content is from the same origin.
var sCurrentContentType = "application/pdf";
try {
// browsers render pdf in iframe as html page with embed tag
var aEmbeds = oTarget[0].contentWindow.document.embeds;
bContinue = !!aEmbeds && aEmbeds.length === 1;
if (bContinue) {
sCurrentContentType = aEmbeds[0].attributes.getNamedItem("type").value;
}
} catch (error) {
// even though the sourceValidationFailed event is fired, the default behaviour is to continue.
// when preventDefault is on event object is called, the rendering ends up with error
if (!Device.browser.firefox && this.fireEvent("sourceValidationFailed", {}, true)) {
this._showMessageBox();
return;
}
}
if (bContinue && isSupportedMimeType(sCurrentContentType)) {
this._fireLoadedEvent();
} else {
this._fireErrorEvent();
}
} catch (error) {
jQuery.sap.log.fatal(false, "Fatal error during the handling of load event happened.");
jQuery.sap.log.fatal(false, error.message);
}
};
/**
* @private
*/
PDFViewer.prototype._onErrorListener = function () {
this._fireErrorEvent();
};
/**
* @private
*/
PDFViewer.prototype._onReadyStateChangeListener = function (oEvent) {
var INTERACTIVE_READY_STATE = "interactive";
var COMPLETE_READY_STATE = "complete";
switch (oEvent.target.readyState) {
case INTERACTIVE_READY_STATE: // IE11 only fires interactive
case COMPLETE_READY_STATE:
// iframe content is not loaded when interactive ready state is fired
// even though complete ready state should be fired. We were not able to simulate firing complete ready state
// on IE. Therefore the validation of source is not possible.
this._fireLoadedEvent();
break;
}
};
/**
* @private
*/
PDFViewer.prototype._onBeforeUnloadListener = function () {
// IE problems
// when invalid response is received (404), beforeunload is fired twice
if (this._bOnBeforeUnloadFired) {
this._fireErrorEvent();
return;
}
this._bOnBeforeUnloadFired = true;
};
/**
* @param oEvent
* @private
*/
PDFViewer.prototype._onLoadIEListener = function (oEvent) {
try {
// because of asynchronity of events, IE sometimes fires load event even after it unloads the content.
// The contentWindow does not exists in these moments. On the other hand, the error state is already handled
// by onBeforeUnloadListener, so we only need catch for catching the error and then return.
// The problem is not with null reference. The access of the contentWindow sometimes fires 'access denied' error
// which is not detectable otherwise.
var sCurrentContentType = oEvent.currentTarget.contentWindow.document.mimeType;
} catch (err) {
return;
}
if (!isSupportedMimeType(sCurrentContentType)) {
this._fireErrorEvent();
}
};
/**
* Downloads the PDF file.
*
* @public
*/
PDFViewer.prototype.downloadPDF = function () {
var oWindow = window.open(this.getSource());
oWindow.focus();
};
/**
* @param string oClickedButtonId
* @private
*/
PDFViewer.prototype._onSourceValidationErrorMessageBoxCloseListener = function (oClickedButtonId) {
if (oClickedButtonId === MessageBox.Action.CANCEL) {
this._renderErrorState();
} else {
this._fireLoadedEvent();
}
};
/**
* @param oEvent
* @private
*/
PDFViewer.prototype._onAfterPopupClose = function (oEvent) {
var oPopup = this._objectsRegister.getPopup();
// content has to be cleared from dom
oPopup.removeAllContent();
this._bIsPopupOpen = false;
};
/**
* @returns {boolean}
* @private
*/
PDFViewer.prototype._shouldRenderPdfContent = function () {
return PDFViewer._isPdfPluginEnabled() && this._bRenderPdfContent && this.getSource() !== null;
};
/**
* @returns {boolean}
* @private
*/
PDFViewer.prototype._isSourceValidToDisplay = function () {
var sSource = this.getSource();
return sSource !== null && sSource !== "" && typeof sSource !== "undefined";
};
/**
* Triggers rerendering of this element and its children.
*
* @param {sap.ui.base.ManagedObject} [oOrigin] Child control for which the method was called
*
* @public
*/
PDFViewer.prototype.invalidate = function (oOrigin) {
this._initControlState();
Control.prototype.invalidate.call(this, oOrigin);
};
/**
* Opens the PDF viewer in a popup dialog.
*
* @public
*/
PDFViewer.prototype.open = function () {
if (!this._isSourceValidToDisplay()) {
jQuery.sap.assert(false, "The PDF file cannot be opened with the given source. Given source: " + this.getSource());
return;
}
if (this._isEmbeddedModeAllowed()) {
this._openOnDesktop();
} else {
this._openOnMobile();
}
};
/**
* Handles opening on desktop devices
* @private
*/
PDFViewer.prototype._openOnDesktop = function () {
var oPopup = this._objectsRegister.getPopup();
if (this._bIsPopupOpen) {
return;
}
this._initControlState();
this._preparePopup(oPopup);
oPopup.addContent(this);
this._bIsPopupOpen = true;
oPopup.open();
};
/**
* Handles opening on mobile/tablet devices
* @private
*/
PDFViewer.prototype._openOnMobile = function () {
var oWindow = window.open(this.getSource());
oWindow.focus();
};
/**
* Gets the iframe element from rendered DOM
* @returns {*} jQuery object of iframe
* @private
*/
PDFViewer.prototype._getIframeDOMElement = function () {
var oIframeElement = this.$().find("iframe");
if (oIframeElement.length === 0) {
throw Error("Underlying iframe was not found in DOM.");
}
if (oIframeElement.length > 1) {
jQuery.sap.log.fatal("Initialization of iframe fails. Reason: the control somehow renders multiple iframes");
}
return oIframeElement;
};
/**
* @private
*/
PDFViewer.prototype._isEmbeddedModeAllowed = function () {
return Device.system.desktop;
};
/**
* @returns {jQuery.sap.util.ResourceBundle}
* @private
*/
PDFViewer.prototype._getLibraryResourceBundle = function () {
return sap.ui.getCore().getLibraryResourceBundle("sap.m");
};
/**
* @returns {string}
* @private
*/
PDFViewer.prototype._getMessagePageErrorMessage = function () {
return this.getErrorPlaceholderMessage() ? this.getErrorPlaceholderMessage() :
this._getLibraryResourceBundle().getText("PDF_VIEWER_PLACEHOLDER_ERROR_TEXT");
};
/**
* @returns {string}
* @private
*/
PDFViewer.prototype._getRenderWidth = function () {
return this._bIsPopupOpen ? '100%' : this.getWidth();
};
/**
* @returns {string}
* @private
*/
PDFViewer.prototype._getRenderHeight = function () {
return this._bIsPopupOpen ? '100%' : this.getHeight();
};
/**
* @private
*/
PDFViewer.prototype._showMessageBox = function () {
MessageBox.show(this._getLibraryResourceBundle().getText("PDF_VIEWER_SOURCE_VALIDATION_MESSAGE_TEXT"), {
icon: MessageBox.Icon.WARNING,
title: this._getLibraryResourceBundle().getText("PDF_VIEWER_SOURCE_VALIDATION_MESSAGE_HEADER"),
actions: [MessageBox.Action.OK, MessageBox.Action.CANCEL],
defaultAction: MessageBox.Action.CANCEL,
id: this.getId() + "-validationErrorSourceMessageBox",
styleClass: "sapUiSizeCompact",
contentWidth: '100px',
onClose: this._onSourceValidationErrorMessageBoxCloseListener.bind(this)
});
};
/**
* Lifecycle method
* @private
*/
PDFViewer.prototype.exit = function () {
jQuery.each(this._objectsRegister, function (iIndex, fnGetObject) {
var oObject = fnGetObject(true);
if (oObject) {
oObject.destroy();
}
});
};
PDFViewerRenderManager.extendPdfViewer(PDFViewer);
return PDFViewer;
}, /* bExport= */ true);
|
thbonk/electron-openui5-boilerplate
|
libs/openui5-runtime/resources/sap/m/PDFViewer-dbg.js
|
JavaScript
|
apache-2.0
| 19,266 |
var madson = (function () {
import "nxutils/generic/base";
import "./utils";
import "./write";
import "./read";
import "./preset";
function mEncode(input, options) {
var encoder = new EncodeBuffer(options);
encode(encoder, cloneDecycle(input));
return encoder.read();
}
function mDecode(input, options) {
var decoder = new DecodeBuffer(options);
decoder.append(input);
return retroCycle(decode(decoder));
}
function packer(input) {
return Buffer.isBuffer(input) ? mDecode(input) : mEncode(input);
}
var madson = extend(packer, {
createCodec: Codec,
codec: { preset: preset },
encode: mEncode,
decode: mDecode
});
if ("isServer") {
if (typeof module == 'object')
module.exports = madson;
}
else global.madson = madson;
return madson;
})();
|
arash16/madson
|
src/index.js
|
JavaScript
|
apache-2.0
| 901 |
// Copyright 2000-2020 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.
package com.intellij.openapi.wm.impl;
import com.intellij.ide.RemoteDesktopService;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.UISettingsListener;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.ThreeComponentsSplitter;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.registry.RegistryValue;
import com.intellij.openapi.util.registry.RegistryValueListener;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowType;
import com.intellij.openapi.wm.WindowInfo;
import com.intellij.openapi.wm.ex.ToolWindowEx;
import com.intellij.reference.SoftReference;
import com.intellij.ui.OnePixelSplitter;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.ui.paint.PaintUtil;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.ui.scale.ScaleContext;
import com.intellij.util.IJSwingUtilities;
import com.intellij.util.ui.ImageUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import static com.intellij.util.ui.UIUtil.useSafely;
/**
* This panel contains all tool stripes and JLayeredPane at the center area. All tool windows are
* located inside this layered pane.
*
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public final class ToolWindowsPane extends JBLayeredPane implements UISettingsListener {
private static final Logger LOG = Logger.getInstance(ToolWindowsPane.class);
@NonNls public static final String TEMPORARY_ADDED = "TEMPORARY_ADDED";
private final JFrame frame;
private ToolWindowPaneState state = new ToolWindowPaneState();
/**
* This panel is the layered pane where all sliding tool windows are located. The DEFAULT
* layer contains splitters. The PALETTE layer contains all sliding tool windows.
*/
private final MyLayeredPane layeredPane;
/*
* Splitters.
*/
private final ThreeComponentsSplitter verticalSplitter;
private final ThreeComponentsSplitter horizontalSplitter;
/*
* Tool stripes.
*/
private final Stripe leftStripe;
private final Stripe rightStripe;
private final Stripe bottomStripe;
private final Stripe topStripe;
private final List<Stripe> stripes = new ArrayList<>(4);
private boolean isWideScreen;
private boolean leftHorizontalSplit;
private boolean rightHorizontalSplit;
private List<String> myDefaultRightButtons = new ArrayList<>();
private List<String> myDefaultLeftButtons = new ArrayList<>();
private List<String> myDefaultBottomButtons = new ArrayList<>();
@Nullable private final ToolwindowToolbar myLeftToolbar;
@Nullable private final ToolwindowToolbar myRightToolbar;
ToolWindowsPane(@NotNull JFrame frame,
@NotNull Disposable parentDisposable,
@Nullable ToolwindowToolbar leftSidebar,
@Nullable ToolwindowToolbar rightSidebar) {
myLeftToolbar = leftSidebar;
myRightToolbar = rightSidebar;
setOpaque(false);
this.frame = frame;
// splitters
verticalSplitter = new ThreeComponentsSplitter(true, parentDisposable);
RegistryValue registryValue = Registry.get("ide.mainSplitter.min.size");
registryValue.addListener(new RegistryValueListener() {
@Override
public void afterValueChanged(@NotNull RegistryValue value) {
updateInnerMinSize(value);
}
}, parentDisposable);
verticalSplitter.setDividerWidth(0);
verticalSplitter.setDividerMouseZoneSize(Registry.intValue("ide.splitter.mouseZone"));
verticalSplitter.setBackground(Color.gray);
horizontalSplitter = new ThreeComponentsSplitter(false, parentDisposable);
horizontalSplitter.setDividerWidth(0);
horizontalSplitter.setDividerMouseZoneSize(Registry.intValue("ide.splitter.mouseZone"));
horizontalSplitter.setBackground(Color.gray);
updateInnerMinSize(registryValue);
UISettings uiSettings = UISettings.getInstance();
isWideScreen = uiSettings.getWideScreenSupport();
leftHorizontalSplit = uiSettings.getLeftHorizontalSplit();
rightHorizontalSplit = uiSettings.getRightHorizontalSplit();
if (isWideScreen) {
horizontalSplitter.setInnerComponent(verticalSplitter);
}
else {
verticalSplitter.setInnerComponent(horizontalSplitter);
}
// tool stripes
topStripe = new Stripe(SwingConstants.TOP);
stripes.add(topStripe);
leftStripe = new Stripe(SwingConstants.LEFT);
stripes.add(leftStripe);
bottomStripe = new Stripe(SwingConstants.BOTTOM);
stripes.add(bottomStripe);
rightStripe = new Stripe(SwingConstants.RIGHT);
stripes.add(rightStripe);
updateToolStripesVisibility(uiSettings);
// layered pane
layeredPane = new MyLayeredPane(isWideScreen ? horizontalSplitter : verticalSplitter);
// compose layout
add(topStripe, JLayeredPane.POPUP_LAYER);
add(leftStripe, JLayeredPane.POPUP_LAYER);
add(bottomStripe, JLayeredPane.POPUP_LAYER);
add(rightStripe, JLayeredPane.POPUP_LAYER);
add(layeredPane, JLayeredPane.DEFAULT_LAYER);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicy());
}
void initDocumentComponent(@NotNull Project project) {
JComponent editorComponent = FileEditorManagerEx.getInstanceEx(project).getComponent();
editorComponent.setFocusable(false);
setDocumentComponent(editorComponent);
}
private void updateInnerMinSize(@NotNull RegistryValue value) {
int minSize = Math.max(0, Math.min(100, value.asInteger()));
verticalSplitter.setMinSize(JBUIScale.scale(minSize));
horizontalSplitter.setMinSize(JBUIScale.scale(minSize));
}
@Override
public void doLayout() {
Dimension size = getSize();
if (!topStripe.isVisible()) {
topStripe.setBounds(0, 0, 0, 0);
bottomStripe.setBounds(0, 0, 0, 0);
leftStripe.setBounds(0, 0, 0, 0);
rightStripe.setBounds(0, 0, 0, 0);
layeredPane.setBounds(0, 0, getWidth(), getHeight());
}
else {
Dimension topSize = topStripe.getPreferredSize();
Dimension bottomSize = bottomStripe.getPreferredSize();
Dimension leftSize = leftStripe.getPreferredSize();
Dimension rightSize = rightStripe.getPreferredSize();
topStripe.setBounds(0, 0, size.width, topSize.height);
int height = size.height - topSize.height - bottomSize.height;
leftStripe.setBounds(0, topSize.height, leftSize.width, height);
rightStripe.setBounds(size.width - rightSize.width, topSize.height, rightSize.width, height);
bottomStripe.setBounds(0, size.height - bottomSize.height, size.width, bottomSize.height);
UISettings uiSettings = UISettings.getInstance();
if (uiSettings.getHideToolStripes() || uiSettings.getPresentationMode()) {
if (isSquareStripeUI()) {
updateSquareStripes(false);
} else {
layeredPane.setBounds(0, 0, size.width, size.height);
}
}
else {
int width = size.width - leftSize.width - rightSize.width;
layeredPane.setBounds(leftSize.width, topSize.height, width, height);
}
}
}
private static boolean isSquareStripeUI() {
return Registry.is("ide.new.stripes.ui");
}
@Override
public void uiSettingsChanged(@NotNull UISettings uiSettings) {
updateToolStripesVisibility(uiSettings);
updateLayout(uiSettings);
}
/**
* @param dirtyMode if {@code true} then JRootPane will not be validated and repainted after adding
* the decorator. Moreover in this (dirty) mode animation doesn't work.
*/
final void addDecorator(@NotNull JComponent decorator, @NotNull WindowInfo info, boolean dirtyMode, @NotNull ToolWindowManagerImpl manager) {
if (info.isDocked()) {
boolean side = !info.isSplit();
WindowInfo sideInfo = manager.getDockedInfoAt(info.getAnchor(), side);
if (sideInfo == null) {
ToolWindowAnchor anchor = info.getAnchor();
setComponent(decorator, anchor, normalizeWeigh(info.getWeight()));
if (!dirtyMode) {
layeredPane.validate();
layeredPane.repaint();
}
}
else {
addAndSplitDockedComponentCmd(decorator, info, dirtyMode, manager);
}
}
else if (info.getType() == ToolWindowType.SLIDING) {
addSlidingComponent(decorator, info, dirtyMode);
}
else {
throw new IllegalArgumentException("Unknown window type: " + info.getType());
}
}
void removeDecorator(@NotNull WindowInfo info, @Nullable JComponent component, boolean dirtyMode, @NotNull ToolWindowManagerImpl manager) {
if (info.getType() == ToolWindowType.DOCKED) {
WindowInfo sideInfo = manager.getDockedInfoAt(info.getAnchor(), !info.isSplit());
if (sideInfo == null) {
setComponent(null, info.getAnchor(), 0);
}
else {
ToolWindowAnchor anchor = info.getAnchor();
JComponent c = getComponentAt(anchor);
if (c instanceof Splitter) {
Splitter splitter = (Splitter)c;
InternalDecoratorImpl component1 = (InternalDecoratorImpl)(info.isSplit() ? splitter.getFirstComponent() : splitter.getSecondComponent());
state.addSplitProportion(info, component1, splitter);
setComponent(component1, anchor,
component1 == null ? 0 : ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError(component1).getWeight());
}
else {
setComponent(null, anchor, 0);
}
}
if (!dirtyMode) {
layeredPane.validate();
layeredPane.repaint();
}
}
else if (info.getType() == ToolWindowType.SLIDING) {
if (component != null) {
removeSlidingComponent(component, info, dirtyMode);
}
}
}
public final @NotNull JComponent getLayeredPane() {
return layeredPane;
}
public void validateAndRepaint() {
layeredPane.validate();
layeredPane.repaint();
for (Stripe stripe : stripes) {
stripe.revalidate();
stripe.repaint();
}
}
public void revalidateNotEmptyStripes() {
for (Stripe stripe : stripes) {
if (!stripe.isEmpty()) {
stripe.revalidate();
}
}
}
private void setComponent(@Nullable JComponent component, @NotNull ToolWindowAnchor anchor, float weight) {
Dimension size = getSize();
if (ToolWindowAnchor.TOP == anchor) {
verticalSplitter.setFirstComponent(component);
verticalSplitter.setFirstSize((int)(size.getHeight() * weight));
}
else if (ToolWindowAnchor.LEFT == anchor) {
horizontalSplitter.setFirstComponent(component);
horizontalSplitter.setFirstSize((int)(size.getWidth() * weight));
}
else if (ToolWindowAnchor.BOTTOM == anchor) {
verticalSplitter.setLastComponent(component);
verticalSplitter.setLastSize((int)(size.getHeight() * weight));
}
else if (ToolWindowAnchor.RIGHT == anchor) {
horizontalSplitter.setLastComponent(component);
horizontalSplitter.setLastSize((int)(size.getWidth() * weight));
}
else {
LOG.error("unknown anchor: " + anchor);
}
}
private JComponent getComponentAt(@NotNull ToolWindowAnchor anchor) {
if (ToolWindowAnchor.TOP == anchor) {
return verticalSplitter.getFirstComponent();
}
else if (ToolWindowAnchor.LEFT == anchor) {
return horizontalSplitter.getFirstComponent();
}
else if (ToolWindowAnchor.BOTTOM == anchor) {
return verticalSplitter.getLastComponent();
}
else if (ToolWindowAnchor.RIGHT == anchor) {
return horizontalSplitter.getLastComponent();
}
else {
LOG.error("unknown anchor: " + anchor);
return null;
}
}
private void setDocumentComponent(@Nullable JComponent component) {
(isWideScreen ? verticalSplitter : horizontalSplitter).setInnerComponent(component);
}
private void updateToolStripesVisibility(@NotNull UISettings uiSettings) {
boolean oldVisible = leftStripe.isVisible();
boolean showButtons = !uiSettings.getHideToolStripes() && !uiSettings.getPresentationMode();
boolean visible = (showButtons || state.isStripesOverlaid()) && !isSquareStripeUI();
leftStripe.setVisible(visible);
rightStripe.setVisible(visible);
topStripe.setVisible(visible);
bottomStripe.setVisible(visible);
if (myLeftToolbar != null && myRightToolbar != null) {
boolean oldSquareVisible = myLeftToolbar.isVisible() && myRightToolbar.isVisible();
boolean squareStripesVisible = isSquareStripeUI() && showButtons;
updateSquareStripes(squareStripesVisible);
if (isSquareStripeUI() && oldSquareVisible != squareStripesVisible) {
revalidate();
repaint();
}
}
boolean overlayed = !showButtons && state.isStripesOverlaid();
leftStripe.setOverlayed(overlayed);
rightStripe.setOverlayed(overlayed);
topStripe.setOverlayed(overlayed);
bottomStripe.setOverlayed(overlayed);
if (oldVisible != visible) {
revalidate();
repaint();
}
}
private void updateSquareStripes(boolean squareStripesVisible) {
if (myLeftToolbar != null && myRightToolbar != null) {
myLeftToolbar.setVisible(squareStripesVisible);
myRightToolbar.setVisible(squareStripesVisible);
}
}
public int getBottomHeight() {
return bottomStripe.isVisible() ? bottomStripe.getHeight() : 0;
}
public boolean isBottomSideToolWindowsVisible() {
return getComponentAt(ToolWindowAnchor.BOTTOM) != null;
}
@NotNull
Stripe getStripeFor(@NotNull ToolWindowAnchor anchor) {
if (ToolWindowAnchor.TOP == anchor) {
return topStripe;
}
if (ToolWindowAnchor.BOTTOM == anchor) {
return bottomStripe;
}
if (ToolWindowAnchor.LEFT == anchor) {
return leftStripe;
}
if (ToolWindowAnchor.RIGHT == anchor) {
return rightStripe;
}
throw new IllegalArgumentException("Anchor=" + anchor);
}
@Nullable
Stripe getStripeFor(@NotNull Rectangle screenRectangle, @NotNull Stripe preferred) {
if (preferred.containsScreen(screenRectangle)) {
return preferred;
}
for (Stripe stripe : stripes) {
if (stripe.containsScreen(screenRectangle)) {
return stripe;
}
}
return null;
}
@Nullable
ToolwindowToolbar getSquareStripeFor(@NotNull ToolWindowAnchor anchor) {
if (ToolWindowAnchor.TOP == anchor || ToolWindowAnchor.RIGHT == anchor) return myRightToolbar;
if (ToolWindowAnchor.BOTTOM == anchor || ToolWindowAnchor.LEFT == anchor) return myLeftToolbar;
throw new IllegalArgumentException("Anchor=" + anchor);
}
void startDrag() {
for (Stripe each : stripes) {
each.startDrag();
}
}
void stopDrag() {
for (Stripe stripe : stripes) {
stripe.stopDrag();
}
}
void stretchWidth(@NotNull ToolWindow window, int value) {
stretch(window, value);
}
void stretchHeight(@NotNull ToolWindow window, int value) {
stretch(window, value);
}
private void stretch(@NotNull ToolWindow wnd, int value) {
Pair<Resizer, Component> pair = findResizerAndComponent(wnd);
if (pair == null) return;
boolean vertical = wnd.getAnchor() == ToolWindowAnchor.TOP || wnd.getAnchor() == ToolWindowAnchor.BOTTOM;
int actualSize = (vertical ? pair.second.getHeight() : pair.second.getWidth()) + value;
boolean first = wnd.getAnchor() == ToolWindowAnchor.LEFT || wnd.getAnchor() == ToolWindowAnchor.TOP;
int maxValue = vertical ? verticalSplitter.getMaxSize(first) : horizontalSplitter.getMaxSize(first);
int minValue = vertical ? verticalSplitter.getMinSize(first) : horizontalSplitter.getMinSize(first);
pair.first.setSize(Math.max(minValue, Math.min(maxValue, actualSize)));
}
private @Nullable Pair<Resizer, Component> findResizerAndComponent(@NotNull ToolWindow window) {
if (!window.isVisible()) return null;
Resizer resizer = null;
Component component = null;
if (window.getType() == ToolWindowType.DOCKED) {
component = getComponentAt(window.getAnchor());
if (component != null) {
if (window.getAnchor().isHorizontal()) {
resizer = verticalSplitter.getFirstComponent() == component
? new Resizer.Splitter.FirstComponent(verticalSplitter)
: new Resizer.Splitter.LastComponent(verticalSplitter);
}
else {
resizer = horizontalSplitter.getFirstComponent() == component
? new Resizer.Splitter.FirstComponent(horizontalSplitter)
: new Resizer.Splitter.LastComponent(horizontalSplitter);
}
}
}
else if (window.getType() == ToolWindowType.SLIDING) {
component = window.getComponent();
while (component != null) {
if (component.getParent() == layeredPane) break;
component = component.getParent();
}
if (component != null) {
if (window.getAnchor() == ToolWindowAnchor.TOP) {
resizer = new Resizer.LayeredPane.Top(component);
}
else if (window.getAnchor() == ToolWindowAnchor.BOTTOM) {
resizer = new Resizer.LayeredPane.Bottom(component);
}
else if (window.getAnchor() == ToolWindowAnchor.LEFT) {
resizer = new Resizer.LayeredPane.Left(component);
}
else if (window.getAnchor() == ToolWindowAnchor.RIGHT) {
resizer = new Resizer.LayeredPane.Right(component);
}
}
}
return resizer != null ? Pair.create(resizer, component) : null;
}
private void updateLayout(@NotNull UISettings uiSettings) {
if (isWideScreen != uiSettings.getWideScreenSupport()) {
JComponent documentComponent = (isWideScreen ? verticalSplitter : horizontalSplitter).getInnerComponent();
isWideScreen = uiSettings.getWideScreenSupport();
if (isWideScreen) {
verticalSplitter.setInnerComponent(null);
horizontalSplitter.setInnerComponent(verticalSplitter);
}
else {
horizontalSplitter.setInnerComponent(null);
verticalSplitter.setInnerComponent(horizontalSplitter);
}
layeredPane.remove(isWideScreen ? verticalSplitter : horizontalSplitter);
layeredPane.add(isWideScreen ? horizontalSplitter : verticalSplitter, DEFAULT_LAYER);
setDocumentComponent(documentComponent);
}
if (leftHorizontalSplit != uiSettings.getLeftHorizontalSplit()) {
JComponent component = getComponentAt(ToolWindowAnchor.LEFT);
if (component instanceof Splitter) {
Splitter splitter = (Splitter)component;
WindowInfoImpl firstInfo = ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError((InternalDecoratorImpl)splitter.getFirstComponent());
WindowInfoImpl secondInfo = ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError((InternalDecoratorImpl)splitter.getSecondComponent());
setComponent(splitter, ToolWindowAnchor.LEFT, ToolWindowAnchor.LEFT.isSplitVertically()
? firstInfo.getWeight()
: firstInfo.getWeight() + secondInfo.getWeight());
}
leftHorizontalSplit = uiSettings.getLeftHorizontalSplit();
}
if (rightHorizontalSplit != uiSettings.getRightHorizontalSplit()) {
JComponent component = getComponentAt(ToolWindowAnchor.RIGHT);
if (component instanceof Splitter) {
Splitter splitter = (Splitter)component;
WindowInfoImpl firstInfo = ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError((InternalDecoratorImpl)splitter.getFirstComponent());
WindowInfoImpl secondInfo = ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError((InternalDecoratorImpl)splitter.getSecondComponent());
setComponent(splitter, ToolWindowAnchor.RIGHT, ToolWindowAnchor.RIGHT.isSplitVertically()
? firstInfo.getWeight()
: firstInfo.getWeight() + secondInfo.getWeight());
}
rightHorizontalSplit = uiSettings.getRightHorizontalSplit();
}
}
public boolean isMaximized(@NotNull ToolWindow window) {
return state.isMaximized(window);
}
void setMaximized(@NotNull ToolWindow toolWindow, boolean maximized) {
Pair<Resizer, Component> resizerAndComponent = findResizerAndComponent(toolWindow);
if (resizerAndComponent == null) {
return;
}
if (maximized) {
int size = toolWindow.getAnchor().isHorizontal() ? resizerAndComponent.second.getHeight() : resizerAndComponent.second.getWidth();
stretch(toolWindow, Short.MAX_VALUE);
state.setMaximizedProportion(Pair.create(toolWindow, size));
}
else {
Pair<ToolWindow, Integer> maximizedProportion = state.getMaximizedProportion();
LOG.assertTrue(maximizedProportion != null);
ToolWindow maximizedWindow = maximizedProportion.first;
assert maximizedWindow == toolWindow;
resizerAndComponent.first.setSize(maximizedProportion.second);
state.setMaximizedProportion(null);
}
doLayout();
}
void reset() {
for (Stripe stripe : stripes) {
stripe.reset();
}
state = new ToolWindowPaneState();
revalidate();
}
void onStripeButtonRemoved(@NotNull Project project, @NotNull ToolWindow toolWindow) {
if (!isSquareStripeUI()) return;
if (myLeftToolbar == null || myRightToolbar == null) return;
if (!toolWindow.isAvailable() || toolWindow.getIcon() == null) return;
toolWindow.setVisibleOnLargeStripe(false);
ToolWindowAnchor anchor = toolWindow.getLargeStripeAnchor();
if (ToolWindowAnchor.LEFT.equals(anchor) || ToolWindowAnchor.BOTTOM.equals(anchor)) {
myLeftToolbar.removeStripeButton(project, toolWindow, anchor);
}
else if (ToolWindowAnchor.RIGHT.equals(anchor)) {
myRightToolbar.removeStripeButton(project, toolWindow, anchor);
}
}
void onStripeButtonAdded(@NotNull Project project,
@NotNull ToolWindow toolWindow,
@NotNull ToolWindowAnchor actualAnchor,
@NotNull Comparator<ToolWindow> comparator) {
if (!isSquareStripeUI()) return;
if (myLeftToolbar == null || myRightToolbar == null) return;
ensureDefaultInitialized(project);
ToolWindowAnchor toolWindowAnchor = toolWindow.getAnchor();
if (toolWindowAnchor == ToolWindowAnchor.LEFT && myDefaultLeftButtons.contains(toolWindow.getId())
|| toolWindowAnchor == ToolWindowAnchor.RIGHT && myDefaultRightButtons.contains(toolWindow.getId())
|| toolWindowAnchor == ToolWindowAnchor.BOTTOM && myDefaultBottomButtons.contains(toolWindow.getId())) {
toolWindow.setVisibleOnLargeStripe(true);
actualAnchor = toolWindowAnchor;
}
toolWindow.setLargeStripeAnchor(actualAnchor);
if (!toolWindow.isAvailable() || toolWindow.getIcon() == null || !toolWindow.isVisibleOnLargeStripe()) return;
if (ToolWindowAnchor.LEFT.equals(actualAnchor) || ToolWindowAnchor.BOTTOM.equals(actualAnchor)) {
myLeftToolbar.addStripeButton(project, actualAnchor, comparator, toolWindow);
}
else if (ToolWindowAnchor.RIGHT.equals(actualAnchor)) {
myRightToolbar.addStripeButton(project, actualAnchor, comparator, toolWindow);
}
}
private void ensureDefaultInitialized(@NotNull Project project) {
String key = "NEW_TOOLWINDOW_STRIPE_DEFAULTS";
if (PropertiesComponent.getInstance(project).isTrueValue(key)) {
return;
}
myDefaultLeftButtons = ToolWindowToolbarProvider.getInstance().defaultBottomToolwindows(project, ToolWindowAnchor.LEFT);
myDefaultRightButtons = ToolWindowToolbarProvider.getInstance().defaultBottomToolwindows(project, ToolWindowAnchor.RIGHT);
myDefaultBottomButtons = ToolWindowToolbarProvider.getInstance().defaultBottomToolwindows(project, ToolWindowAnchor.BOTTOM);
PropertiesComponent.getInstance(project).setValue(key, true);
}
@FunctionalInterface
interface Resizer {
void setSize(int size);
abstract class Splitter implements Resizer {
ThreeComponentsSplitter mySplitter;
Splitter(@NotNull ThreeComponentsSplitter splitter) {
mySplitter = splitter;
}
static final class FirstComponent extends Splitter {
FirstComponent(@NotNull ThreeComponentsSplitter splitter) {
super(splitter);
}
@Override
public void setSize(int size) {
mySplitter.setFirstSize(size);
}
}
static final class LastComponent extends Splitter {
LastComponent(@NotNull ThreeComponentsSplitter splitter) {
super(splitter);
}
@Override
public void setSize(int size) {
mySplitter.setLastSize(size);
}
}
}
abstract class LayeredPane implements Resizer {
Component myComponent;
LayeredPane(@NotNull Component component) {
myComponent = component;
}
@Override
public final void setSize(int size) {
_setSize(size);
if (myComponent.getParent() instanceof JComponent) {
JComponent parent = (JComponent)myComponent;
parent.revalidate();
parent.repaint();
}
}
abstract void _setSize(int size);
static final class Left extends LayeredPane {
Left(@NotNull Component component) {
super(component);
}
@Override
public void _setSize(int size) {
myComponent.setSize(size, myComponent.getHeight());
}
}
static final class Right extends LayeredPane {
Right(@NotNull Component component) {
super(component);
}
@Override
public void _setSize(int size) {
Rectangle bounds = myComponent.getBounds();
int delta = size - bounds.width;
bounds.x -= delta;
bounds.width += delta;
myComponent.setBounds(bounds);
}
}
static class Top extends LayeredPane {
Top(@NotNull Component component) {
super(component);
}
@Override
public void _setSize(int size) {
myComponent.setSize(myComponent.getWidth(), size);
}
}
static class Bottom extends LayeredPane {
Bottom(@NotNull Component component) {
super(component);
}
@Override
public void _setSize(int size) {
Rectangle bounds = myComponent.getBounds();
int delta = size - bounds.height;
bounds.y -= delta;
bounds.height += delta;
myComponent.setBounds(bounds);
}
}
}
}
private void addAndSplitDockedComponentCmd(@NotNull JComponent newComponent,
@NotNull WindowInfo info,
boolean dirtyMode,
@NotNull ToolWindowManagerImpl manager) {
ToolWindowAnchor anchor = info.getAnchor();
final class MySplitter extends OnePixelSplitter implements UISettingsListener {
@Override
public void uiSettingsChanged(@NotNull UISettings uiSettings) {
if (anchor == ToolWindowAnchor.LEFT) {
setOrientation(!uiSettings.getLeftHorizontalSplit());
}
else if (anchor == ToolWindowAnchor.RIGHT) {
setOrientation(!uiSettings.getRightHorizontalSplit());
}
}
@Override
public String toString() {
return "[" + getFirstComponent() + "|" + getSecondComponent() + "]";
}
}
Splitter splitter = new MySplitter();
splitter.setOrientation(anchor.isSplitVertically());
if (!anchor.isHorizontal()) {
splitter.setAllowSwitchOrientationByMouseClick(true);
splitter.addPropertyChangeListener(evt -> {
if (!Splitter.PROP_ORIENTATION.equals(evt.getPropertyName())) return;
boolean isSplitterHorizontalNow = !splitter.isVertical();
UISettings settings = UISettings.getInstance();
if (anchor == ToolWindowAnchor.LEFT) {
if (settings.getLeftHorizontalSplit() != isSplitterHorizontalNow) {
settings.setLeftHorizontalSplit(isSplitterHorizontalNow);
settings.fireUISettingsChanged();
}
}
if (anchor == ToolWindowAnchor.RIGHT) {
if (settings.getRightHorizontalSplit() != isSplitterHorizontalNow) {
settings.setRightHorizontalSplit(isSplitterHorizontalNow);
settings.fireUISettingsChanged();
}
}
});
}
JComponent c = getComponentAt(anchor);
// if all components are hidden for anchor we should find the second component to put in a splitter
// otherwise we add empty splitter
if (c == null) {
List<ToolWindowEx> toolWindows = manager.getToolWindowsOn(anchor, Objects.requireNonNull(info.getId()));
toolWindows.removeIf(window -> window == null || window.isSplitMode() == info.isSplit() || !window.isVisible());
if (!toolWindows.isEmpty()) {
c = ((ToolWindowImpl)toolWindows.get(0)).getDecoratorComponent();
}
if (c == null) {
LOG.error("Empty splitter @ " + anchor + " during AddAndSplitDockedComponentCmd for " + info.getId());
}
}
float newWeight;
if (c instanceof InternalDecoratorImpl) {
InternalDecoratorImpl oldComponent = (InternalDecoratorImpl)c;
WindowInfoImpl oldInfo = ToolWindowManagerImpl.getRegisteredMutableInfoOrLogError(oldComponent);
IJSwingUtilities.updateComponentTreeUI(oldComponent);
IJSwingUtilities.updateComponentTreeUI(newComponent);
if (info.isSplit()) {
splitter.setFirstComponent(oldComponent);
splitter.setSecondComponent(newComponent);
float proportion = state.getPreferredSplitProportion(Objects.requireNonNull(oldInfo.getId()), normalizeWeigh(
oldInfo.getSideWeight() / (oldInfo.getSideWeight() + info.getSideWeight())));
splitter.setProportion(proportion);
if (!anchor.isHorizontal() && !anchor.isSplitVertically()) {
newWeight = normalizeWeigh(oldInfo.getWeight() + info.getWeight());
}
else {
newWeight = normalizeWeigh(oldInfo.getWeight());
}
}
else {
splitter.setFirstComponent(newComponent);
splitter.setSecondComponent(oldComponent);
splitter.setProportion(normalizeWeigh(info.getSideWeight()));
if (!anchor.isHorizontal() && !anchor.isSplitVertically()) {
newWeight = normalizeWeigh(oldInfo.getWeight() + info.getWeight());
}
else {
newWeight = normalizeWeigh(info.getWeight());
}
}
}
else {
newWeight = normalizeWeigh(info.getWeight());
}
setComponent(splitter, anchor, newWeight);
if (!dirtyMode) {
layeredPane.validate();
layeredPane.repaint();
}
}
private void addSlidingComponent(@NotNull JComponent component, @NotNull WindowInfo info, boolean dirtyMode) {
if (dirtyMode || !UISettings.getInstance().getAnimateWindows() || RemoteDesktopService.isRemoteSession()) {
// not animated
layeredPane.add(component, JLayeredPane.PALETTE_LAYER);
layeredPane.setBoundsInPaletteLayer(component, info.getAnchor(), info.getWeight());
}
else {
// Prepare top image. This image is scrolling over bottom image.
Image topImage = layeredPane.getTopImage();
Rectangle bounds = component.getBounds();
useSafely(topImage.getGraphics(), topGraphics -> {
component.putClientProperty(TEMPORARY_ADDED, Boolean.TRUE);
try {
layeredPane.add(component, JLayeredPane.PALETTE_LAYER);
layeredPane.moveToFront(component);
layeredPane.setBoundsInPaletteLayer(component, info.getAnchor(), info.getWeight());
component.paint(topGraphics);
layeredPane.remove(component);
}
finally {
component.putClientProperty(TEMPORARY_ADDED, null);
}
});
// prepare bottom image
Image bottomImage = layeredPane.getBottomImage();
Point2D bottomImageOffset = PaintUtil.getFractOffsetInRootPane(layeredPane);
useSafely(bottomImage.getGraphics(), bottomGraphics -> {
bottomGraphics.setClip(0, 0, bounds.width, bounds.height);
bottomGraphics.translate(bottomImageOffset.getX() - bounds.x, bottomImageOffset.getY() - bounds.y);
layeredPane.paint(bottomGraphics);
});
// start animation.
Surface surface = new Surface(topImage, bottomImage, PaintUtil.negate(bottomImageOffset), 1, info.getAnchor(), UISettings.ANIMATION_DURATION);
layeredPane.add(surface, JLayeredPane.PALETTE_LAYER);
surface.setBounds(bounds);
layeredPane.validate();
layeredPane.repaint();
surface.runMovement();
layeredPane.remove(surface);
layeredPane.add(component, JLayeredPane.PALETTE_LAYER);
}
if (!dirtyMode) {
layeredPane.validate();
layeredPane.repaint();
}
}
private void removeSlidingComponent(@NotNull Component component, @NotNull WindowInfo info, boolean dirtyMode) {
UISettings uiSettings = UISettings.getInstance();
if (!dirtyMode && uiSettings.getAnimateWindows() && !RemoteDesktopService.isRemoteSession()) {
Rectangle bounds = component.getBounds();
// Prepare top image. This image is scrolling over bottom image. It contains
// picture of component is being removed.
Image topImage = layeredPane.getTopImage();
useSafely(topImage.getGraphics(), component::paint);
// Prepare bottom image. This image contains picture of component that is located
// under the component to is being removed.
Image bottomImage = layeredPane.getBottomImage();
Point2D bottomImageOffset = PaintUtil.getFractOffsetInRootPane(layeredPane);
useSafely(bottomImage.getGraphics(), bottomGraphics -> {
layeredPane.remove(component);
bottomGraphics.clipRect(0, 0, bounds.width, bounds.height);
bottomGraphics.translate(bottomImageOffset.getX() - bounds.x, bottomImageOffset.getY() - bounds.y);
layeredPane.paint(bottomGraphics);
});
// Remove component from the layered pane and start animation.
Surface surface = new Surface(topImage, bottomImage, PaintUtil.negate(bottomImageOffset), -1, info.getAnchor(), UISettings.ANIMATION_DURATION);
layeredPane.add(surface, JLayeredPane.PALETTE_LAYER);
surface.setBounds(bounds);
layeredPane.validate();
layeredPane.repaint();
surface.runMovement();
layeredPane.remove(surface);
}
else {
// not animated
layeredPane.remove(component);
}
if (!dirtyMode) {
layeredPane.validate();
layeredPane.repaint();
}
}
private static final class ImageRef extends SoftReference<BufferedImage> {
private @Nullable BufferedImage myStrongRef;
ImageRef(@NotNull BufferedImage image) {
super(image);
myStrongRef = image;
}
@Override
public BufferedImage get() {
if (myStrongRef != null) {
BufferedImage img = myStrongRef;
myStrongRef = null; // drop on first request
return img;
}
return super.get();
}
}
private static class ImageCache extends ScaleContext.Cache<ImageRef> {
ImageCache(@NotNull Function<? super ScaleContext, ImageRef> imageProvider) {
super(imageProvider);
}
public BufferedImage get(@NotNull ScaleContext ctx) {
ImageRef ref = getOrProvide(ctx);
BufferedImage image = SoftReference.dereference(ref);
if (image != null) return image;
clear(); // clear to recalculate the image
return get(ctx); // first recalculated image will be non-null
}
}
private final class MyLayeredPane extends JBLayeredPane {
private final Function<ScaleContext, ImageRef> myImageProvider = __ -> {
int width = Math.max(Math.max(1, getWidth()), frame.getWidth());
int height = Math.max(Math.max(1, getHeight()), frame.getHeight());
return new ImageRef(ImageUtil.createImage(getGraphicsConfiguration(), width, height, BufferedImage.TYPE_INT_RGB));
};
/*
* These images are used to perform animated showing and hiding of components.
* They are the member for performance reason.
*/
private final ImageCache myBottomImageCache = new ImageCache(myImageProvider);
private final ImageCache myTopImageCache = new ImageCache(myImageProvider);
MyLayeredPane(@NotNull JComponent splitter) {
setOpaque(false);
add(splitter, JLayeredPane.DEFAULT_LAYER);
}
final Image getBottomImage() {
return myBottomImageCache.get(ScaleContext.create(this));
}
final Image getTopImage() {
return myTopImageCache.get(ScaleContext.create(this));
}
/**
* When component size becomes larger then bottom and top images should be enlarged.
*/
@Override
public void doLayout() {
final int width = getWidth();
final int height = getHeight();
if (width < 0 || height < 0) {
return;
}
// Resize component at the DEFAULT layer. It should be only on component in that layer
Component[] components = getComponentsInLayer(JLayeredPane.DEFAULT_LAYER);
LOG.assertTrue(components.length <= 1);
for (Component component : components) {
component.setBounds(0, 0, getWidth(), getHeight());
}
// Resize components at the PALETTE layer
components = getComponentsInLayer(JLayeredPane.PALETTE_LAYER);
for (Component component : components) {
if (!(component instanceof InternalDecoratorImpl)) {
continue;
}
WindowInfo info = (((InternalDecoratorImpl)component)).getToolWindow().getWindowInfo();
float weight = info.getAnchor().isHorizontal()
? (float)component.getHeight() / getHeight()
: (float)component.getWidth() / getWidth();
setBoundsInPaletteLayer(component, info.getAnchor(), weight);
}
}
final void setBoundsInPaletteLayer(@NotNull Component component, @NotNull ToolWindowAnchor anchor, float weight) {
if (weight < .0f) {
weight = WindowInfoImpl.DEFAULT_WEIGHT;
}
else if (weight > 1.0f) {
weight = 1.0f;
}
if (ToolWindowAnchor.TOP == anchor) {
component.setBounds(0, 0, getWidth(), (int)(getHeight() * weight + .5f));
}
else if (ToolWindowAnchor.LEFT == anchor) {
component.setBounds(0, 0, (int)(getWidth() * weight + .5f), getHeight());
}
else if (ToolWindowAnchor.BOTTOM == anchor) {
final int height = (int)(getHeight() * weight + .5f);
component.setBounds(0, getHeight() - height, getWidth(), height);
}
else if (ToolWindowAnchor.RIGHT == anchor) {
final int width = (int)(getWidth() * weight + .5f);
component.setBounds(getWidth() - width, 0, width, getHeight());
}
else {
LOG.error("unknown anchor " + anchor);
}
}
}
void setStripesOverlayed(boolean value) {
state.setStripesOverlaid(value);
updateToolStripesVisibility(UISettings.getInstance());
}
private static float normalizeWeigh(final float weight) {
if (weight <= 0) return WindowInfoImpl.DEFAULT_WEIGHT;
if (weight >= 1) return 1 - WindowInfoImpl.DEFAULT_WEIGHT;
return weight;
}
}
|
dahlstrom-g/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowsPane.java
|
Java
|
apache-2.0
| 40,236 |
package de.adihubba;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ObjectUtils {
private static final int DEFAULT_DOUBLE_PRECISION = 8;
private static final double[] POWER_OF_TEN = new double[15];
static {
for (int i = 0; i < POWER_OF_TEN.length; i++) {
POWER_OF_TEN[i] = Math.pow(10, i);
}
}
public static boolean smallerOrEqualsDoublePrecision(double double1, double double2) {
return smallerOrEqualsDoublePrecision(double1, double2, DEFAULT_DOUBLE_PRECISION);
}
public static boolean smallerOrEqualsDoublePrecision(double double1, double double2, int precision) {
// try to save the POWER operation
double factor = (precision >= 0 && precision < POWER_OF_TEN.length) ? POWER_OF_TEN[precision] : Math.pow(10, precision);
long result = Math.round((double1 - double2) * factor);
if (result <= 0) {
return true;
}
return false;
}
public static boolean equalsDoublePrecision(double double1, double double2) {
return equalsDoublePrecision(double1, double2, DEFAULT_DOUBLE_PRECISION);
}
public static boolean equalsDoublePrecision(double double1, double double2, int precision) {
double absDifference = Math.abs(double1 - double2);
if (absDifference == 0.0) {
// don't calculate, if result is already zero
return true;
}
if (absDifference >= 1) {
return false;
}
// try to save the POWER operation
double factor = (precision >= 0 && precision < POWER_OF_TEN.length) ? POWER_OF_TEN[precision] : Math.pow(10, precision);
return (absDifference * factor < 1);
}
public static boolean smallerDoublePrecision(double double1, double double2) {
return smallerDoublePrecision(double1, double2, DEFAULT_DOUBLE_PRECISION);
}
public static boolean smallerDoublePrecision(double double1, double double2, int precision) {
// try to save the POWER operation
double factor = (precision >= 0 && precision < POWER_OF_TEN.length) ? POWER_OF_TEN[precision] : Math.pow(10, precision);
long result = Math.round((double1 - double2) * factor);
if (result < 0) {
return true;
}
return false;
}
public static <O> List<O> asReadonlyList(O... objects) {
return objects == null ? Collections.EMPTY_LIST : Arrays.asList(objects);
}
public static boolean equalsObject(Object obj1, Object obj2) {
if (obj1 == obj2) {
// both objects are identical or null
return true;
}
if (obj1 == null || obj2 == null) {
// only one side is null
return false;
}
// from here both of them are not null
// don't compare the classes as it is done in the equals routine and should be up
// to objects we are comparing
return obj1.equals(obj2);
}
public static boolean arrayHasElements(Object[] obj) {
if (obj != null && obj.length != 0) {
for (Object object : obj) {
if (object != null) {
return true;
}
}
}
return false;
}
}
|
adihubba/javafx-3d-surface-chart
|
src/main/java/de/adihubba/ObjectUtils.java
|
Java
|
apache-2.0
| 3,433 |
/**
* Copyright (C) 2015 Red Hat, 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 io.fabric8.kubernetes.client.mock;
import io.fabric8.kubernetes.api.model.extensions.Deployment;
import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder;
import io.fabric8.kubernetes.api.model.extensions.DeploymentList;
import io.fabric8.kubernetes.api.model.extensions.DeploymentListBuilder;
import io.fabric8.kubernetes.api.model.extensions.ReplicaSet;
import io.fabric8.kubernetes.api.model.extensions.ReplicaSetBuilder;
import io.fabric8.kubernetes.api.model.extensions.ReplicaSetListBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.server.mock.KubernetesServer;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class DeploymentTest {
@Rule
public KubernetesServer server = new KubernetesServer();
@Test
public void testList() {
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/deployments").andReturn(200, new DeploymentListBuilder().build()).once();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/deployments").andReturn(200, new DeploymentListBuilder()
.addNewItem().and()
.addNewItem().and().build()).once();
server.expect().withPath("/apis/extensions/v1beta1/deployments").andReturn(200, new DeploymentListBuilder()
.addNewItem().and()
.addNewItem().and()
.addNewItem()
.and().build()).once();
KubernetesClient client = server.getClient();
DeploymentList deploymentList = client.extensions().deployments().list();
assertNotNull(deploymentList);
assertEquals(0, deploymentList.getItems().size());
deploymentList = client.extensions().deployments().inNamespace("ns1").list();
assertNotNull(deploymentList);
assertEquals(2, deploymentList.getItems().size());
deploymentList = client.extensions().deployments().inAnyNamespace().list();
assertNotNull(deploymentList);
assertEquals(3, deploymentList.getItems().size());
}
@Test
public void testListWithLabels() {
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/deployments?labelSelector=" + toUrlEncoded("key1=value1,key2=value2,key3=value3")).andReturn(200, new DeploymentListBuilder().build()).always();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/deployments?labelSelector=" + toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new DeploymentListBuilder()
.addNewItem().and()
.addNewItem().and()
.addNewItem().and()
.build()).once();
KubernetesClient client = server.getClient();
DeploymentList deploymentList = client.extensions().deployments()
.withLabel("key1", "value1")
.withLabel("key2", "value2")
.withLabel("key3", "value3")
.list();
assertNotNull(deploymentList);
assertEquals(0, deploymentList.getItems().size());
deploymentList = client.extensions().deployments()
.withLabel("key1", "value1")
.withLabel("key2", "value2")
.list();
assertNotNull(deploymentList);
assertEquals(3, deploymentList.getItems().size());
}
@Test
public void testGet() {
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/deployments/deployment1").andReturn(200, new DeploymentBuilder().build()).once();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/deployments/deployment2").andReturn(200, new DeploymentBuilder().build()).once();
KubernetesClient client = server.getClient();
Deployment deployment = client.extensions().deployments().withName("deployment1").get();
assertNotNull(deployment);
deployment = client.extensions().deployments().withName("deployment2").get();
assertNull(deployment);
deployment = client.extensions().deployments().inNamespace("ns1").withName("deployment2").get();
assertNotNull(deployment);
}
@Test
public void testDelete() {
Deployment deployment1 = new DeploymentBuilder().withNewMetadata()
.withName("deployment1")
.addToLabels("key1", "value1")
.withResourceVersion("1")
.withGeneration(1L)
.endMetadata()
.withNewSpec()
.withNewSelector()
.addToMatchLabels("key1", "value1")
.endSelector()
.withReplicas(0)
.endSpec()
.withNewStatus()
.withReplicas(1)
.withObservedGeneration(1l)
.endStatus()
.build();
ReplicaSet replicaSet1 = new ReplicaSetBuilder().withNewMetadata()
.withName("rs1")
.addToLabels("key1", "value1")
.withResourceVersion("1")
.withGeneration(1L)
.endMetadata()
.withNewSpec()
.withNewSelector()
.addToMatchLabels("key1", "value1")
.endSelector()
.withReplicas(0)
.endSpec()
.withNewStatus()
.withReplicas(1)
.withObservedGeneration(1l)
.endStatus()
.build();
Deployment deployment2 = new DeploymentBuilder().withNewMetadata()
.withName("deployment2")
.addToLabels("key2", "value2")
.withResourceVersion("1")
.withGeneration(1L)
.endMetadata()
.withNewSpec()
.withNewSelector()
.addToMatchLabels("key2", "value2")
.endSelector()
.withReplicas(0)
.endSpec()
.withNewStatus()
.withReplicas(1)
.withObservedGeneration(1l)
.endStatus()
.build();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/deployments/deployment1").andReturn(200, deployment1).once();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/deployments/deployment1").andReturn(200, new DeploymentBuilder(deployment1).editSpec().withReplicas(0).endSpec().build()).times(5);
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/replicasets?labelSelector=key1%3Dvalue1").andReturn(200, new ReplicaSetListBuilder().addToItems(replicaSet1).build()).once();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/replicasets/rs1").andReturn(200, replicaSet1).once();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/deployments/deployment2").andReturn(200, deployment2).once();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/deployments/deployment2").andReturn(200, new DeploymentBuilder(deployment2).editSpec().withReplicas(0).endSpec().build()).times(5);
KubernetesClient client = server.getClient();
Boolean deleted = client.extensions().deployments().withName("deployment1").delete();
assertNotNull(deleted);
deleted = client.extensions().deployments().withName("deployment2").delete();
assertFalse(deleted);
deleted = client.extensions().deployments().inNamespace("ns1").withName("deployment2").delete();
assertTrue(deleted);
}
@Test
public void testDeleteMulti() {
Deployment deployment1 = new DeploymentBuilder().withNewMetadata()
.withNamespace("test")
.withName("deployment1")
.withResourceVersion("1")
.withGeneration(2L)
.endMetadata()
.withNewSpec()
.withReplicas(0)
.endSpec()
.withNewStatus()
.withReplicas(1)
.withObservedGeneration(1l)
.endStatus()
.build();
Deployment deployment2 = new DeploymentBuilder().withNewMetadata()
.withNamespace("ns1")
.withName("deployment2")
.withResourceVersion("1")
.withGeneration(2L)
.endMetadata()
.withNewSpec()
.withReplicas(0)
.endSpec()
.withNewStatus()
.withReplicas(1)
.withObservedGeneration(1l)
.endStatus()
.build();
Deployment deployment3 = new DeploymentBuilder().withNewMetadata().withName("deployment3").withNamespace("any").and().build();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/deployments/deployment1").andReturn(200, deployment1).once();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/test/deployments/deployment1").andReturn(200, new DeploymentBuilder(deployment1)
.editStatus()
.withReplicas(0)
.withObservedGeneration(2l)
.endStatus()
.build()).times(5);
server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/deployments/deployment2").andReturn(200, deployment2).once();
server.expect().withPath("/apis/extensions/v1beta1/namespaces/ns1/deployments/deployment2").andReturn(200, new DeploymentBuilder(deployment2)
.editStatus()
.withReplicas(0)
.withObservedGeneration(2l)
.endStatus()
.build()).times(5);
KubernetesClient client = server.getClient();
Boolean deleted = client.extensions().deployments().inAnyNamespace().delete(deployment1, deployment2);
assertTrue(deleted);
deleted = client.extensions().deployments().inAnyNamespace().delete(deployment3);
assertFalse(deleted);
}
@Test(expected = KubernetesClientException.class)
public void testDeleteWithNamespaceMismatch() {
Deployment deployment1 = new DeploymentBuilder().withNewMetadata().withName("deployment1").withNamespace("test").and().build();
KubernetesClient client = server.getClient();
Boolean deleted = client.extensions().deployments().inNamespace("test1").delete(deployment1);
assertNotNull(deleted);
}
@Test(expected = KubernetesClientException.class)
public void testCreateWithNameMismatch() {
Deployment deployment1 = new DeploymentBuilder().withNewMetadata().withName("deployment1").withNamespace("test").and().build();
Deployment deployment2 = new DeploymentBuilder().withNewMetadata().withName("deployment2").withNamespace("ns1").and().build();
KubernetesClient client = server.getClient();
client.extensions().deployments().inNamespace("test1").withName("mydeployment1").create(deployment1);
}
/**
* Converts string to URL encoded string.
* It's not a fullblown converter, it serves just the purpose of this test.
* @param str
* @return
*/
private static final String toUrlEncoded(String str) {
return str.replaceAll("=", "%3D");
}
}
|
jimmidyson/kubernetes-client
|
kubernetes-tests/src/test/java/io/fabric8/kubernetes/client/mock/DeploymentTest.java
|
Java
|
apache-2.0
| 10,860 |
/*
Copyright 2019 The Knative 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
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.
*/
// Code generated by injection-gen. DO NOT EDIT.
package fake
import (
"context"
fake "github.com/knative/pkg/client/injection/informers/authentication/factory/fake"
policy "github.com/knative/pkg/client/injection/informers/authentication/v1alpha1/policy"
controller "github.com/knative/pkg/controller"
injection "github.com/knative/pkg/injection"
)
var Get = policy.Get
func init() {
injection.Fake.RegisterInformer(withInformer)
}
func withInformer(ctx context.Context) (context.Context, controller.Informer) {
f := fake.Get(ctx)
inf := f.Authentication().V1alpha1().Policies()
return context.WithValue(ctx, policy.Key{}, inf), inf.Informer()
}
|
knative/build
|
vendor/github.com/knative/pkg/client/injection/informers/authentication/v1alpha1/policy/fake/fake.go
|
GO
|
apache-2.0
| 1,229 |
package org.onetwo.common.data;
import java.io.Serializable;
/*****
* @author wayshall
*
*/
@SuppressWarnings("serial")
public class ValueWrapper<T> implements Serializable{
public static <E> ValueWrapper<E> wrap(E value){
return new ValueWrapper<E>(value);
}
public static <E> ValueWrapper<E> create(){
return new ValueWrapper<E>(null);
}
private T value;
private ValueWrapper(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public boolean isPresent() {
return this.value!=null;
}
public void setValue(T value) {
this.value = value;
}
}
|
wayshall/onetwo
|
core/modules/common/src/main/java/org/onetwo/common/data/ValueWrapper.java
|
Java
|
apache-2.0
| 602 |
/* ###
* IP: GHIDRA
*
* 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 ghidra.app.util.viewer.field;
import java.math.BigInteger;
import docking.widgets.OptionDialog;
import docking.widgets.fieldpanel.field.*;
import docking.widgets.fieldpanel.support.FieldLocation;
import ghidra.app.util.HighlightProvider;
import ghidra.app.util.viewer.format.FieldFormatModel;
import ghidra.app.util.viewer.proxy.ProxyObj;
import ghidra.framework.options.Options;
import ghidra.framework.options.ToolOptions;
import ghidra.program.model.listing.CodeUnit;
import ghidra.program.model.listing.Data;
import ghidra.program.util.ProgramLocation;
import ghidra.program.util.SpacerFieldLocation;
import ghidra.util.StringUtilities;
import ghidra.util.classfinder.ClassSearcher;
/**
* Generates Spacer Fields.
* <P>
* This field is not meant to be loaded by the {@link ClassSearcher}, hence the X in the name.
*/
public class SpacerFieldFactory extends FieldFactory {
public static final String FIELD_NAME = "Spacer";
private String text = null;
/**
* Constructor
*/
public SpacerFieldFactory() {
super(FIELD_NAME);
}
/**
* Constructor
* @param model the model that the field belongs to.
* @param hsProvider the HightLightStringProvider.
* @param displayOptions the Options for display properties.
* @param fieldOptions the Options for field specific properties.
*/
private SpacerFieldFactory(FieldFormatModel model, HighlightProvider hsProvider,
Options displayOptions, Options fieldOptions) {
super(FIELD_NAME, model, hsProvider, displayOptions, fieldOptions);
}
/**
* Constructor
* @param text The text to display in the field.
* @param model The Field model that will use this Address factory.
* @param hsProvider the HightLightProvider.
* @param displayOptions the Options for display properties.
* @param fieldOptions the Options for field specific properties.
*/
public SpacerFieldFactory(String text, FieldFormatModel model, HighlightProvider hsProvider,
Options displayOptions, Options fieldOptions) {
super(FIELD_NAME, model, hsProvider, displayOptions, fieldOptions);
this.text = text;
}
/**
* Sets the text for the spacer field
* @param text the text to display in the listing
*/
public void setText(String text) {
if (text != null && text.length() == 0) {
text = null;
}
this.text = text;
}
/**
* Sets the literal text to display in this field.
*/
public void setText() {
String newText =
OptionDialog.showInputSingleLineDialog(null, "Input Spacer Text", "Text", text);
if (newText != null) {
newText = newText.trim();
if (newText.equals("")) {
text = null;
}
else {
text = newText;
}
}
model.update();
}
/**
* Returns the spacer field's text
*/
public String getText() {
return text;
}
@Override
public ListingField getField(ProxyObj<?> proxy, int varWidth) {
if (enabled && (text != null)) {
AttributedString as = new AttributedString(text, color, getMetrics());
FieldElement field = new TextFieldElement(as, 0, 0);
return ListingTextField.createSingleLineTextField(this, proxy, field, startX + varWidth,
width, hlProvider);
}
return null;
}
@Override
public String getFieldText() {
if (text == null) {
return "";
}
return text;
}
@Override
public FieldLocation getFieldLocation(ListingField bf, BigInteger index, int fieldNum,
ProgramLocation programLoc) {
if (!(programLoc instanceof SpacerFieldLocation)) {
return null;
}
SpacerFieldLocation loc = (SpacerFieldLocation) programLoc;
if (loc.getText().equals(text)) {
return new FieldLocation(index, fieldNum, 0, loc.getCharOffset());
}
return null;
}
@Override
public ProgramLocation getProgramLocation(int row, int col, ListingField bf) {
Object obj = bf.getProxy().getObject();
if (!(obj instanceof CodeUnit)) {
return null;
}
CodeUnit cu = (CodeUnit) obj;
int[] cpath = null;
if (obj instanceof Data) {
cpath = ((Data) obj).getComponentPath();
}
return new SpacerFieldLocation(cu.getProgram(), cu.getMinAddress(), cpath, col, text);
}
/**
* Returns the string to highlight
* @param bf the ListingTextField
* @param row the row in the field
* @param col the column in the field
* @param loc the programLocation.
*/
public String getStringToHighlight(ListingTextField bf, int row, int col, ProgramLocation loc) {
if (loc == null) {
return null;
}
String s = ((SpacerFieldLocation) loc).getText();
return StringUtilities.findWord(s, col);
}
@Override
public boolean acceptsType(int category, Class<?> proxyObjectClass) {
return true;
}
@Override
public FieldFactory newInstance(FieldFormatModel formatModel, HighlightProvider provider,
ToolOptions options, ToolOptions fieldOptions) {
return new SpacerFieldFactory(formatModel, provider, options, fieldOptions);
}
}
|
NationalSecurityAgency/ghidra
|
Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/SpacerFieldFactory.java
|
Java
|
apache-2.0
| 5,415 |
/*
* Copyright 2020 Google LLC
*
* 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 pubsublite;
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;
import com.google.cloud.pubsublite.BacklogLocation;
import com.google.cloud.pubsublite.CloudRegion;
import com.google.cloud.pubsublite.ProjectNumber;
import com.google.cloud.pubsublite.ReservationName;
import com.google.cloud.pubsublite.ReservationPath;
import com.google.cloud.pubsublite.SeekTarget;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Random;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
public class QuickStartIT {
private ByteArrayOutputStream bout;
private PrintStream out;
Random rand = new Random();
private static final Long projectNumber =
Long.parseLong(System.getenv("GOOGLE_CLOUD_PROJECT_NUMBER"));
private String cloudRegion = "us-central1";
private final char zoneId = (char) (rand.nextInt(3) + 'a');
private static final String suffix = UUID.randomUUID().toString();
private static final String reservationId = "lite-reservation-" + suffix;
private static final String topicId = "lite-topic-" + suffix;
private static final String subscriptionId = "lite-subscription-" + suffix;
private static final int partitions = 2;
private static final int messageCount = 10;
ReservationPath reservationPath =
ReservationPath.newBuilder()
.setProject(ProjectNumber.of(projectNumber))
.setLocation(CloudRegion.of(cloudRegion))
.setName(ReservationName.of(reservationId))
.build();
private static void requireEnvVar(String varName) {
assertNotNull(
"Environment variable " + varName + " is required to perform these tests.",
System.getenv(varName));
}
@Rule public Timeout globalTimeout = Timeout.seconds(300); // 5 minute timeout
@BeforeClass
public static void checkRequirements() {
requireEnvVar("GOOGLE_CLOUD_PROJECT_NUMBER");
}
@Before
public void setUp() throws Exception {
bout = new ByteArrayOutputStream();
out = new PrintStream(bout);
System.setOut(out);
}
@After
public void tearDown() throws Exception {
System.setOut(null);
}
@Test
public void testQuickstart() throws Exception {
// Create a reservation.
CreateReservationExample.createReservationExample(
projectNumber, cloudRegion, reservationId, /*throughputCapacity=*/ 4);
assertThat(bout.toString()).contains(reservationId);
assertThat(bout.toString()).contains("created successfully");
bout.reset();
// Create a regional topic.
CreateTopicExample.createTopicExample(
cloudRegion, zoneId, projectNumber, topicId, reservationId, partitions, /*regional=*/ true);
assertThat(bout.toString()).contains(" (regional topic) created successfully");
bout.reset();
// Create a zonal topic.
CreateTopicExample.createTopicExample(
cloudRegion,
zoneId,
projectNumber,
topicId,
reservationId,
partitions,
/*regional=*/ false);
assertThat(bout.toString()).contains(" (zonal topic) created successfully");
bout.reset();
// Get a reservation.
GetReservationExample.getReservationExample(projectNumber, cloudRegion, reservationId);
assertThat(bout.toString()).contains(reservationId);
assertThat(bout.toString()).contains("4 units of throughput capacity.");
bout.reset();
// List reservations.
ListReservationsExample.listReservationsExample(projectNumber, cloudRegion);
assertThat(bout.toString()).contains("reservation(s) listed");
bout.reset();
// Update reservation to have a throughput capacity of 8 units.
UpdateReservationExample.updateReservationExample(projectNumber, cloudRegion, reservationId, 8);
assertThat(bout.toString()).contains("throughput_capacity=8");
bout.reset();
// Get a regional topic.
GetTopicExample.getTopicExample(
cloudRegion, zoneId, projectNumber, topicId, /*regional=*/ true);
assertThat(bout.toString()).contains(cloudRegion + "/topics/" + topicId);
assertThat(bout.toString()).contains(String.format("%s partition(s).", partitions));
bout.reset();
// Get a zonal topic
GetTopicExample.getTopicExample(
cloudRegion, zoneId, projectNumber, topicId, /*regional=*/ false);
assertThat(bout.toString().contains(cloudRegion + "-" + zoneId + "/topics/" + topicId));
assertThat(bout.toString()).contains(String.format("%s partition(s).", partitions));
bout.reset();
// List regional topics.
ListTopicsExample.listTopicsExample(cloudRegion, zoneId, projectNumber, /*regional=*/ true);
assertThat(bout.toString().contains(cloudRegion + "/topics/" + topicId));
assertThat(bout.toString()).contains("topic(s) listed");
bout.reset();
// List zonal topics.
ListTopicsExample.listTopicsExample(cloudRegion, zoneId, projectNumber, /*regional=*/ false);
assertThat(bout.toString().contains(cloudRegion + "-" + zoneId + "/topics/" + topicId));
assertThat(bout.toString()).contains("topic(s) listed");
bout.reset();
// Update a regional topic.
UpdateTopicExample.updateTopicExample(
cloudRegion, zoneId, projectNumber, topicId, reservationId, /*regional=*/ true);
assertThat(bout.toString()).contains("seconds: 604800");
assertThat(bout.toString()).contains("per_partition_bytes: 34359738368");
assertThat(bout.toString()).contains("throughput_reservation: \"" + reservationPath.toString());
bout.reset();
// Update a zonal topic.
UpdateTopicExample.updateTopicExample(
cloudRegion, zoneId, projectNumber, topicId, reservationId, /*regional=*/ false);
assertThat(bout.toString()).contains("seconds: 604800");
assertThat(bout.toString()).contains("per_partition_bytes: 34359738368");
assertThat(bout.toString()).contains("throughput_reservation: \"" + reservationPath.toString());
bout.reset();
// Create a regional subscription.
CreateSubscriptionExample.createSubscriptionExample(
cloudRegion, zoneId, projectNumber, topicId, subscriptionId, /*regional=*/ true);
assertThat(bout.toString().contains(cloudRegion + "/subscriptions/" + subscriptionId));
assertThat(bout.toString()).contains("created successfully");
bout.reset();
// Create a zonal subscription.
CreateSubscriptionExample.createSubscriptionExample(
cloudRegion, zoneId, projectNumber, topicId, subscriptionId, /*regional=*/ false);
assertThat(
bout.toString().contains(cloudRegion + "-" + zoneId + "/subscriptions/" + subscriptionId));
assertThat(bout.toString()).contains("created successfully");
bout.reset();
// Get a regional subscription.
GetSubscriptionExample.getSubscriptionExample(
cloudRegion, zoneId, projectNumber, subscriptionId, /*regional=*/ true);
assertThat(bout.toString().contains(cloudRegion + "/subscriptions/" + subscriptionId));
bout.reset();
// Get a zonal subscription.
GetSubscriptionExample.getSubscriptionExample(
cloudRegion, zoneId, projectNumber, subscriptionId, /*regional=*/ false);
assertThat(
bout.toString().contains(cloudRegion + "-" + zoneId + "/subscriptions/" + subscriptionId));
bout.reset();
// List subscriptions in a regional topic.
ListSubscriptionsInTopicExample.listSubscriptionsInTopicExample(
cloudRegion, zoneId, projectNumber, topicId, /*regional=*/ true);
assertThat(bout.toString()).contains("subscription(s) listed in the regional topic");
// List subscriptions in a zonal topic.
ListSubscriptionsInTopicExample.listSubscriptionsInTopicExample(
cloudRegion, zoneId, projectNumber, topicId, /*regional=*/ false);
assertThat(bout.toString()).contains("subscription(s) listed in the zonal topic");
bout.reset();
// List regional subscriptions in a project.
ListSubscriptionsInProjectExample.listSubscriptionsInProjectExample(
cloudRegion, zoneId, projectNumber, /*regional=*/ true);
assertThat(bout.toString()).contains("subscription(s) listed in the project");
bout.reset();
// List zonal subscriptions in a project.
ListSubscriptionsInProjectExample.listSubscriptionsInProjectExample(
cloudRegion, zoneId, projectNumber, /*regional=*/ false);
assertThat(bout.toString()).contains("subscription(s) listed in the project");
bout.reset();
// Update a regional subscription.
UpdateSubscriptionExample.updateSubscriptionExample(
cloudRegion, zoneId, projectNumber, subscriptionId, /*regional=*/ true);
assertThat(bout.toString()).contains("delivery_requirement: DELIVER_AFTER_STORED");
bout.reset();
// Update a zonal subscription.
UpdateSubscriptionExample.updateSubscriptionExample(
cloudRegion, zoneId, projectNumber, subscriptionId, /*regional=*/ false);
assertThat(bout.toString()).contains("delivery_requirement: DELIVER_AFTER_STORED");
bout.reset();
// Publish to a regional topic.
PublisherExample.publisherExample(
cloudRegion, zoneId, projectNumber, topicId, messageCount, /*regional=*/ true);
assertThat(bout.toString()).contains("Published " + messageCount + " messages.");
bout.reset();
// Publish to a zonal topic.
PublisherExample.publisherExample(
cloudRegion, zoneId, projectNumber, topicId, messageCount, /*regional=*/ false);
assertThat(bout.toString()).contains("Published " + messageCount + " messages.");
bout.reset();
// Publish with ordering key to a regional topic.
PublishWithOrderingKeyExample.publishWithOrderingKeyExample(
cloudRegion, zoneId, projectNumber, topicId, /*regional=*/ true);
assertThat(bout.toString()).contains("Published a message with ordering key:");
bout.reset();
// Publish with ordering key to a zonal topic.
PublishWithOrderingKeyExample.publishWithOrderingKeyExample(
cloudRegion, zoneId, projectNumber, topicId, /*regional=*/ false);
assertThat(bout.toString()).contains("Published a message with ordering key:");
bout.reset();
// Publish messages with custom attributes to a regional topic.
PublishWithCustomAttributesExample.publishWithCustomAttributesExample(
cloudRegion, zoneId, projectNumber, topicId, /*regional=*/ true);
assertThat(bout.toString()).contains("Published a message with custom attributes:");
bout.reset();
// Publish messages with custom attributes to a zonal topic.
PublishWithCustomAttributesExample.publishWithCustomAttributesExample(
cloudRegion, zoneId, projectNumber, topicId, /*regional=*/ false);
assertThat(bout.toString()).contains("Published a message with custom attributes:");
bout.reset();
// Publish with batch settings to a regional topic.
PublishWithBatchSettingsExample.publishWithBatchSettingsExample(
cloudRegion, zoneId, projectNumber, topicId, messageCount, /*regional=*/ true);
assertThat(bout.toString())
.contains("Published " + messageCount + " messages with batch settings.");
bout.reset();
// Publish with batch settings to a zonal topic.
PublishWithBatchSettingsExample.publishWithBatchSettingsExample(
cloudRegion, zoneId, projectNumber, topicId, messageCount, /*regional=*/ false);
assertThat(bout.toString())
.contains("Published " + messageCount + " messages with batch settings.");
bout.reset();
// Subscribe to a regional subscription.
SubscriberExample.subscriberExample(
cloudRegion, zoneId, projectNumber, subscriptionId, /*regional=*/ true);
assertThat(bout.toString()).contains("Listening");
for (int i = 0; i < messageCount; ++i) {
assertThat(bout.toString()).contains(String.format("Data : message-%s", i));
}
assertThat(bout.toString()).contains("Subscriber is shut down: TERMINATED");
bout.reset();
// Subscribe to a zonal subscription.
SubscriberExample.subscriberExample(
cloudRegion, zoneId, projectNumber, subscriptionId, /*regional=*/ false);
assertThat(bout.toString()).contains("Listening");
for (int i = 0; i < messageCount; ++i) {
assertThat(bout.toString()).contains(String.format("Data : message-%s", i));
}
assertThat(bout.toString()).contains("Subscriber is shut down: TERMINATED");
bout.reset();
// Seek in a regional subscription.
SeekSubscriptionExample.seekSubscriptionExample(
cloudRegion,
zoneId,
projectNumber,
subscriptionId,
SeekTarget.of(BacklogLocation.BEGINNING),
/*waitForOperation=*/ false,
/*regional=*/ true);
assertThat(bout.toString()).contains("initiated successfully");
bout.reset();
// Seek in a zonal subscription.
SeekSubscriptionExample.seekSubscriptionExample(
cloudRegion,
zoneId,
projectNumber,
subscriptionId,
SeekTarget.of(BacklogLocation.BEGINNING),
/*waitForOperation=*/ false,
/*regional=*/ false);
assertThat(bout.toString()).contains("initiated successfully");
bout.reset();
// Delete a regional subscription.
DeleteSubscriptionExample.deleteSubscriptionExample(
cloudRegion, zoneId, projectNumber, subscriptionId, /*regional=*/ true);
assertThat(bout.toString()).contains(" deleted successfully");
bout.reset();
// Delete a zonal subscription.
DeleteSubscriptionExample.deleteSubscriptionExample(
cloudRegion, zoneId, projectNumber, subscriptionId, /*regional=*/ false);
assertThat(bout.toString()).contains(" deleted successfully");
bout.reset();
// Delete a regional topic.
DeleteTopicExample.deleteTopicExample(
cloudRegion, zoneId, projectNumber, topicId, /*regional=*/ true);
assertThat(bout.toString()).contains(" (regional topic) deleted successfully");
bout.reset();
// Delete a zonal topic.
DeleteTopicExample.deleteTopicExample(
cloudRegion, zoneId, projectNumber, topicId, /*regional=*/ false);
assertThat(bout.toString()).contains(" (zonal topic) deleted successfully");
bout.reset();
// Delete a reservation.
DeleteReservationExample.deleteReservationExample(projectNumber, cloudRegion, reservationId);
assertThat(bout.toString()).contains("deleted successfully");
}
}
|
googleapis/java-pubsublite
|
samples/snippets/src/test/java/pubsublite/QuickStartIT.java
|
Java
|
apache-2.0
| 15,069 |
/*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.internal.gosu.ir.nodes;
import gw.lang.reflect.IMethodInfo;
import gw.lang.reflect.IType;
import gw.lang.reflect.IRelativeTypeInfo;
import gw.lang.reflect.IFunctionType;
import gw.lang.reflect.IConstructorInfo;
import gw.lang.ir.IRType;
import gw.lang.ir.IRTypeConstants;
import gw.internal.gosu.parser.DynamicFunctionSymbol;
import gw.internal.gosu.ir.transform.AbstractElementTransformer;
import gw.internal.gosu.ir.transform.util.IRTypeResolver;
import gw.lang.reflect.java.IJavaClassInfo;
import gw.lang.reflect.java.IJavaClassMethod;
import java.lang.reflect.Method;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class IRMethodFactory {
public static IRMethodFromMethodInfo createIRMethod(IMethodInfo originalMethodInfo, IFunctionType functionType) {
if (originalMethodInfo == null) {
return null;
}
return new IRMethodFromMethodInfo(originalMethodInfo, functionType);
}
public static IRMethod createIRMethod( IConstructorInfo constructor ) {
return new IRMethodFromConstructorInfo( constructor );
}
public static IRMethod createIRMethod(Class cls, String name, Class... paramTypes) {
return createIRMethod(AbstractElementTransformer.getDeclaredMethod(cls, name, paramTypes));
}
public static IRMethod createIRMethod(IJavaClassInfo cls, String name, Class... paramTypes) {
return createIRMethod(AbstractElementTransformer.getDeclaredMethod(cls, name, paramTypes));
}
public static IRMethod createIRMethod(Method method) {
return new IRMethodFromMethod(method);
}
public static IRMethod createIRMethod(IJavaClassMethod method) {
return new IRMethodFromJavaMethodInfo(method);
}
public static IRMethod createConstructorIRMethod(IType gosuClass, DynamicFunctionSymbol dfs, int numberOfTypeParameters) {
return new IRMethodForConstructorSymbol(gosuClass, dfs, numberOfTypeParameters);
}
public static IRMethod createIRMethod(IType owner, String name, IType returnType, IType[] parameterTypes, IRelativeTypeInfo.Accessibility accessibility, boolean bStatic) {
return new SyntheticIRMethod( owner, name, IRTypeResolver.getDescriptor(returnType), convertToIRTypes(parameterTypes), accessibility, bStatic );
}
public static IRMethod createIRMethod(IType owner, String name, IRType returnType, List<IRType> parameterTypes, IRelativeTypeInfo.Accessibility accessibility, boolean bStatic) {
return new SyntheticIRMethod( owner, name, returnType, parameterTypes, accessibility, bStatic );
}
public static IRMethod createConstructorIRMethod(IType owner, IRType[] parameterTypes ) {
return new SyntheticIRMethod( owner, "<init>", IRTypeConstants.pVOID(), Arrays.asList(parameterTypes), IRelativeTypeInfo.Accessibility.PUBLIC, false );
}
private static List<IRType> convertToIRTypes(IType[] types) {
List<IRType> result = new ArrayList<IRType>();
for (IType type : types) {
result.add(IRTypeResolver.getDescriptor(type));
}
return result;
}
// private static IType getTrueOwningType( IMethodInfo mi ) {
// if( mi instanceof IJavaMethodInfo)
// {
// // We have to get the owner type from the method because it may be different from the owning type e.g., entity aspects see ContactGosuAspect.AllAdresses
// Method m = ((IJavaMethodInfo)mi).getMethod();
// if( m != null )
// {
// return TypeSystem.get( m.getDeclaringClass() );
// }
// }
// return mi.getOwnersType();
// }
//
// private static IType[] getParameterTypes( IMethodInfo mi ) {
// if ( mi instanceof IGosuMethodInfo ) {
// IDynamicFunctionSymbol dfs = ((IGosuMethodInfo)mi).getDfs();
// while( dfs instanceof ParameterizedDynamicFunctionSymbol)
// {
// ParameterizedDynamicFunctionSymbol pdfs = (ParameterizedDynamicFunctionSymbol)dfs;
// dfs = pdfs.getBackingDfs();
// }
// IType[] boundedTypes = new IType[dfs.getArgTypes().length];
// for( int i = 0; i < dfs.getArgTypes().length; i++ )
// {
// boundedTypes[i] = TypeLord.getDefaultParameterizedTypeWithTypeVars( dfs.getArgTypes()[i] );
// }
// return boundedTypes;
// } else {
// IParameterInfo[] parameterInfos = mi.getParameters();
// IType[] parameterTypes = new IType[parameterInfos.length];
// for (int i = 0; i < parameterInfos.length; i++) {
// parameterTypes[i] = parameterInfos[i].getFeatureType();
// }
// return parameterTypes;
// }
// }
}
|
gosu-lang/gosu-lang
|
gosu-core/src/main/java/gw/internal/gosu/ir/nodes/IRMethodFactory.java
|
Java
|
apache-2.0
| 4,548 |
namespace AppsAgainstHumanity.Server.UI
{
partial class expansionPackForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.saveSelectionBtn = new System.Windows.Forms.Button();
this.reloadDecksBtn = new System.Windows.Forms.Button();
this.cancelBtn = new System.Windows.Forms.Button();
this.expansionPackListBox = new System.Windows.Forms.CheckedListBox();
this.SuspendLayout();
//
// saveSelectionBtn
//
this.saveSelectionBtn.Location = new System.Drawing.Point(329, 12);
this.saveSelectionBtn.Name = "saveSelectionBtn";
this.saveSelectionBtn.Size = new System.Drawing.Size(122, 23);
this.saveSelectionBtn.TabIndex = 0;
this.saveSelectionBtn.Text = "Save Selections";
this.saveSelectionBtn.UseVisualStyleBackColor = true;
this.saveSelectionBtn.Click += new System.EventHandler(this.saveSelectionBtn_Click);
//
// reloadDecksBtn
//
this.reloadDecksBtn.Location = new System.Drawing.Point(329, 41);
this.reloadDecksBtn.Name = "reloadDecksBtn";
this.reloadDecksBtn.Size = new System.Drawing.Size(122, 23);
this.reloadDecksBtn.TabIndex = 1;
this.reloadDecksBtn.Text = "Reload Packs";
this.reloadDecksBtn.UseVisualStyleBackColor = true;
this.reloadDecksBtn.Click += new System.EventHandler(this.reloadDecksBtn_Click);
//
// cancelBtn
//
this.cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelBtn.Location = new System.Drawing.Point(329, 244);
this.cancelBtn.Name = "cancelBtn";
this.cancelBtn.Size = new System.Drawing.Size(122, 23);
this.cancelBtn.TabIndex = 3;
this.cancelBtn.Text = "Cancel";
this.cancelBtn.UseVisualStyleBackColor = true;
//
// expansionPackListBox
//
this.expansionPackListBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.expansionPackListBox.CheckOnClick = true;
this.expansionPackListBox.FormattingEnabled = true;
this.expansionPackListBox.Location = new System.Drawing.Point(12, 12);
this.expansionPackListBox.Name = "expansionPackListBox";
this.expansionPackListBox.ScrollAlwaysVisible = true;
this.expansionPackListBox.Size = new System.Drawing.Size(303, 255);
this.expansionPackListBox.TabIndex = 4;
//
// expansionPackForm
//
this.AcceptButton = this.saveSelectionBtn;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Window;
this.CancelButton = this.cancelBtn;
this.ClientSize = new System.Drawing.Size(459, 275);
this.ControlBox = false;
this.Controls.Add(this.expansionPackListBox);
this.Controls.Add(this.cancelBtn);
this.Controls.Add(this.reloadDecksBtn);
this.Controls.Add(this.saveSelectionBtn);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "expansionPackForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Select Expansion Packs";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button saveSelectionBtn;
private System.Windows.Forms.Button reloadDecksBtn;
private System.Windows.Forms.Button cancelBtn;
private System.Windows.Forms.CheckedListBox expansionPackListBox;
}
}
|
McSherry/AppsAgainstHumanity
|
Server/UI/expansionPackForm.Designer.cs
|
C#
|
apache-2.0
| 4,820 |
// Copyright (c) Keith D Gregory
//
// 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.
/**
* Constants related to Spring implementations: classnames, locations, &c.
*/
package com.kdgregory.pathfinder.spring.context;
public class SpringConstants
{
public final static String CLASS_DISPATCHER_SERVLET = "org.springframework.web.servlet.DispatcherServlet";
public final static String CLASS_CONTEXT_LISTENER = "org.springframework.web.context.ContextLoaderListener";
public final static String CLASS_SIMPLE_URL_HANDLER = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping";
public final static String CLASS_BEAN_NAME_HANDLER = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping";
public final static String CLASS_CLASS_NAME_HANDLER = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping";
public final static String INTF_CONTROLLER = "org.springframework.web.servlet.mvc.Controller";
public final static String ANNO_CONTROLLER = "org.springframework.stereotype.Controller";
public final static String ANNO_COMPONENT = "org.springframework.stereotype.Component";
public final static String ANNO_REQUEST_MAPPING = "org.springframework.web.bind.annotation.RequestMapping";
public final static String ANNO_REQUEST_PARAM = "org.springframework.web.bind.annotation.RequestParam";
}
|
kdgregory/pathfinder
|
lib-spring/src/main/java/com/kdgregory/pathfinder/spring/context/SpringConstants.java
|
Java
|
apache-2.0
| 1,960 |
package ca.corefacility.bioinformatics.irida.ria.web.exceptions;
import java.util.Map;
/**
* Used by UI to contain internationalized constraint violations.
*/
public class UIConstraintViolationException extends Exception {
private final Map<String, String> errors;
public UIConstraintViolationException(Map<String, String> errors) {
this.errors = errors;
}
public Map<String, String> getErrors() {
return errors;
}
}
|
phac-nml/irida
|
src/main/java/ca/corefacility/bioinformatics/irida/ria/web/exceptions/UIConstraintViolationException.java
|
Java
|
apache-2.0
| 432 |
/**
* Copyright 2008 - 2010
*
* 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.
*
* @project loon
* @author cping
* @email:javachenpeng@yahoo.com
* @version 0.1
*/
package loon.action.sprite.effect;
import loon.LSystem;
import loon.action.sprite.Entity;
import loon.canvas.LColor;
import loon.opengl.GLEx;
/**
* 最基础的画面淡入淡出
*/
public class FadeEffect extends Entity implements BaseEffect {
private float time;
private float currentFrame;
private int type;
private boolean finished;
private boolean autoRemoved;
public static FadeEffect create(int type, LColor c) {
return create(type, c, LSystem.viewSize.getWidth(),
LSystem.viewSize.getHeight());
}
public static FadeEffect create(int type, int timer, LColor c) {
return new FadeEffect(c, timer, type, LSystem.viewSize.getWidth(),
LSystem.viewSize.getHeight());
}
public static FadeEffect create(int type, LColor c, int w, int h) {
return new FadeEffect(c, 120, type, w, h);
}
public FadeEffect(int type, LColor c) {
this(c, 120, type, LSystem.viewSize.getWidth(), LSystem.viewSize
.getHeight());
}
public FadeEffect(LColor c, int delay, int type, int w, int h) {
this.type = type;
this.setDelay(delay);
this.setColor(c);
this.setSize(w, h);
this.setRepaint(true);
}
public float getDelay() {
return time;
}
public void setDelay(float delay) {
this.time = delay;
if (type == TYPE_FADE_IN) {
this.currentFrame = this.time;
} else {
this.currentFrame = 0;
}
}
public float getCurrentFrame() {
return currentFrame;
}
public void setCurrentFrame(float currentFrame) {
this.currentFrame = currentFrame;
}
@Override
public boolean isCompleted() {
return finished;
}
public void setStop(boolean finished) {
this.finished = finished;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public void repaint(GLEx g, float sx, float sy) {
if (finished) {
return;
}
float op = (currentFrame / time);
int old = g.color();
g.setTint(_baseColor.r, _baseColor.g, _baseColor.b, op);
g.fillRect(drawX(sx), drawY(sy), _width,
_height);
g.setTint(old);
return;
}
@Override
public void onUpdate(long timer) {
if (type == TYPE_FADE_IN) {
currentFrame--;
if (currentFrame <= 0) {
setAlpha(0);
finished = true;
}
} else {
currentFrame++;
if (currentFrame >= time) {
setAlpha(0);
finished = true;
}
}
if (this.finished) {
if (autoRemoved && getSprites() != null) {
getSprites().remove(this);
}
}
}
public int getFadeType() {
return type;
}
public boolean isAutoRemoved() {
return autoRemoved;
}
public FadeEffect setAutoRemoved(boolean autoRemoved) {
this.autoRemoved = autoRemoved;
return this;
}
@Override
public void close() {
super.close();
finished = true;
}
}
|
cping/LGame
|
Java/Loon-Neo/src/loon/action/sprite/effect/FadeEffect.java
|
Java
|
apache-2.0
| 3,402 |
'use strict';
//https://evaluat-e-api.herokuapp.com
angular.module('evaluateApp').factory('Student',function($resource,$cookieStore,$http,url_api){
var interface_api = {
resource: $resource(url_api+'api/student/:id',{id:'@id','csrf_token' :$cookieStore._csrf, page: 1 },{
update: { method:'PUT'},
delete: { method:'DELETE',
headers: {
'Content-Type': 'application/json'
},params: {id: '@id'}}
}),
http: {
getStudentsByCourse: function(id_course,page)
{
return $http({
url: url_api+'api/student_course',
method: 'GET',
params: {id_course: id_course,page: page}
});
},
saveStudentCourse: function(id_course,id_student)
{
var data = $.param({
id_course: id_course,
id_student: id_student
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
return $http.post(url_api+'api/student_course', data, config)
},
deleteStudentCourse: function(id_student,id_course)
{
return $http({
url: url_api+'api/student_course',
method: 'DELETE',
params: {id_course: id_course,id_student: id_student}
});
}
}
}
return interface_api;
});
|
IIC3143-Equipo1/angularJS
|
app/scripts/services/student.js
|
JavaScript
|
apache-2.0
| 1,586 |
/**
* Copyright (C) 2015 Fernando Cejas 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.
*/
package com.fernandocejas.android10.sample.data.cache;
import android.content.Context;
import com.fernandocejas.android10.sample.data.cache.serializer.JsonSerializer;
import com.fernandocejas.android10.sample.data.entity.UserEntity;
import com.fernandocejas.android10.sample.data.exception.UserNotFoundException;
import com.fernandocejas.android10.sample.domain.executor.ThreadExecutor;
import java.io.File;
import javax.inject.Inject;
import javax.inject.Singleton;
import rx.Observable;
/**
* {@link UserCache} implementation.
*/
@Singleton
public class UserCacheImpl implements UserCache {
private static final String SETTINGS_FILE_NAME = "com.fernandocejas.android10.SETTINGS";
private static final String SETTINGS_KEY_LAST_CACHE_UPDATE = "last_cache_update";
private static final String DEFAULT_FILE_NAME = "user_";
private static final long EXPIRATION_TIME = 60 * 10 * 1000;
private final Context context;
private final File cacheDir;
private final JsonSerializer serializer;
private final FileManager fileManager;
private final ThreadExecutor threadExecutor;
/**
* Constructor of the class {@link UserCacheImpl}.
*
* @param context A
* @param userCacheSerializer {@link JsonSerializer} for object serialization.
* @param fileManager {@link FileManager} for saving serialized objects to the file system.
*/
@Inject
public UserCacheImpl(Context context, JsonSerializer userCacheSerializer,
FileManager fileManager, ThreadExecutor executor) {
if (context == null || userCacheSerializer == null || fileManager == null || executor == null) {
throw new IllegalArgumentException("Invalid null parameter");
}
this.context = context.getApplicationContext();
this.cacheDir = this.context.getCacheDir();
this.serializer = userCacheSerializer;
this.fileManager = fileManager;
this.threadExecutor = executor;
}
@Override public Observable<UserEntity> get(final int userId) {
return Observable.create(subscriber -> {
File userEntityFile = UserCacheImpl.this.buildFile(userId);
String fileContent = UserCacheImpl.this.fileManager.readFileContent(userEntityFile);
UserEntity userEntity = UserCacheImpl.this.serializer.deserialize(fileContent,UserEntity.class);
if (userEntity != null) {
subscriber.onNext(userEntity);
subscriber.onCompleted();
} else {
subscriber.onError(new UserNotFoundException());
}
});
}
@Override public void put(UserEntity userEntity) {
if (userEntity != null) {
File userEntityFile = this.buildFile(userEntity.getUserId());
if (!isCached(userEntity.getUserId())) {
String jsonString = this.serializer.serialize(userEntity);
this.executeAsynchronously(new CacheWriter(this.fileManager, userEntityFile,
jsonString));
setLastCacheUpdateTimeMillis();
}
}
}
@Override public boolean isCached(int userId) {
File userEntitiyFile = this.buildFile(userId);
return this.fileManager.exists(userEntitiyFile);
}
@Override public boolean isExpired() {
long currentTime = System.currentTimeMillis();
long lastUpdateTime = this.getLastCacheUpdateTimeMillis();
boolean expired = ((currentTime - lastUpdateTime) > EXPIRATION_TIME);
if (expired) {
this.evictAll();
}
return expired;
}
@Override public void evictAll() {
this.executeAsynchronously(new CacheEvictor(this.fileManager, this.cacheDir));
}
/**
* Build a file, used to be inserted in the disk cache.
*
* @param userId The id user to build the file.
* @return A valid file.
*/
private File buildFile(int userId) {
StringBuilder fileNameBuilder = new StringBuilder();
fileNameBuilder.append(this.cacheDir.getPath());
fileNameBuilder.append(File.separator);
fileNameBuilder.append(DEFAULT_FILE_NAME);
fileNameBuilder.append(userId);
return new File(fileNameBuilder.toString());
}
/**
* Set in millis, the last time the cache was accessed.
*/
private void setLastCacheUpdateTimeMillis() {
long currentMillis = System.currentTimeMillis();
this.fileManager.writeToPreferences(this.context, SETTINGS_FILE_NAME,
SETTINGS_KEY_LAST_CACHE_UPDATE, currentMillis);
}
/**
* Get in millis, the last time the cache was accessed.
*/
private long getLastCacheUpdateTimeMillis() {
return this.fileManager.getFromPreferences(this.context, SETTINGS_FILE_NAME,
SETTINGS_KEY_LAST_CACHE_UPDATE);
}
/**
* Executes a {@link Runnable} in another Thread.
*
* @param runnable {@link Runnable} to execute
*/
private void executeAsynchronously(Runnable runnable) {
this.threadExecutor.execute(runnable);
}
/**
* {@link Runnable} class for writing to disk.
*/
private static class CacheWriter implements Runnable {
private final FileManager fileManager;
private final File fileToWrite;
private final String fileContent;
CacheWriter(FileManager fileManager, File fileToWrite, String fileContent) {
this.fileManager = fileManager;
this.fileToWrite = fileToWrite;
this.fileContent = fileContent;
}
@Override public void run() {
this.fileManager.writeToFile(fileToWrite, fileContent);
}
}
/**
* {@link Runnable} class for evicting all the cached files
*/
private static class CacheEvictor implements Runnable {
private final FileManager fileManager;
private final File cacheDir;
CacheEvictor(FileManager fileManager, File cacheDir) {
this.fileManager = fileManager;
this.cacheDir = cacheDir;
}
@Override public void run() {
this.fileManager.clearDirectory(this.cacheDir);
}
}
}
|
SeekingAlone/AndroidWheel
|
data/src/main/java/com/fernandocejas/android10/sample/data/cache/UserCacheImpl.java
|
Java
|
apache-2.0
| 6,364 |
package com.github.dockerjava.client.command;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Joiner;
/**
*
* @author marcus
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class TopContainerResponse {
@JsonProperty("Titles")
private String[] titles;
@JsonProperty("Processes")
private String[][] processes;
public String[] getTitles() {
return titles;
}
public String[][] getProcesses() {
return processes;
}
@Override
public String toString() {
Joiner joiner = Joiner.on("; ").skipNulls();
StringBuffer buffer = new StringBuffer();
buffer.append("[");
for(String[] fields: processes) {
buffer.append("[" + joiner.join(fields) + "]");
}
buffer.append("]");
return "TopContainerResponse{" +
"titles=" + joiner.join(titles) +
", processes=" + buffer.toString() +
'}';
}
}
|
dflemstr/docker-java
|
src/main/java/com/github/dockerjava/client/command/TopContainerResponse.java
|
Java
|
apache-2.0
| 983 |
<?php if(!defined('KIRBY')) exit ?>
# default Link
title: Link
pages: false
files: false
fields:
title:
label: Text
type: text
website:
label: Link
type: text
|
SnorMagazine/Website
|
php/site/panel/blueprints/link.php
|
PHP
|
apache-2.0
| 181 |
/**
* Copyright 2013, Big Switch Networks, 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 net.floodlightcontroller.topology;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.HAListenerTypeMarker;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IFloodlightProviderService.Role;
import net.floodlightcontroller.core.IHAListener;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.annotations.LogMessageCategory;
import net.floodlightcontroller.core.annotations.LogMessageDoc;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.module.FloodlightModuleException;
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.core.util.SingletonTask;
import net.floodlightcontroller.counter.ICounterStoreService;
import net.floodlightcontroller.debugcounter.IDebugCounter;
import net.floodlightcontroller.debugcounter.IDebugCounterService;
import net.floodlightcontroller.debugcounter.IDebugCounterService.CounterException;
import net.floodlightcontroller.debugcounter.IDebugCounterService.CounterType;
import net.floodlightcontroller.debugcounter.NullDebugCounter;
import net.floodlightcontroller.debugevent.IDebugEventService;
import net.floodlightcontroller.debugevent.IDebugEventService.EventColumn;
import net.floodlightcontroller.debugevent.IDebugEventService.EventFieldType;
import net.floodlightcontroller.debugevent.IDebugEventService.EventType;
import net.floodlightcontroller.debugevent.IDebugEventService.MaxEventsRegistered;
import net.floodlightcontroller.debugevent.IEventUpdater;
import net.floodlightcontroller.debugevent.NullDebugEvent;
import net.floodlightcontroller.linkdiscovery.ILinkDiscoveryListener;
//import net.floodlightcontroller.linkdiscovery.ILinkDiscoveryService;
import net.floodlightcontroller.packet.BSN;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.LLDP;
import net.floodlightcontroller.restserver.IRestApiService;
import net.floodlightcontroller.routing.IRoutingService;
import net.floodlightcontroller.routing.Link;
import net.floodlightcontroller.routing.Route;
import net.floodlightcontroller.threadpool.IThreadPoolService;
import net.floodlightcontroller.topology.web.TopologyWebRoutable;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFPacketIn;
import org.openflow.protocol.OFPacketOut;
import org.openflow.protocol.OFPort;
import org.openflow.protocol.OFType;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//Yikai
import edu.linkdiscovery.F3LinkDiscoveryService;
/**
* Topology manager is responsible for maintaining the controller's notion
* of the network graph, as well as implementing tools for finding routes
* through the topology.
*/
@LogMessageCategory("Network Topology")
public class TopologyManager implements
IFloodlightModule, ITopologyService,
IRoutingService, ILinkDiscoveryListener,
IOFMessageListener {
protected static Logger log = LoggerFactory.getLogger(TopologyManager.class);
public static final String MODULE_NAME = "topology";
public static final String CONTEXT_TUNNEL_ENABLED =
"com.bigswitch.floodlight.topologymanager.tunnelEnabled";
/**
* Role of the controller.
*/
private Role role;
/**
* Set of ports for each switch
*/
protected Map<Long, Set<Integer>> switchPorts;
/**
* Set of links organized by node port tuple
*/
protected Map<NodePortTuple, Set<Link>> switchPortLinks;
/**
* Set of direct links
*/
protected Map<NodePortTuple, Set<Link>> directLinks;
/**
* set of links that are broadcast domain links.
*/
protected Map<NodePortTuple, Set<Link>> portBroadcastDomainLinks;
/**
* set of tunnel links
*/
protected Set<NodePortTuple> tunnelPorts;
//Yikai
protected F3LinkDiscoveryService linkDiscovery;
protected IThreadPoolService threadPool;
protected IFloodlightProviderService floodlightProvider;
protected IRestApiService restApi;
protected IDebugCounterService debugCounters;
// Modules that listen to our updates
protected ArrayList<ITopologyListener> topologyAware;
protected BlockingQueue<LDUpdate> ldUpdates;
// These must be accessed using getCurrentInstance(), not directly
protected TopologyInstance currentInstance;
protected TopologyInstance currentInstanceWithoutTunnels;
protected SingletonTask newInstanceTask;
private Date lastUpdateTime;
/**
* Flag that indicates if links (direct/tunnel/multihop links) were
* updated as part of LDUpdate.
*/
protected boolean linksUpdated;
/**
* Flag that indicates if direct or tunnel links were updated as
* part of LDUpdate.
*/
protected boolean dtLinksUpdated;
/** Flag that indicates if tunnel ports were updated or not
*/
protected boolean tunnelPortsUpdated;
protected int TOPOLOGY_COMPUTE_INTERVAL_MS = 500;
private IHAListener haListener;
/**
* Debug Counters
*/
protected static final String PACKAGE = TopologyManager.class.getPackage().getName();
protected IDebugCounter ctrIncoming;
/**
* Debug Events
*/
protected IDebugEventService debugEvents;
/*
* Topology Event Updater
*/
protected IEventUpdater<TopologyEvent> evTopology;
/**
* Topology Information exposed for a Topology related event - used inside
* the BigTopologyEvent class
*/
protected class TopologyEventInfo {
private final int numOpenflowClustersWithTunnels;
private final int numOpenflowClustersWithoutTunnels;
private final Map<Long, List<NodePortTuple>> externalPortsMap;
private final int numTunnelPorts;
public TopologyEventInfo(int numOpenflowClustersWithTunnels,
int numOpenflowClustersWithoutTunnels,
Map<Long, List<NodePortTuple>> externalPortsMap,
int numTunnelPorts) {
super();
this.numOpenflowClustersWithTunnels = numOpenflowClustersWithTunnels;
this.numOpenflowClustersWithoutTunnels = numOpenflowClustersWithoutTunnels;
this.externalPortsMap = externalPortsMap;
this.numTunnelPorts = numTunnelPorts;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("# Openflow Clusters:");
builder.append(" { With Tunnels: ");
builder.append(numOpenflowClustersWithTunnels);
builder.append(" Without Tunnels: ");
builder.append(numOpenflowClustersWithoutTunnels);
builder.append(" }");
builder.append(", # External Clusters: ");
int numExternalClusters = externalPortsMap.size();
builder.append(numExternalClusters);
if (numExternalClusters > 0) {
builder.append(" { ");
int count = 0;
for (Long extCluster : externalPortsMap.keySet()) {
builder.append("#" + extCluster + ":Ext Ports: ");
builder.append(externalPortsMap.get(extCluster).size());
if (++count < numExternalClusters) {
builder.append(", ");
} else {
builder.append(" ");
}
}
builder.append("}");
}
builder.append(", # Tunnel Ports: ");
builder.append(numTunnelPorts);
return builder.toString();
}
}
/**
* Topology Event class to track topology related events
*/
protected class TopologyEvent {
@EventColumn(name = "Reason", description = EventFieldType.STRING)
private final String reason;
@EventColumn(name = "Topology Summary")
private final TopologyEventInfo topologyInfo;
public TopologyEvent(String reason,
TopologyEventInfo topologyInfo) {
super();
this.reason = reason;
this.topologyInfo = topologyInfo;
}
}
// Getter/Setter methods
/**
* Get the time interval for the period topology updates, if any.
* The time returned is in milliseconds.
* @return
*/
public int getTopologyComputeInterval() {
return TOPOLOGY_COMPUTE_INTERVAL_MS;
}
/**
* Set the time interval for the period topology updates, if any.
* The time is in milliseconds.
* @return
*/
public void setTopologyComputeInterval(int time_ms) {
TOPOLOGY_COMPUTE_INTERVAL_MS = time_ms;
}
/**
* Thread for recomputing topology. The thread is always running,
* however the function applyUpdates() has a blocking call.
*/
@LogMessageDoc(level="ERROR",
message="Error in topology instance task thread",
explanation="An unknown error occured in the topology " +
"discovery module.",
recommendation=LogMessageDoc.CHECK_CONTROLLER)
protected class UpdateTopologyWorker implements Runnable {
@Override
public void run() {
try {
if (ldUpdates.peek() != null)
updateTopology();
handleMiscellaneousPeriodicEvents();
}
catch (Exception e) {
log.error("Error in topology instance task thread", e);
} finally {
if (floodlightProvider.getRole() != Role.SLAVE)
newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS,
TimeUnit.MILLISECONDS);
}
}
}
// To be used for adding any periodic events that's required by topology.
protected void handleMiscellaneousPeriodicEvents() {
return;
}
public boolean updateTopology() {
boolean newInstanceFlag;
linksUpdated = false;
dtLinksUpdated = false;
tunnelPortsUpdated = false;
List<LDUpdate> appliedUpdates = applyUpdates();
newInstanceFlag = createNewInstance("link-discovery-updates");
lastUpdateTime = new Date();
informListeners(appliedUpdates);
return newInstanceFlag;
}
// **********************
// ILinkDiscoveryListener
// **********************
@Override
public void linkDiscoveryUpdate(List<LDUpdate> updateList) {
if (log.isTraceEnabled()) {
log.trace("Queuing update: {}", updateList);
}
ldUpdates.addAll(updateList);
}
@Override
public void linkDiscoveryUpdate(LDUpdate update) {
if (log.isTraceEnabled()) {
log.trace("Queuing update: {}", update);
}
ldUpdates.add(update);
}
// ****************
// ITopologyService
// ****************
//
// ITopologyService interface methods
//
@Override
public Date getLastUpdateTime() {
return lastUpdateTime;
}
@Override
public void addListener(ITopologyListener listener) {
topologyAware.add(listener);
}
@Override
public boolean isAttachmentPointPort(long switchid, int port) {
return isAttachmentPointPort(switchid, port, true);
}
@Override
public boolean isAttachmentPointPort(long switchid, int port,
boolean tunnelEnabled) {
// If the switch port is 'tun-bsn' port, it is not
// an attachment point port, irrespective of whether
// a link is found through it or not.
if (linkDiscovery.isTunnelPort(switchid, port))
return false;
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
// if the port is not attachment point port according to
// topology instance, then return false
if (ti.isAttachmentPointPort(switchid, port) == false)
return false;
// Check whether the port is a physical port. We should not learn
// attachment points on "special" ports.
if ((port & 0xff00) == 0xff00 && port != (short)0xfffe) return false;
// Make sure that the port is enabled.
IOFSwitch sw = floodlightProvider.getSwitch(switchid);
if (sw == null) return false;
return (sw.portEnabled(port));
}
@Override
public long getOpenflowDomainId(long switchId) {
return getOpenflowDomainId(switchId, true);
}
@Override
public long getOpenflowDomainId(long switchId, boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getOpenflowDomainId(switchId);
}
@Override
public long getL2DomainId(long switchId) {
return getL2DomainId(switchId, true);
}
@Override
public long getL2DomainId(long switchId, boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getL2DomainId(switchId);
}
@Override
public boolean inSameOpenflowDomain(long switch1, long switch2) {
return inSameOpenflowDomain(switch1, switch2, true);
}
@Override
public boolean inSameOpenflowDomain(long switch1, long switch2,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.inSameOpenflowDomain(switch1, switch2);
}
@Override
public boolean isAllowed(long sw, int portId) {
return isAllowed(sw, portId, true);
}
@Override
public boolean isAllowed(long sw, int portId, boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.isAllowed(sw, portId);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
@Override
public boolean isIncomingBroadcastAllowed(long sw, int portId) {
return isIncomingBroadcastAllowed(sw, portId, true);
}
@Override
public boolean isIncomingBroadcastAllowed(long sw, int portId,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.isIncomingBroadcastAllowedOnSwitchPort(sw, portId);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/** Get all the ports connected to the switch */
@Override
public Set<Integer> getPortsWithLinks(long sw) {
return getPortsWithLinks(sw, true);
}
/** Get all the ports connected to the switch */
@Override
public Set<Integer> getPortsWithLinks(long sw, boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getPortsWithLinks(sw);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/** Get all the ports on the target switch (targetSw) on which a
* broadcast packet must be sent from a host whose attachment point
* is on switch port (src, srcPort).
*/
@Override
public Set<Integer> getBroadcastPorts(long targetSw,
long src, int srcPort) {
return getBroadcastPorts(targetSw, src, srcPort, true);
}
/** Get all the ports on the target switch (targetSw) on which a
* broadcast packet must be sent from a host whose attachment point
* is on switch port (src, srcPort).
*/
@Override
public Set<Integer> getBroadcastPorts(long targetSw,
long src, int srcPort,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getBroadcastPorts(targetSw, src, srcPort);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
@Override
public NodePortTuple getOutgoingSwitchPort(long src, int srcPort,
long dst, int dstPort) {
// Use this function to redirect traffic if needed.
return getOutgoingSwitchPort(src, srcPort, dst, dstPort, true);
}
@Override
public NodePortTuple getOutgoingSwitchPort(long src, int srcPort,
long dst, int dstPort,
boolean tunnelEnabled) {
// Use this function to redirect traffic if needed.
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getOutgoingSwitchPort(src, srcPort,
dst, dstPort);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
@Override
public NodePortTuple getIncomingSwitchPort(long src, int srcPort,
long dst, int dstPort) {
return getIncomingSwitchPort(src, srcPort, dst, dstPort, true);
}
@Override
public NodePortTuple getIncomingSwitchPort(long src, int srcPort,
long dst, int dstPort,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getIncomingSwitchPort(src, srcPort,
dst, dstPort);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/**
* Checks if the two switchports belong to the same broadcast domain.
*/
@Override
public boolean isInSameBroadcastDomain(long s1, int p1, long s2,
int p2) {
return isInSameBroadcastDomain(s1, p1, s2, p2, true);
}
@Override
public boolean isInSameBroadcastDomain(long s1, int p1,
long s2, int p2,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.inSameBroadcastDomain(s1, p1, s2, p2);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/**
* Checks if the switchport is a broadcast domain port or not.
*/
@Override
public boolean isBroadcastDomainPort(long sw, int port) {
return isBroadcastDomainPort(sw, port, true);
}
@Override
public boolean isBroadcastDomainPort(long sw, int port,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.isBroadcastDomainPort(new NodePortTuple(sw, port));
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/**
* Checks if the new attachment point port is consistent with the
* old attachment point port.
*/
@Override
public boolean isConsistent(long oldSw, int oldPort,
long newSw, int newPort) {
return isConsistent(oldSw, oldPort,
newSw, newPort, true);
}
@Override
public boolean isConsistent(long oldSw, int oldPort,
long newSw, int newPort,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.isConsistent(oldSw, oldPort, newSw, newPort);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/**
* Checks if the two switches are in the same Layer 2 domain.
*/
@Override
public boolean inSameL2Domain(long switch1, long switch2) {
return inSameL2Domain(switch1, switch2, true);
}
@Override
public boolean inSameL2Domain(long switch1, long switch2,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.inSameL2Domain(switch1, switch2);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
@Override
public NodePortTuple getAllowedOutgoingBroadcastPort(long src,
int srcPort,
long dst,
int dstPort) {
return getAllowedOutgoingBroadcastPort(src, srcPort,
dst, dstPort, true);
}
@Override
public NodePortTuple getAllowedOutgoingBroadcastPort(long src,
int srcPort,
long dst,
int dstPort,
boolean tunnelEnabled){
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getAllowedOutgoingBroadcastPort(src, srcPort,
dst, dstPort);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
@Override
public NodePortTuple
getAllowedIncomingBroadcastPort(long src, int srcPort) {
return getAllowedIncomingBroadcastPort(src,srcPort, true);
}
@Override
public NodePortTuple
getAllowedIncomingBroadcastPort(long src, int srcPort,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getAllowedIncomingBroadcastPort(src,srcPort);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
@Override
public Set<Long> getSwitchesInOpenflowDomain(long switchDPID) {
return getSwitchesInOpenflowDomain(switchDPID, true);
}
@Override
public Set<Long> getSwitchesInOpenflowDomain(long switchDPID,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getSwitchesInOpenflowDomain(switchDPID);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
@Override
public Set<NodePortTuple> getBroadcastDomainPorts() {
return portBroadcastDomainLinks.keySet();
}
@Override
public Set<NodePortTuple> getTunnelPorts() {
return tunnelPorts;
}
@Override
public Set<NodePortTuple> getBlockedPorts() {
Set<NodePortTuple> bp;
Set<NodePortTuple> blockedPorts =
new HashSet<NodePortTuple>();
// As we might have two topologies, simply get the union of
// both of them and send it.
bp = getCurrentInstance(true).getBlockedPorts();
if (bp != null)
blockedPorts.addAll(bp);
bp = getCurrentInstance(false).getBlockedPorts();
if (bp != null)
blockedPorts.addAll(bp);
return blockedPorts;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// ***************
// IRoutingService
// ***************
@Override
public Route getRoute(long src, long dst, long cookie) {
return getRoute(src, dst, cookie, true);
}
@Override
public Route getRoute(long src, long dst, long cookie, boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getRoute(src, dst, cookie);
}
@Override
public Route getRoute(long src, int srcPort, long dst, int dstPort, long cookie) {
return getRoute(src, srcPort, dst, dstPort, cookie, true);
}
@Override
public Route getRoute(long src, int srcPort, long dst, int dstPort, long cookie,
boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.getRoute(null, src, srcPort, dst, dstPort, cookie);
}
@Override
public boolean routeExists(long src, long dst) {
return routeExists(src, dst, true);
}
@Override
public boolean routeExists(long src, long dst, boolean tunnelEnabled) {
TopologyInstance ti = getCurrentInstance(tunnelEnabled);
return ti.routeExists(src, dst);
}
@Override
public ArrayList<Route> getRoutes(long srcDpid, long dstDpid,
boolean tunnelEnabled) {
// Floodlight supports single path routing now
// return single path now
ArrayList<Route> result=new ArrayList<Route>();
result.add(getRoute(srcDpid, dstDpid, 0, tunnelEnabled));
return result;
}
// ******************
// IOFMessageListener
// ******************
@Override
public String getName() {
return MODULE_NAME;
}
//Yikai
@Override
public boolean isCallbackOrderingPrereq(OFType type, String name) {
return "f3linkdiscovery".equals(name);
}
@Override
public boolean isCallbackOrderingPostreq(OFType type, String name) {
return false;
}
@Override
public Command receive(IOFSwitch sw, OFMessage msg,
FloodlightContext cntx) {
switch (msg.getType()) {
case PACKET_IN:
ctrIncoming.updateCounterNoFlush();
return this.processPacketInMessage(sw,
(OFPacketIn) msg, cntx);
default:
break;
}
return Command.CONTINUE;
}
// ***************
// IHAListener
// ***************
private class HAListenerDelegate implements IHAListener {
@Override
public void transitionToMaster() {
role = Role.MASTER;
log.debug("Re-computing topology due " +
"to HA change from SLAVE->MASTER");
newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS,
TimeUnit.MILLISECONDS);
}
@Override
public void controllerNodeIPsChanged(
Map<String, String> curControllerNodeIPs,
Map<String, String> addedControllerNodeIPs,
Map<String, String> removedControllerNodeIPs) {
// no-op
}
@Override
public String getName() {
return TopologyManager.this.getName();
}
//Yikai
@Override
public boolean isCallbackOrderingPrereq(HAListenerTypeMarker type,
String name) {
return "f3linkdiscovery".equals(name) ||
"tunnelmanager".equals(name);
}
@Override
public boolean isCallbackOrderingPostreq(HAListenerTypeMarker type,
String name) {
// TODO Auto-generated method stub
return false;
}
}
// *****************
// IFloodlightModule
// *****************
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
l.add(ITopologyService.class);
l.add(IRoutingService.class);
return l;
}
@Override
public Map<Class<? extends IFloodlightService>, IFloodlightService>
getServiceImpls() {
Map<Class<? extends IFloodlightService>,
IFloodlightService> m =
new HashMap<Class<? extends IFloodlightService>,
IFloodlightService>();
// We are the class that implements the service
m.put(ITopologyService.class, this);
m.put(IRoutingService.class, this);
return m;
}
@Override
public Collection<Class<? extends IFloodlightService>>
getModuleDependencies() {
Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
//Yikai
l.add(F3LinkDiscoveryService.class);
l.add(IThreadPoolService.class);
l.add(IFloodlightProviderService.class);
l.add(ICounterStoreService.class);
l.add(IRestApiService.class);
return l;
}
@Override
public void init(FloodlightModuleContext context)
throws FloodlightModuleException {
//Yikai
linkDiscovery = context.getServiceImpl(F3LinkDiscoveryService.class);
threadPool = context.getServiceImpl(IThreadPoolService.class);
floodlightProvider =
context.getServiceImpl(IFloodlightProviderService.class);
restApi = context.getServiceImpl(IRestApiService.class);
debugCounters = context.getServiceImpl(IDebugCounterService.class);
debugEvents = context.getServiceImpl(IDebugEventService.class);
switchPorts = new HashMap<Long,Set<Integer>>();
switchPortLinks = new HashMap<NodePortTuple, Set<Link>>();
directLinks = new HashMap<NodePortTuple, Set<Link>>();
portBroadcastDomainLinks = new HashMap<NodePortTuple, Set<Link>>();
tunnelPorts = new HashSet<NodePortTuple>();
topologyAware = new ArrayList<ITopologyListener>();
ldUpdates = new LinkedBlockingQueue<LDUpdate>();
haListener = new HAListenerDelegate();
registerTopologyDebugCounters();
registerTopologyDebugEvents();
}
protected void registerTopologyDebugEvents() throws FloodlightModuleException {
if (debugEvents == null) {
debugEvents = new NullDebugEvent();
}
try {
evTopology =
debugEvents.registerEvent(PACKAGE, "topologyevent",
"Topology Computation",
EventType.ALWAYS_LOG,
TopologyEvent.class, 100);
} catch (MaxEventsRegistered e) {
throw new FloodlightModuleException("Max events registered", e);
}
}
@Override
public void startUp(FloodlightModuleContext context) {
clearCurrentTopology();
// Initialize role to floodlight provider role.
this.role = floodlightProvider.getRole();
ScheduledExecutorService ses = threadPool.getScheduledExecutor();
newInstanceTask = new SingletonTask(ses, new UpdateTopologyWorker());
if (role != Role.SLAVE)
newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS,
TimeUnit.MILLISECONDS);
linkDiscovery.addListener(this);
floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
floodlightProvider.addHAListener(this.haListener);
addRestletRoutable();
}
private void registerTopologyDebugCounters() throws FloodlightModuleException {
if (debugCounters == null) {
log.error("Debug Counter Service not found.");
debugCounters = new NullDebugCounter();
}
try {
ctrIncoming = debugCounters.registerCounter(PACKAGE, "incoming",
"All incoming packets seen by this module",
CounterType.ALWAYS_COUNT);
} catch (CounterException e) {
throw new FloodlightModuleException(e.getMessage());
}
}
protected void addRestletRoutable() {
restApi.addRestletRoutable(new TopologyWebRoutable());
}
// ****************
// Internal methods
// ****************
/**
* If the packet-in switch port is disabled for all data traffic, then
* the packet will be dropped. Otherwise, the packet will follow the
* normal processing chain.
* @param sw
* @param pi
* @param cntx
* @return
*/
protected Command dropFilter(long sw, OFPacketIn pi,
FloodlightContext cntx) {
Command result = Command.CONTINUE;
int port = pi.getInPort();
// If the input port is not allowed for data traffic, drop everything.
// BDDP packets will not reach this stage.
if (isAllowed(sw, port) == false) {
if (log.isTraceEnabled()) {
log.trace("Ignoring packet because of topology " +
"restriction on switch={}, port={}", sw, port);
result = Command.STOP;
}
}
return result;
}
/**
* TODO This method must be moved to a layer below forwarding
* so that anyone can use it.
* @param packetData
* @param sw
* @param ports
* @param cntx
*/
@LogMessageDoc(level="ERROR",
message="Failed to clear all flows on switch {switch}",
explanation="An I/O error occured while trying send " +
"topology discovery packet",
recommendation=LogMessageDoc.CHECK_SWITCH)
public void doMultiActionPacketOut(byte[] packetData, IOFSwitch sw,
Set<Integer> ports,
FloodlightContext cntx) {
if (ports == null) return;
if (packetData == null || packetData.length <= 0) return;
OFPacketOut po =
(OFPacketOut) floodlightProvider.getOFMessageFactory().
getMessage(OFType.PACKET_OUT);
List<OFAction> actions = new ArrayList<OFAction>();
for(int p: ports) {
actions.add(new OFActionOutput(p, (short) 0));
}
// set actions
po.setActions(actions);
// set action length
po.setActionsLength((short) (OFActionOutput.MINIMUM_LENGTH *
ports.size()));
// set buffer-id to BUFFER_ID_NONE
po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
// set in-port to OFPP_ANY
po.setInPort(OFPort.OFPP_ANY.getValue());
// set packet data
po.setPacketData(packetData);
// compute and set packet length.
short poLength = (short)(OFPacketOut.MINIMUM_LENGTH +
po.getActionsLength() +
packetData.length);
po.setLength(poLength);
try {
//counterStore.updatePktOutFMCounterStore(sw, po);
if (log.isTraceEnabled()) {
log.trace("write broadcast packet on switch-id={} " +
"interaces={} packet-data={} packet-out={}",
new Object[] {sw.getId(), ports, packetData, po});
}
sw.write(po, cntx);
} catch (IOException e) {
log.error("Failure writing packet out", e);
}
}
/**
* Get the set of ports to eliminate for sending out BDDP. The method
* returns all the ports that are suppressed for link discovery on the
* switch.
* packets.
* @param sid
* @return
*/
protected Set<Integer> getPortsToEliminateForBDDP(long sid) {
Set<NodePortTuple> suppressedNptList = linkDiscovery.getSuppressLLDPsInfo();
if (suppressedNptList == null) return null;
Set<Integer> resultPorts = new HashSet<Integer>();
for(NodePortTuple npt: suppressedNptList) {
if (npt.getNodeId() == sid) {
resultPorts.add(npt.getPortId());
}
}
return resultPorts;
}
/**
* The BDDP packets are forwarded out of all the ports out of an
* openflowdomain. Get all the switches in the same openflow
* domain as the sw (disabling tunnels). Then get all the
* external switch ports and send these packets out.
* @param sw
* @param pi
* @param cntx
*/
protected void doFloodBDDP(long pinSwitch, OFPacketIn pi,
FloodlightContext cntx) {
TopologyInstance ti = getCurrentInstance(false);
Set<Long> switches = ti.getSwitchesInOpenflowDomain(pinSwitch);
if (switches == null)
{
// indicates no links are connected to the switches
switches = new HashSet<Long>();
switches.add(pinSwitch);
}
for(long sid: switches) {
IOFSwitch sw = floodlightProvider.getSwitch(sid);
if (sw == null) continue;
Collection<Integer> enabledPorts = sw.getEnabledPortNumbers();
if (enabledPorts == null)
continue;
Set<Integer> ports = new HashSet<Integer>();
ports.addAll(enabledPorts);
// all the ports known to topology // without tunnels.
// out of these, we need to choose only those that are
// broadcast port, otherwise, we should eliminate.
Set<Integer> portsKnownToTopo = ti.getPortsWithLinks(sid);
if (portsKnownToTopo != null) {
for(int p: portsKnownToTopo) {
NodePortTuple npt =
new NodePortTuple(sid, p);
if (ti.isBroadcastDomainPort(npt) == false) {
ports.remove(p);
}
}
}
Set<Integer> portsToEliminate = getPortsToEliminateForBDDP(sid);
if (portsToEliminate != null) {
ports.removeAll(portsToEliminate);
}
// remove the incoming switch port
if (pinSwitch == sid) {
ports.remove(pi.getInPort());
}
// we have all the switch ports to which we need to broadcast.
doMultiActionPacketOut(pi.getPacketData(), sw, ports, cntx);
}
}
protected Command processPacketInMessage(IOFSwitch sw, OFPacketIn pi,
FloodlightContext cntx) {
// get the packet-in switch.
Ethernet eth =
IFloodlightProviderService.bcStore.
get(cntx,IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
if (eth.getPayload() instanceof BSN) {
BSN bsn = (BSN) eth.getPayload();
if (bsn == null) return Command.STOP;
if (bsn.getPayload() == null) return Command.STOP;
// It could be a packet other than BSN LLDP, therefore
// continue with the regular processing.
if (bsn.getPayload() instanceof LLDP == false)
return Command.CONTINUE;
doFloodBDDP(sw.getId(), pi, cntx);
return Command.STOP;
} else {
return dropFilter(sw.getId(), pi, cntx);
}
}
/**
* Updates concerning switch disconnect and port down are not processed.
* LinkDiscoveryManager is expected to process those messages and send
* multiple link removed messages. However, all the updates from
* LinkDiscoveryManager would be propagated to the listeners of topology.
*/
@LogMessageDoc(level="ERROR",
message="Error reading link discovery update.",
explanation="Unable to process link discovery update",
recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG)
public List<LDUpdate> applyUpdates() {
List<LDUpdate> appliedUpdates = new ArrayList<LDUpdate>();
LDUpdate update = null;
while (ldUpdates.peek() != null) {
try {
update = ldUpdates.take();
} catch (Exception e) {
log.error("Error reading link discovery update.", e);
}
if (log.isTraceEnabled()) {
log.trace("Applying update: {}", update);
}
System.out.println("in topology manager: "+update);
switch (update.getOperation()) {
case LINK_UPDATED:
addOrUpdateLink(update.getSrc(), update.getSrcPort(),
update.getDst(), update.getDstPort(),
update.getType());
break;
case LINK_REMOVED:
removeLink(update.getSrc(), update.getSrcPort(),
update.getDst(), update.getDstPort());
break;
case SWITCH_UPDATED:
addOrUpdateSwitch(update.getSrc());
break;
case SWITCH_REMOVED:
removeSwitch(update.getSrc());
break;
case TUNNEL_PORT_ADDED:
addTunnelPort(update.getSrc(), update.getSrcPort());
break;
case TUNNEL_PORT_REMOVED:
removeTunnelPort(update.getSrc(), update.getSrcPort());
break;
case PORT_UP: case PORT_DOWN:
break;
}
// Add to the list of applied updates.
appliedUpdates.add(update);
}
//Yikai Lin (hilarious0401@gmail.com)
Map<NodePortTuple, Set<Link>> switchPortLinks = this.getSwitchPortLinks();
for(NodePortTuple tuple:switchPortLinks.keySet()) {
System.out.println(tuple+" -> "+switchPortLinks.get(tuple));
}
return (Collections.unmodifiableList(appliedUpdates));
}
protected void addOrUpdateSwitch(long sw) {
// nothing to do here for the time being.
return;
}
public void addTunnelPort(long sw, int port) {
NodePortTuple npt = new NodePortTuple(sw, port);
tunnelPorts.add(npt);
tunnelPortsUpdated = true;
}
public void removeTunnelPort(long sw, int port) {
NodePortTuple npt = new NodePortTuple(sw, port);
tunnelPorts.remove(npt);
tunnelPortsUpdated = true;
}
public boolean createNewInstance() {
return createNewInstance("internal");
}
/**
* This function computes a new topology instance.
* It ignores links connected to all broadcast domain ports
* and tunnel ports. The method returns if a new instance of
* topology was created or not.
*/
protected boolean createNewInstance(String reason) {
Set<NodePortTuple> blockedPorts = new HashSet<NodePortTuple>();
if (!linksUpdated) return false;
Map<NodePortTuple, Set<Link>> openflowLinks;
openflowLinks =
new HashMap<NodePortTuple, Set<Link>>();
Set<NodePortTuple> nptList = switchPortLinks.keySet();
if (nptList != null) {
for(NodePortTuple npt: nptList) {
Set<Link> linkSet = switchPortLinks.get(npt);
if (linkSet == null) continue;
openflowLinks.put(npt, new HashSet<Link>(linkSet));
}
}
// Identify all broadcast domain ports.
// Mark any port that has inconsistent set of links
// as broadcast domain ports as well.
Set<NodePortTuple> broadcastDomainPorts =
identifyBroadcastDomainPorts();
// Remove all links incident on broadcast domain ports.
for(NodePortTuple npt: broadcastDomainPorts) {
if (switchPortLinks.get(npt) == null) continue;
for(Link link: switchPortLinks.get(npt)) {
removeLinkFromStructure(openflowLinks, link);
}
}
// Remove all tunnel links.
for(NodePortTuple npt: tunnelPorts) {
if (switchPortLinks.get(npt) == null) continue;
for(Link link: switchPortLinks.get(npt)) {
removeLinkFromStructure(openflowLinks, link);
}
}
TopologyInstance nt = new TopologyInstance(switchPorts,
blockedPorts,
openflowLinks,
broadcastDomainPorts,
tunnelPorts);
nt.compute();
// We set the instances with and without tunnels to be identical.
// If needed, we may compute them differently.
currentInstance = nt;
currentInstanceWithoutTunnels = nt;
TopologyEventInfo topologyInfo =
new TopologyEventInfo(0, nt.getClusters().size(),
new HashMap<Long, List<NodePortTuple>>(),
0);
evTopology.updateEventWithFlush(new TopologyEvent(reason,
topologyInfo));
return true;
}
/**
* We expect every switch port to have at most two links. Both these
* links must be unidirectional links connecting to the same switch port.
* If not, we will mark this as a broadcast domain port.
*/
protected Set<NodePortTuple> identifyBroadcastDomainPorts() {
Set<NodePortTuple> broadcastDomainPorts =
new HashSet<NodePortTuple>();
broadcastDomainPorts.addAll(this.portBroadcastDomainLinks.keySet());
Set<NodePortTuple> additionalNpt =
new HashSet<NodePortTuple>();
// Copy switchPortLinks
Map<NodePortTuple, Set<Link>> spLinks =
new HashMap<NodePortTuple, Set<Link>>();
for(NodePortTuple npt: switchPortLinks.keySet()) {
spLinks.put(npt, new HashSet<Link>(switchPortLinks.get(npt)));
}
for(NodePortTuple npt: spLinks.keySet()) {
Set<Link> links = spLinks.get(npt);
boolean bdPort = false;
ArrayList<Link> linkArray = new ArrayList<Link>();
if (links.size() > 2) {
bdPort = true;
} else if (links.size() == 2) {
for(Link l: links) {
linkArray.add(l);
}
// now, there should be two links in [0] and [1].
Link l1 = linkArray.get(0);
Link l2 = linkArray.get(1);
// check if these two are symmetric.
if (l1.getSrc() != l2.getDst() ||
l1.getSrcPort() != l2.getDstPort() ||
l1.getDst() != l2.getSrc() ||
l1.getDstPort() != l2.getSrcPort()) {
bdPort = true;
}
}
if (bdPort && (broadcastDomainPorts.contains(npt) == false)) {
additionalNpt.add(npt);
}
}
if (additionalNpt.size() > 0) {
log.warn("The following switch ports have multiple " +
"links incident on them, so these ports will be treated " +
" as braodcast domain ports. {}", additionalNpt);
broadcastDomainPorts.addAll(additionalNpt);
}
return broadcastDomainPorts;
}
public void informListeners(List<LDUpdate> linkUpdates) {
if (role != null && role != Role.MASTER)
return;
for(int i=0; i<topologyAware.size(); ++i) {
ITopologyListener listener = topologyAware.get(i);
listener.topologyChanged(linkUpdates);
}
}
public void addSwitch(long sid) {
if (switchPorts.containsKey(sid) == false) {
switchPorts.put(sid, new HashSet<Integer>());
}
}
private void addPortToSwitch(long s, int p) {
addSwitch(s);
switchPorts.get(s).add(p);
}
public void removeSwitch(long sid) {
// Delete all the links in the switch, switch and all
// associated data should be deleted.
if (switchPorts.containsKey(sid) == false) return;
// Check if any tunnel ports need to be removed.
for(NodePortTuple npt: tunnelPorts) {
if (npt.getNodeId() == sid) {
removeTunnelPort(npt.getNodeId(), npt.getPortId());
}
}
Set<Link> linksToRemove = new HashSet<Link>();
for(Integer p: switchPorts.get(sid)) {
NodePortTuple n1 = new NodePortTuple(sid, p);
linksToRemove.addAll(switchPortLinks.get(n1));
}
if (linksToRemove.isEmpty()) return;
for(Link link: linksToRemove) {
removeLink(link);
}
}
/**
* Add the given link to the data structure. Returns true if a link was
* added.
* @param s
* @param l
* @return
*/
private boolean addLinkToStructure(Map<NodePortTuple,
Set<Link>> s, Link l) {
boolean result1 = false, result2 = false;
NodePortTuple n1 = new NodePortTuple(l.getSrc(), l.getSrcPort());
NodePortTuple n2 = new NodePortTuple(l.getDst(), l.getDstPort());
if (s.get(n1) == null) {
s.put(n1, new HashSet<Link>());
}
if (s.get(n2) == null) {
s.put(n2, new HashSet<Link>());
}
result1 = s.get(n1).add(l);
result2 = s.get(n2).add(l);
return (result1 || result2);
}
/**
* Delete the given link from the data strucure. Returns true if the
* link was deleted.
* @param s
* @param l
* @return
*/
private boolean removeLinkFromStructure(Map<NodePortTuple,
Set<Link>> s, Link l) {
boolean result1 = false, result2 = false;
NodePortTuple n1 = new NodePortTuple(l.getSrc(), l.getSrcPort());
NodePortTuple n2 = new NodePortTuple(l.getDst(), l.getDstPort());
if (s.get(n1) != null) {
result1 = s.get(n1).remove(l);
if (s.get(n1).isEmpty()) s.remove(n1);
}
if (s.get(n2) != null) {
result2 = s.get(n2).remove(l);
if (s.get(n2).isEmpty()) s.remove(n2);
}
return result1 || result2;
}
protected void addOrUpdateTunnelLink(long srcId, int srcPort, long dstId,
int dstPort) {
// If you need to handle tunnel links, this is a placeholder.
}
public void addOrUpdateLink(long srcId, int srcPort, long dstId,
int dstPort, LinkType type) {
Link link = new Link(srcId, srcPort, dstId, dstPort);
if (type.equals(LinkType.MULTIHOP_LINK)) {
addPortToSwitch(srcId, srcPort);
addPortToSwitch(dstId, dstPort);
addLinkToStructure(switchPortLinks, link);
addLinkToStructure(portBroadcastDomainLinks, link);
dtLinksUpdated = removeLinkFromStructure(directLinks, link);
linksUpdated = true;
} else if (type.equals(LinkType.DIRECT_LINK)) {
addPortToSwitch(srcId, srcPort);
addPortToSwitch(dstId, dstPort);
addLinkToStructure(switchPortLinks, link);
addLinkToStructure(directLinks, link);
removeLinkFromStructure(portBroadcastDomainLinks, link);
dtLinksUpdated = true;
linksUpdated = true;
} else if (type.equals(LinkType.TUNNEL)) {
addOrUpdateTunnelLink(srcId, srcPort, dstId, dstPort);
}
}
public void removeLink(Link link) {
linksUpdated = true;
dtLinksUpdated = removeLinkFromStructure(directLinks, link);
removeLinkFromStructure(portBroadcastDomainLinks, link);
removeLinkFromStructure(switchPortLinks, link);
NodePortTuple srcNpt =
new NodePortTuple(link.getSrc(), link.getSrcPort());
NodePortTuple dstNpt =
new NodePortTuple(link.getDst(), link.getDstPort());
// Remove switch ports if there are no links through those switch ports
if (switchPortLinks.get(srcNpt) == null) {
if (switchPorts.get(srcNpt.getNodeId()) != null)
switchPorts.get(srcNpt.getNodeId()).remove(srcNpt.getPortId());
}
if (switchPortLinks.get(dstNpt) == null) {
if (switchPorts.get(dstNpt.getNodeId()) != null)
switchPorts.get(dstNpt.getNodeId()).remove(dstNpt.getPortId());
}
// Remove the node if no ports are present
if (switchPorts.get(srcNpt.getNodeId())!=null &&
switchPorts.get(srcNpt.getNodeId()).isEmpty()) {
switchPorts.remove(srcNpt.getNodeId());
}
if (switchPorts.get(dstNpt.getNodeId())!=null &&
switchPorts.get(dstNpt.getNodeId()).isEmpty()) {
switchPorts.remove(dstNpt.getNodeId());
}
}
public void removeLink(long srcId, int srcPort,
long dstId, int dstPort) {
Link link = new Link(srcId, srcPort, dstId, dstPort);
removeLink(link);
}
public void clear() {
switchPorts.clear();
tunnelPorts.clear();
switchPortLinks.clear();
portBroadcastDomainLinks.clear();
directLinks.clear();
}
/**
* Clears the current topology. Note that this does NOT
* send out updates.
*/
public void clearCurrentTopology() {
this.clear();
linksUpdated = true;
dtLinksUpdated = true;
tunnelPortsUpdated = true;
createNewInstance("startup");
lastUpdateTime = new Date();
}
/**
* Getters. No Setters.
*/
public Map<Long, Set<Integer>> getSwitchPorts() {
return switchPorts;
}
public Map<NodePortTuple, Set<Link>> getSwitchPortLinks() {
return switchPortLinks;
}
public Map<NodePortTuple, Set<Link>> getPortBroadcastDomainLinks() {
return portBroadcastDomainLinks;
}
public TopologyInstance getCurrentInstance(boolean tunnelEnabled) {
if (tunnelEnabled)
return currentInstance;
else return this.currentInstanceWithoutTunnels;
}
public TopologyInstance getCurrentInstance() {
return this.getCurrentInstance(true);
}
/**
* Switch methods
*/
@Override
public Set<Integer> getPorts(long sw) {
IOFSwitch iofSwitch = floodlightProvider.getSwitch(sw);
if (iofSwitch == null) return Collections.emptySet();
Collection<Integer> ofpList = iofSwitch.getEnabledPortNumbers();
if (ofpList == null) return Collections.emptySet();
Set<Integer> ports = new HashSet<Integer>(ofpList);
Set<Integer> qPorts = linkDiscovery.getQuarantinedPorts(sw);
if (qPorts != null)
ports.removeAll(qPorts);
return ports;
}
}
|
Syn-Flow/Controller
|
src/main/java/net/floodlightcontroller/topology/TopologyManager.java
|
Java
|
apache-2.0
| 56,882 |
namespace Foundation.StateMachine
{
public class ValueStateTransition<TStateType, TInputType> : StateTransition<TStateType, TInputType>
{
public ValueStateTransition(TStateType fromState, TStateType toState, TInputType input)
{
FromState = fromState;
ToState = toState;
InputValue = input;
InputValidator = ValidateInput;
}
bool ValidateInput(TInputType value)
{
return value != null && value.Equals(InputValue);
}
/// <summary>
/// Gets or sets the valid input for this transition.
/// </summary>
/// <value>The input.</value>
public TInputType InputValue { get; set; }
}
}
|
DavidMoore/Foundation
|
Code/Foundation/StateMachine/ValueStateTransition.cs
|
C#
|
apache-2.0
| 759 |
package com.cognizant.cognizantits.qcconnection.qcupdation;
import com4j.DISPID;
import com4j.IID;
import com4j.VTID;
@IID("{DDE517F0-AF73-4327-A1BD-403E6A047B0A}")
public abstract interface IHierarchySupportList
extends IFactoryList
{
@DISPID(12)
@VTID(19)
public abstract boolean isInFilter(int paramInt);
}
/* Location: D:\Prabu\jars\QC.jar
* Qualified Name: qcupdation.IHierarchySupportList
* JD-Core Version: 0.7.0.1
*/
|
CognizantQAHub/Cognizant-Intelligent-Test-Scripter
|
QcConnection/src/main/java/com/cognizant/cognizantits/qcconnection/qcupdation/IHierarchySupportList.java
|
Java
|
apache-2.0
| 456 |
/*
* Copyright 2010-2016 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.waf.model.transform;
import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.waf.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* DeleteIPSetRequest Marshaller
*/
public class DeleteIPSetRequestMarshaller implements
Marshaller<Request<DeleteIPSetRequest>, DeleteIPSetRequest> {
public Request<DeleteIPSetRequest> marshall(
DeleteIPSetRequest deleteIPSetRequest) {
if (deleteIPSetRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
Request<DeleteIPSetRequest> request = new DefaultRequest<DeleteIPSetRequest>(
deleteIPSetRequest, "AWSWAF");
request.addHeader("X-Amz-Target", "AWSWAF_20150824.DeleteIPSet");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
final StructuredJsonGenerator jsonGenerator = SdkJsonProtocolFactory
.createWriter(false, "1.1");
jsonGenerator.writeStartObject();
if (deleteIPSetRequest.getIPSetId() != null) {
jsonGenerator.writeFieldName("IPSetId").writeValue(
deleteIPSetRequest.getIPSetId());
}
if (deleteIPSetRequest.getChangeToken() != null) {
jsonGenerator.writeFieldName("ChangeToken").writeValue(
deleteIPSetRequest.getChangeToken());
}
jsonGenerator.writeEndObject();
byte[] content = jsonGenerator.getBytes();
request.setContent(new ByteArrayInputStream(content));
request.addHeader("Content-Length",
Integer.toString(content.length));
request.addHeader("Content-Type", jsonGenerator.getContentType());
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
|
mhurne/aws-sdk-java
|
aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/transform/DeleteIPSetRequestMarshaller.java
|
Java
|
apache-2.0
| 3,111 |
package com.adeptions.clarguments.validators;
import com.adeptions.clarguments.ArgumentName;
import com.adeptions.clarguments.BadArgumentException;
import com.adeptions.clarguments.arguments.Argument;
import static com.adeptions.clarguments.PredefinedBadArgumentReasons.MULTIPLE_ARGUMENT_NOT_ALLOWED;
public class DisallowMultiplesValueValidator implements ArgumentValueValidator {
/**
* {@inheritDoc}
*/
@Override
public Object validate(int tokenPosition, Object value, Argument argument, ArgumentName specifiedArgumentName) throws BadArgumentException {
if (argument.wasSeen()) {
throw new BadArgumentException(MULTIPLE_ARGUMENT_NOT_ALLOWED, tokenPosition,
"Argument '" + specifiedArgumentName.getDisplayName() + "' cannot be specified more than once", argument, specifiedArgumentName);
}
return value;
}
}
|
Adeptions/CLArguments
|
src/main/java/com/adeptions/clarguments/validators/DisallowMultiplesValueValidator.java
|
Java
|
apache-2.0
| 893 |
package apple.mapkit;
import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.corelocation.*;
import apple.uikit.*;
import apple.dispatch.*;
/**
* @since Available in iOS 7.0 and later.
*/
@Library("MapKit/MapKit.h")
@Mapping("MKOverlayLevel")
public final class MKOverlayLevel extends ObjCEnum {
@GlobalConstant("MKOverlayLevelAboveRoads")
public static final long Roads = 0L;
@GlobalConstant("MKOverlayLevelAboveLabels")
public static final long Labels = 1L;
}
|
Sellegit/j2objc
|
runtime/src/main/java/apple/mapkit/MKOverlayLevel.java
|
Java
|
apache-2.0
| 769 |
# Copyright (c) 2012-2015 Snowplow Analytics Ltd. All rights reserved.
#
# This program is licensed to you under the Apache License Version 2.0,
# and you may not use this file except in compliance with the Apache License Version 2.0.
# You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the Apache License Version 2.0 is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
# Author:: Alex Dean (mailto:support@snowplowanalytics.com)
# Copyright:: Copyright (c) 2012-2015 Snowplow Analytics Ltd
# License:: Apache License Version 2.0
# Ruby 1.9.2 onwards doesn't add . into $LOAD_PATH by default - use require_relative instead
require_relative 'snowplow-storage-loader/snowplow'
require_relative 'snowplow-storage-loader/errors'
require_relative 'snowplow-storage-loader/contracts'
require_relative 'snowplow-storage-loader/config'
require_relative 'snowplow-storage-loader/file_tasks'
require_relative 'snowplow-storage-loader/s3_tasks'
require_relative 'snowplow-storage-loader/postgres_loader'
require_relative 'snowplow-storage-loader/shredded_type'
require_relative 'snowplow-storage-loader/redshift_loader'
require_relative 'snowplow-storage-loader/sanitization'
require_relative 'snowplow-storage-loader/mongo_loader'
module Snowplow
module StorageLoader
NAME = "snowplow-storage-loader"
VERSION = "0.11.0-rc5"
end
end
|
haensel-ams/snowplow
|
4-storage/storage-loader/lib/snowplow-storage-loader.rb
|
Ruby
|
apache-2.0
| 1,676 |
/*
* Copyright 2010-2017 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.
*/
#include <aws/robomaker/model/RobotSoftwareSuite.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace RoboMaker
{
namespace Model
{
RobotSoftwareSuite::RobotSoftwareSuite() :
m_name(RobotSoftwareSuiteType::NOT_SET),
m_nameHasBeenSet(false),
m_version(RobotSoftwareSuiteVersionType::NOT_SET),
m_versionHasBeenSet(false)
{
}
RobotSoftwareSuite::RobotSoftwareSuite(JsonView jsonValue) :
m_name(RobotSoftwareSuiteType::NOT_SET),
m_nameHasBeenSet(false),
m_version(RobotSoftwareSuiteVersionType::NOT_SET),
m_versionHasBeenSet(false)
{
*this = jsonValue;
}
RobotSoftwareSuite& RobotSoftwareSuite::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("name"))
{
m_name = RobotSoftwareSuiteTypeMapper::GetRobotSoftwareSuiteTypeForName(jsonValue.GetString("name"));
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("version"))
{
m_version = RobotSoftwareSuiteVersionTypeMapper::GetRobotSoftwareSuiteVersionTypeForName(jsonValue.GetString("version"));
m_versionHasBeenSet = true;
}
return *this;
}
JsonValue RobotSoftwareSuite::Jsonize() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("name", RobotSoftwareSuiteTypeMapper::GetNameForRobotSoftwareSuiteType(m_name));
}
if(m_versionHasBeenSet)
{
payload.WithString("version", RobotSoftwareSuiteVersionTypeMapper::GetNameForRobotSoftwareSuiteVersionType(m_version));
}
return payload;
}
} // namespace Model
} // namespace RoboMaker
} // namespace Aws
|
cedral/aws-sdk-cpp
|
aws-cpp-sdk-robomaker/source/model/RobotSoftwareSuite.cpp
|
C++
|
apache-2.0
| 2,203 |
"""Chessboard: Describe an application once, deploy and manage it anywhere.
Chessboard includes utilities for modeling application topologies and
deploying/managing applications in a provider-agnostic way.
"""
import setuptools
VERSION = '0.1.0'
setuptools.setup(
name='chessboard',
version=VERSION,
maintainer='Rackspace Hosting, Inc.',
url='https://github.com/checkmate/chessboard',
description='Describe an application once, deploy and manage it anywhere',
platforms=['any'],
packages=setuptools.find_packages(
exclude=['chessboard.tests', 'chessboard.tests.*']
),
provides=['chessboard (%s)' % VERSION],
license='Apache License 2.0',
keywords=(
'application model topology deployment manage orchestration '
'configuration automation checkmate'
),
include_package_data=True,
data_files=[('chessboard', ['chessboard/schema_docs.yaml'])],
classifiers=(
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
'Topic :: System :: Systems Administration',
),
)
|
larsbutler/chessboard
|
setup.py
|
Python
|
apache-2.0
| 1,395 |
/*
* #%L
* mosaic-platform-core
* %%
* Copyright (C) 2010 - 2013 Institute e-Austria Timisoara (Romania)
* %%
* 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%
*/
package eu.mosaic_cloud.drivers.exceptions;
/**
* Exception thrown when no operation completion callback is set.
*
* @author Georgiana Macariu
*/
public class NullCompletionCallback
extends Exception
{
/**
* Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link Throwable#initCause(Throwable)}.
*/
public NullCompletionCallback () {
super ();
}
/**
* Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link Throwable#initCause(Throwable)}.
*
* @param message
* the detail message. The detail message is saved for later retrieval by the {@link Throwable#getMessage()}
* method
*/
public NullCompletionCallback (final String message) {
super (message);
}
/**
* Constructs a new exception with the specified detail message and cause. Note that the detail message associated with
* cause is not automatically incorporated in this exception's detail message.
*
* @param message
* the detail message. The detail message is saved for later retrieval by the {@link Throwable#getMessage()}
* method
* @param cause
* the cause (which is saved for later retrieval by the {@link Throwable#getCause()} method). (A null value is
* permitted, and indicates that the cause is nonexistent or unknown.)
*/
public NullCompletionCallback (final String message, final Throwable cause) {
super (message, cause);
}
/**
* Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString())
* (which typically contains the class and detail message of cause). This constructor is useful for exceptions that are
* little more than wrappers for other throwables.
*
* @param cause
* the cause (which is saved for later retrieval by the {@link Throwable#getCause()} method). (A null value is
* permitted, and indicates that the cause is nonexistent or unknown.)
*/
public NullCompletionCallback (final Throwable cause) {
super (cause);
}
private static final long serialVersionUID = -3388438945086356985L;
}
|
mosaic-cloud/mosaic-java-platform
|
drivers-core/src/main/java/eu/mosaic_cloud/drivers/exceptions/NullCompletionCallback.java
|
Java
|
apache-2.0
| 2,985 |
/**
* Created by yang on 14/12/8.
*/
var SimpleHotCSV = require('./index').SimpleHotCSV;
var HotCSV = require('./index').HotCSV;
var path = require('path');
var hostCityList = path.join(__dirname,'./whiteCityList.csv');
var hotCity1 = new SimpleHotCSV(hostCityList);
hotCity1.init(function(){
setInterval(function(){
console.log('simpleHotCity length ' + hotCity1.getList().length)
},1000);
});
var hotCity2 = new HotCSV(hostCityList);
hotCity2.init( {headers : ["column1"]},function(){
setInterval(function(){
console.log('hotCity length ' + hotCity1.getList().length)
},1000);
});
|
gastrodia/hot-csv
|
test.js
|
JavaScript
|
apache-2.0
| 619 |
require_relative '../../version2_0'
require_relative '../../relationship'
module BELParser
module Language
module Version2_0
module Relationships
# BiomarkerFor: +A biomarkerFor P+ - For term A and process term
# P, +A biomarkerFor P+ indicates that changes in or detection
# of A is used in some way to be a biomarker for pathology or
# biological process P.
class BiomarkerFor
extend Relationship
SHORT = :biomarkerFor
LONG = :biomarkerFor
DESCRIPTION = ' +A biomarkerFor P+ - For term A and process
erm P, +A biomarkerFor P+ indicates that changes
n or detection of A is used in some way to be
biomarker for pathology or biological process
.'.freeze
def self.short
SHORT
end
def self.long
LONG
end
def self.description
DESCRIPTION
end
def self.deprecated?
true
end
def self.directed?
true
end
end
end
end
end
end
|
nbargnesi/bel-parser
|
lib/bel_parser/language/version2_0/relationships/biomarker_for.rb
|
Ruby
|
apache-2.0
| 1,152 |
package cn.purchasenear.v1.goods.domain;
public class Brand {
}
|
runfriends/PurchaseNear
|
purchasenear/purchasenear-goods/src/main/java/cn/purchasenear/v1/goods/domain/Brand.java
|
Java
|
apache-2.0
| 66 |
#!/bin/env ruby
my_rand = rand(100)
attempts = 10
print "Please enter your name: "
# read the inpute and remove trailing 'newline'
gamer = gets.chomp
while attempts >= 1
puts "#{gamer} - You have #{attempts} attempts left"
puts "Please make your choice"
user_choice = gets.to_i
if user_choice > my_rand
then
puts "Error. Your choice is higher than actual value"
elsif user_choice < my_rand
then
puts "Error. Your guess is lower than actual value"
elsif user_choice == my_rand
puts "Congrats, #{gamer}! Coorect answer is #{my_rand}"
exit 0
end
attempts -= 1
end
puts "Sorry #{gamer}. U didn't guess the number: #{my_rand}"
exit 0
|
yprokule/learn-ruby
|
random_number.rb
|
Ruby
|
apache-2.0
| 709 |
/*
* Copyright 2015 Torridity.
*
* 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 de.tor.tribes.ui.components;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.text.NumberFormat;
import javax.swing.*;
/**
*
* @author Torridity
*/
public class FillingLabel extends JLabel {
private double[] fillings = null;
private Color[] colors = null;
private String text = "";
public void setData(double[] fillings, double capacity) {
this.fillings = fillings;
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
double res = 0;
for (Double v : fillings) {
res += v * capacity;
}
res /= 1000;
if(res > 0) {
text = nf.format(res) + " K";
} else {
text = "keine";
}
}
public void setColors(Color[] colors) {
this.colors = colors;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if (fillings == null || colors == null || fillings.length != colors.length) {
return;
}
int h = getHeight() / fillings.length;
if (h == 0) {
return;
}
for (int i = 0; i < fillings.length; i++) {
g2d.setColor(colors[i]);
g2d.fill3DRect(0, i * h, (int) Math.rint(getWidth() * fillings[i]), h, true);
}
g2d.setColor(Color.LIGHT_GRAY);
g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
g2d.setColor(Color.BLACK);
g2d.drawString(text, 1, getHeight() - 1);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
FillingLabel l = new FillingLabel();
l.setPreferredSize(new Dimension(100, 24));
l.setData(new double[]{134644.0 / 400000.0, 180000.0 / 400000.0, 161743.0 / 400000.0}, 400000.0);
l.setColors(new Color[]{new Color(187, 148, 70), new Color(242, 131, 30), new Color(224, 211, 209)});
f.getContentPane().add(l);
f.pack();
f.setVisible(true);
}
}
|
Patschke/dsworkbench
|
Core/src/main/java/de/tor/tribes/ui/components/FillingLabel.java
|
Java
|
apache-2.0
| 2,819 |
package com.jacksen.java.leetcode;
import java.util.Stack;
/**
* 字符串翻转
*
* @author jacksen
*
*/
public class ReverseString {
public static void main(String[] args) {
System.out.println(reverseString7("yansen"));
}
/**
* 时间复杂度 o(n)
*
* @param s
* @return
*/
public static String reverseString(String s) {
String result = "";
char[] ch = s.toCharArray();
for (int i = ch.length - 1; i >= 0; i--) {
result += ch[i];
}
return result;
}
/**
* 时间复杂度 o(n)
*
* @param s
* @return
*/
public static String reverseString2(String s) {
String result = "";
for (int i = s.length() - 1; i >= 0; i--) {
result += s.charAt(i);
}
return result;
}
/**
* 使用StringBuffer类中的reverse方法
*
* @param s
* @return
*/
public static String reverseString3(String s) {
return new StringBuffer(s).reverse().toString();
}
/**
* 时间复杂度o(n/2)
*
* @param s
* @return
*/
public static String reverseString4(String s) {
char[] ch = s.toCharArray();
int halfLength = s.length() / 2;
char temp;
for (int i = 0; i < halfLength; i++) {
temp = ch[s.length() - 1 - i];
ch[s.length() - 1 - i] = ch[i];
ch[i] = temp;
}
return new String(ch);
}
/**
* 异或运算 -- 时间复杂度o(n/2)
*
* @param s
* @return
*/
public static String reverseString5(String s) {
char[] ch = s.toCharArray();
int start = 0;
int end = ch.length - 1;
while (start < end) {
ch[start] = (char) (ch[start] ^ ch[end]);
ch[end] = (char) (ch[start] ^ ch[end]);
ch[start] = (char) (ch[start] ^ ch[end]);
start++;
end--;
}
return new String(ch);
}
/**
* 通过入栈和出栈的思想来做 -- 时间复杂度o(2n)
*
* @param s
* @return
*/
public static String reverseString6(String s) {
Stack<Character> stack = new Stack<>();
char[] ch = s.toCharArray();
String result = "";
for (int i = 0; i < ch.length; i++) {
stack.push(ch[i]);
}
for (int i = 0; i < ch.length; i++) {
result += stack.pop();
}
return result;
}
/**
* 通过递归来做
*
* @param s
* @return
*/
public static String reverseString7(String s) {
int length = s.length();
if (length <= 1) {
return s;
}
String leftStr = s.substring(0, length / 2);
String rightStr = s.substring(length / 2, length);
return reverseString7(rightStr) + reverseString7(leftStr);
}
}
|
crazy1235/BaseJavaProject
|
BaseJavaProject/src/com/jacksen/java/leetcode/ReverseString.java
|
Java
|
apache-2.0
| 2,437 |
// Copyright 2016 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.
using Google.Apis.Bigquery.v2;
using Xunit;
using static Google.Apis.Bigquery.v2.JobsResource;
using static Google.Apis.Bigquery.v2.JobsResource.ListRequest;
namespace Google.Cloud.BigQuery.V2.Tests
{
public class ListJobsOptionsTest
{
[Fact]
public void ModifyRequest()
{
var options = new ListJobsOptions
{
PageSize = 25,
StateFilter = JobState.Pending,
AllUsers = true,
Projection = ProjectionEnum.Full
};
ListRequest request = new ListRequest(new BigqueryService(), "project");
options.ModifyRequest(request);
Assert.Equal(25, request.MaxResults);
Assert.Equal(StateFilterEnum.Pending, request.StateFilter);
Assert.Equal(true, request.AllUsers);
Assert.Equal(ProjectionEnum.Full, request.Projection);
}
}
}
|
iantalarico/google-cloud-dotnet
|
apis/Google.Cloud.BigQuery.V2/Google.Cloud.BigQuery.V2.Tests/ListJobsOptionsTest.cs
|
C#
|
apache-2.0
| 1,544 |
package phoswald.annotation.printer.annotations;
public enum MyEnum {
VALUE_1, VALUE_2
}
|
phoswald/annotation-printer
|
src/test/java/phoswald/annotation/printer/annotations/MyEnum.java
|
Java
|
apache-2.0
| 94 |
/*
* 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.calcite.rex;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.fun.SqlQuantifyOperator;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.type.SqlTypeName;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
/**
* Scalar expression that represents an IN, EXISTS or scalar sub-query.
*/
public class RexSubQuery extends RexCall {
public final RelNode rel;
private RexSubQuery(RelDataType type, SqlOperator op,
ImmutableList<RexNode> operands, RelNode rel) {
super(type, op, operands);
this.rel = rel;
}
/** Creates an IN sub-query. */
public static RexSubQuery in(RelNode rel, ImmutableList<RexNode> nodes) {
final RelDataType type = type(rel, nodes);
return new RexSubQuery(type, SqlStdOperatorTable.IN, nodes, rel);
}
/** Creates a SOME sub-query.
*
* <p>There is no ALL. For {@code x comparison ALL (sub-query)} use instead
* {@code NOT (x inverse-comparison SOME (sub-query))}.
* If {@code comparison} is {@code >}
* then {@code negated-comparison} is {@code <=}, and so forth.
*
* <p>Also =SOME is rewritten into IN</p> */
public static RexSubQuery some(RelNode rel, ImmutableList<RexNode> nodes,
SqlQuantifyOperator op) {
assert op.kind == SqlKind.SOME;
if (op == SqlStdOperatorTable.SOME_EQ) {
return RexSubQuery.in(rel, nodes);
}
final RelDataType type = type(rel, nodes);
return new RexSubQuery(type, op, nodes, rel);
}
static RelDataType type(RelNode rel, ImmutableList<RexNode> nodes) {
assert rel.getRowType().getFieldCount() == nodes.size();
final RelDataTypeFactory typeFactory = rel.getCluster().getTypeFactory();
boolean nullable = false;
for (RexNode node : nodes) {
if (node.getType().isNullable()) {
nullable = true;
}
}
for (RelDataTypeField field : rel.getRowType().getFieldList()) {
if (field.getType().isNullable()) {
nullable = true;
}
}
return typeFactory.createTypeWithNullability(
typeFactory.createSqlType(SqlTypeName.BOOLEAN), nullable);
}
/** Creates an EXISTS sub-query. */
public static RexSubQuery exists(RelNode rel) {
final RelDataTypeFactory typeFactory = rel.getCluster().getTypeFactory();
final RelDataType type = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
return new RexSubQuery(type, SqlStdOperatorTable.EXISTS,
ImmutableList.of(), rel);
}
/** Creates a scalar sub-query. */
public static RexSubQuery scalar(RelNode rel) {
final List<RelDataTypeField> fieldList = rel.getRowType().getFieldList();
assert fieldList.size() == 1;
final RelDataTypeFactory typeFactory = rel.getCluster().getTypeFactory();
final RelDataType type =
typeFactory.createTypeWithNullability(fieldList.get(0).getType(), true);
return new RexSubQuery(type, SqlStdOperatorTable.SCALAR_QUERY,
ImmutableList.of(), rel);
}
@Override public <R> R accept(RexVisitor<R> visitor) {
return visitor.visitSubQuery(this);
}
@Override public <R, P> R accept(RexBiVisitor<R, P> visitor, P arg) {
return visitor.visitSubQuery(this, arg);
}
@Override protected @Nonnull String computeDigest(boolean withType) {
final StringBuilder sb = new StringBuilder(op.getName());
sb.append("(");
for (RexNode operand : operands) {
sb.append(operand);
sb.append(", ");
}
sb.append("{\n");
sb.append(RelOptUtil.toString(rel));
sb.append("})");
return sb.toString();
}
@Override public RexSubQuery clone(RelDataType type, List<RexNode> operands) {
return new RexSubQuery(type, getOperator(),
ImmutableList.copyOf(operands), rel);
}
public RexSubQuery clone(RelNode rel) {
return new RexSubQuery(type, getOperator(), operands, rel);
}
@Override public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof RexSubQuery)) {
return false;
}
RexSubQuery sq = (RexSubQuery) obj;
return op.equals(sq.op)
&& operands.equals(sq.operands)
&& rel.deepEquals(sq.rel);
}
@Override public int hashCode() {
if (hash == 0) {
hash = Objects.hash(op, operands, rel.deepHashCode());
}
return hash;
}
}
|
julianhyde/calcite
|
core/src/main/java/org/apache/calcite/rex/RexSubQuery.java
|
Java
|
apache-2.0
| 5,459 |
package com.dgcy.http.msg;
import com.google.gson.annotations.Expose;
import com.dgcy.http.base.AbstractResponseBody;
import com.dgcy.http.base.AbstractResponseMsg;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class INF1000_Res extends AbstractResponseMsg<INF1000_Res.INF1000_Res_Body> {
public static class INF1000_Res_Body extends AbstractResponseBody {
@Expose
private List<InfoItem> items = new ArrayList<InfoItem>();
public List<InfoItem> getItems() {
return items;
}
public void setItems(List<InfoItem> items) {
this.items = items;
}
public static class InfoItem implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Expose
private String sn = ""; // 序号
@Expose
private String id = ""; // 编号
@Expose
private String title = ""; // 标题
@Expose
private String from = ""; // 来源
@Expose
private String editor = ""; // 作者
@Expose
private String time = ""; // 时间
@Expose
private String type = ""; // 类型
@Expose
private String name = ""; // 类别名称
@Expose
private String intro = ""; // 简介
@Expose
private String hot = ""; // 是否热门
@Expose
private String top = ""; // 是否置顶
@Expose
private String url = "";
@Expose
private String relateType = "";
@Expose
private String relateContent = "";
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getEditor() {
return editor;
}
public void setEditor(String editor) {
this.editor = editor;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public String getHot() {
return hot;
}
public void setHot(String hot) {
this.hot = hot;
}
public String getTop() {
return top;
}
public void setTop(String top) {
this.top = top;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getRelateType() {
return relateType;
}
public void setRelateType(String relateType) {
this.relateType = relateType;
}
public String getRelateContent() {
return relateContent;
}
public void setRelateContent(String relateContent) {
this.relateContent = relateContent;
}
}
}
@Override
protected Class<INF1000_Res_Body> getResBodyType() {
return INF1000_Res_Body.class;
}
}
|
yasenagat/AndroidTest
|
VolleyTest/src/main/java/com/dgcy/http/msg/INF1000_Res.java
|
Java
|
apache-2.0
| 4,492 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.unsignedlong;
import org.elasticsearch.painless.spi.PainlessExtension;
import org.elasticsearch.painless.spi.Whitelist;
import org.elasticsearch.painless.spi.WhitelistLoader;
import org.elasticsearch.script.AggregationScript;
import org.elasticsearch.script.BucketAggregationSelectorScript;
import org.elasticsearch.script.FieldScript;
import org.elasticsearch.script.FilterScript;
import org.elasticsearch.script.NumberSortScript;
import org.elasticsearch.script.ScoreScript;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.StringSortScript;
import java.util.List;
import java.util.Map;
import static java.util.Collections.singletonList;
public class DocValuesWhitelistExtension implements PainlessExtension {
private static final Whitelist WHITELIST = WhitelistLoader.loadFromResourceFiles(DocValuesWhitelistExtension.class, "whitelist.txt");
@Override
public Map<ScriptContext<?>, List<Whitelist>> getContextWhitelists() {
List<Whitelist> whitelist = singletonList(WHITELIST);
Map<ScriptContext<?>, List<Whitelist>> contexts = Map.of(
FieldScript.CONTEXT,
whitelist,
ScoreScript.CONTEXT,
whitelist,
FilterScript.CONTEXT,
whitelist,
AggregationScript.CONTEXT,
whitelist,
NumberSortScript.CONTEXT,
whitelist,
StringSortScript.CONTEXT,
whitelist,
BucketAggregationSelectorScript.CONTEXT,
whitelist
);
return contexts;
}
}
|
scorpionvicky/elasticsearch
|
x-pack/plugin/mapper-unsigned-long/src/main/java/org/elasticsearch/xpack/unsignedlong/DocValuesWhitelistExtension.java
|
Java
|
apache-2.0
| 1,850 |
// Copyright 2020 Google LLC
//
// 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.
//
// ** This file is automatically generated by synthtool. **
// ** https://github.com/googleapis/synthtool **
// ** All changes to this file may be overwritten. **
import * as v1 from './v1';
import * as v1beta1 from './v1beta1';
const BudgetServiceClient = v1.BudgetServiceClient;
type BudgetServiceClient = v1.BudgetServiceClient;
export {v1, v1beta1, BudgetServiceClient};
export default {v1, v1beta1, BudgetServiceClient};
import * as protos from '../protos/protos';
export {protos};
|
googleapis/nodejs-billing-budgets
|
src/index.ts
|
TypeScript
|
apache-2.0
| 1,081 |
# Copyright 2011 Tsutomu Uchino
#
# 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.
def create_popupmenu(ctx, items):
""" create popup menu from items
[ [id, pos, type, 'label', "command", acc_key], [] ]
"""
try:
menu = ctx.getServiceManager().createInstanceWithContext(
"com.sun.star.awt.PopupMenu", ctx)
for i in items:
if i[0] is None or i[0] == -1:
menu.insertSeparator(i[1])
else:
menu.insertItem(i[0], i[3], i[2], i[1])
menu.setCommand(i[0], i[4])
if i[5] is not None:
try:
menu.setAcceleratorKeyEvent(i[0], i[5])
except:
pass
except Exception as e:
print(e)
return menu
def get_current_sentence(target, mini):
""" (\n| )... min ... """
lfstart = target.rfind("\n", 0, mini)
lfend = target.find("\n", mini)
if lfend < 0:
lfend = len(target)
spstart = target.rfind(" ", 0, mini)
spend = target.find(" ", mini)
if spend < 0:
spend = len(target)
if lfstart >= spstart:
start = lfstart +1
if start < 0:
start = 0
else:
start = spstart +2
if spend < lfend:
end = spend
else:
end = lfend
return (start, end)
def get_current_line(target, mini):
""" # xxx\n...min....\nxxx """
start = target.rfind("\n", 0, mini) +1
if start < 0:
start = 0
end = target.find("\n", mini)
if end < 0:
end = len(target)
return (start, end)
def get_first_word(line):
pos = line.lstrip().find(" ")
if pos < 0:
pos = len(line)
return line[0:pos]
|
hanya/MRI
|
pythonpath/mytools_Mri/ui/tools.py
|
Python
|
apache-2.0
| 2,328 |
/*
* Copyright 2017-2022 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.cognitoidp.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/AdminDisableProviderForUser"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AdminDisableProviderForUserResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* 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("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AdminDisableProviderForUserResult == false)
return false;
AdminDisableProviderForUserResult other = (AdminDisableProviderForUserResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public AdminDisableProviderForUserResult clone() {
try {
return (AdminDisableProviderForUserResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/AdminDisableProviderForUserResult.java
|
Java
|
apache-2.0
| 2,427 |
/*
* #%L
* package-info.java - mongodb-async-driver - Allanbank Consulting, Inc.
* %%
* Copyright (C) 2011 - 2014 Allanbank Consulting, 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.
* #L%
*/
/**
* Contains an implementation of the metrics collection that collects metrics
* for users to manually inspect.
*
* @api.no This package is <b>NOT</b> part of the drivers API. This class may be
* mutated in incompatible ways between any two releases of the driver.
* @copyright 2014, Allanbank Consulting, Inc., All Rights Reserved
*/
package com.allanbank.mongodb.client.metrics.basic;
|
allanbank/mongodb-async-driver
|
src/main/java/com/allanbank/mongodb/client/metrics/basic/package-info.java
|
Java
|
apache-2.0
| 1,122 |
// JavaScript Document
function run_timer()
{
var today = new Date();
var ndate=today.toString(); //April 23, 2009, 02:04:25 pm
ndate=ndate.split('GMT');
document.getElementById("TimeDiv").style.border='transparent';
document.getElementById("TimeDiv").innerHTML=ndate[0];
setTimeout(run_timer,1000);
}
function getHeightWidht()
{
var viewportwidth;
var viewportheight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined')
{
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
{
viewportwidth = document.documentElement.clientWidth;
viewportheight = document.documentElement.clientHeight
}
// older versions of IE
else
{
viewportwidth = document.getElementsById('bodyid').clientWidth;
viewportheight = document.getElementsById('bodyid').clientHeight;
}
return parseInt(viewportwidth);
}
function checkall(thisid)
{
for(var i=1;document.getElementById('check'+i);i++){
if(document.getElementById(thisid.id).checked==true){
document.getElementById('check'+i).checked = true;
}
if(document.getElementById(thisid.id).checked==false){
document.getElementById('check'+i).checked = false;
}
}
}
function check_check(spanid,checkid){
var chkchkstat = true;
for(var i=1; document.getElementById('check'+i); i++){
if(document.getElementById('check'+i).checked == false){
chkchkstat = false;
break;
}
}
//alert(chkchkstat);
if(chkchkstat == false){
$('#'+spanid).html('');
document.getElementById(checkid).checked = false;
} else {
document.getElementById(checkid).checked = true;
}
return true;
}
function checknummsp(e)
{
evt=e || window.event;
var keypressed=evt.which || evt.keyCode;
//alert(keypressed);
if(keypressed!="48" && keypressed!="49" && keypressed!="50" && keypressed!="51" && keypressed!="52" && keypressed!="53" && keypressed!="54" && keypressed!="55" && keypressed!="8" && keypressed!="56" && keypressed!="57" && keypressed!="45" && keypressed!="46" && keypressed!="37" && keypressed!="39" && keypressed!="9")
{
return false;
}
}
function showhidedata(show)
{
if(show==1)
{
if(document.getElementById('firstdiv').style.display=="block")
{
document.getElementById('firstdiv').style.display="none";
}
else
{
document.getElementById('firstdiv').style.display="block";
}
}
}
function showhidediscp(show)
{
if(show==1)
{
if(document.getElementById('dispdiv').style.display=="block")
{
document.getElementById('dispdiv').style.display="none";
}
else
{
document.getElementById('dispdiv').style.display="block";
}
}
}
function hrefHandler()
{
var a=window.location.pathname;
var b=a.match(/[\/|\\]([^\\\/]+)$/);
var ans=confirm("Are you sure? You want to delete.");
return ans;
}
function EmptyListbox(listBoxId)
{
var elSel = document.getElementById(listBoxId);
for (i = elSel.length - 1; i>=0; i--) {
elSel.remove(i);
}
}
function AddOptiontoListBox(listBoxId,Value,Text)
{
var elSel = document.getElementById(listBoxId);
var opt = document.createElement("option");
elSel.options.add(opt);
opt.text=Text;
opt.value=Value;
}
function CollaspeExpand(divName)
{
$('#Child'+divName).slideToggle("slow");
/*if(document.getElementById('Child'+divName).style.display=="block")
{
document.getElementById('Child'+divName).style.display="none";
}
else
{
document.getElementById('Child'+divName).style.display="block";
}*/
}
//phone no
function checkLen(charlen,e)
{
var mb= document.getElementById('phone_number').value;
//alert(mb.length);
evt=e || window.event;
var keypressed=evt.which || evt.keyCode;
//alert(keypressed);
if(keypressed!="48" && keypressed!="49" && keypressed!="50" && keypressed!="51" && keypressed!="52" && keypressed!="53" && keypressed!="54" && keypressed!="55" && keypressed!="8" && keypressed!="56" && keypressed!="57" && keypressed!="45" && keypressed!="46" && keypressed!="37" && keypressed!="39" && keypressed!="9")
{
return false;
}
else
{
if(mb.length<3)
{
return charlen;
}
else if(mb.length==3 || mb.length==7 )
{
var dashchar="-";
var charlen1=charlen+dashchar;
var charlen2=document.getElementById('phone_number').value=charlen1;
//var charlen2=charlen1.join("-");
//alert(charlen2);
return charlen1;
//return charlen1;
}
}
}
//print_r
function print_r(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += print_r(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
function makepropertyinsurance(){
//check if checkbox is checked
console.log($('#insurance'),$('#insurance').attr('checked'));
if($('#insurance').attr('checked')=='checked'){
$('#is_insured').val('true');
}else{
$('#is_insured').val('false');
}
}
//loading overlay
//element - jquery object [ $('#element') ]
//image_path - path to image i.e. absolute url **:- omit trailing slash in path
function loading(element,image_path){
element.append('<div class="question-overlay question-overlay-box"></div><img src="'+image_path+'/fancybox_loading2x.gif" class="question-overlay loading-image">')
}
function loadingComplete(){
$('.question-overlay').remove();
}
function linkify(inputText) {
var replacedText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
return replacedText;
}
|
ankuradhey/dealtrip
|
js/general.js
|
JavaScript
|
apache-2.0
| 7,612 |
/* Copyright 2005-2015 Alfresco Software, Ltd.
*
* 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.
*/
'use strict';
flowableAdminApp.controller('ProcessInstanceController', ['$scope', '$rootScope', '$http', '$timeout', '$location', '$routeParams', '$modal', '$translate', '$q', 'gridConstants',
function ($scope, $rootScope, $http, $timeout, $location, $routeParams, $modal, $translate, $q, gridConstants) {
$rootScope.navigation = {main: 'process-engine', sub: 'instances'};
$scope.tabData = {
tabs: [
{id: 'tasks', name: 'PROCESS-INSTANCE.TITLE.TASKS'},
{id: 'variables', name: 'PROCESS-INSTANCE.TITLE.VARIABLES'},
{id: 'subProcesses', name: 'PROCESS-INSTANCE.TITLE.SUBPROCESSES'},
{id: 'jobs', name: 'PROCESS-INSTANCE.TITLE.JOBS'}
]
};
$scope.tabData.activeTab = $scope.tabData.tabs[0].id;
$scope.returnToList = function () {
$location.path("/process-instances");
};
$scope.openTask = function (task) {
if (task && task.getProperty('id')) {
$location.path("/task/" + task.getProperty('id'));
}
};
$scope.openJob = function (job) {
if (job && job.getProperty('id')) {
$location.path("/job/" + job.getProperty('id'));
}
};
$scope.openProcessInstance = function (instance) {
if (instance) {
var id;
if (instance.getProperty !== undefined) {
id = instance.getProperty('id');
} else {
id = instance;
}
$location.path("/process-instance/" + id);
}
};
$scope.showAllTasks = function () {
// Populate the task-filter with parentId
$rootScope.filters.forced.taskFilter = {
processInstanceId: $scope.process.id
};
$location.path("/tasks");
};
$scope.showAllSubprocesses = function () {
// Populate the process-filter with parentId
$rootScope.filters.forced.instanceFilter = {
superProcessInstanceId: $scope.process.id
};
$scope.returnToList();
};
$scope.openProcessDefinition = function (processDefinitionId) {
if (processDefinitionId) {
$location.path("/process-definition/" + processDefinitionId);
}
};
$scope.showProcessDiagram = function () {
$modal.open({
templateUrl: 'views/process-instance-diagram-popup.html',
windowClass: 'modal modal-full-width',
controller: 'ShowProcessInstanceDiagramPopupCtrl',
resolve: {
process: function () {
return $scope.process;
}
}
});
};
$scope.openDecisionTable = function (decisionTable) {
if (decisionTable && decisionTable.getProperty('id')) {
$location.path("/decision-table-execution/" + decisionTable.getProperty('id'));
}
};
$scope.openFormInstance = function (submittedForm) {
if (submittedForm && submittedForm.getProperty('id')) {
$location.path("/form-instance/" + submittedForm.getProperty('id'));
}
};
$scope.loadProcessDefinition = function () {
// Load definition
$http({
method: 'GET',
url: '/app/rest/admin/process-definitions/' + $scope.process.processDefinitionId
}).success(function (data, status, headers, config) {
$scope.definition = data;
}).error(function (data, status, headers, config) {
});
};
$scope.loadProcessInstance = function () {
$scope.process = undefined;
// Load process
$http({
method: 'GET',
url: '/app/rest/admin/process-instances/' + $routeParams.processInstanceId
}).success(function (data, status, headers, config) {
$scope.process = data;
if (data) {
$scope.processCompleted = data.endTime != undefined;
}
// Start loading children
$scope.loadProcessDefinition();
$scope.loadTasks();
$scope.loadVariables();
$scope.loadSubProcesses();
$scope.loadJobs();
$scope.loadDecisionTables()
$scope.tabData.tabs.push({id: 'decisionTables', name: 'PROCESS-INSTANCE.TITLE.DECISION-TABLES'});
$scope.tabData.tabs.push({id: 'forms', name: 'PROCESS-INSTANCE.TITLE.FORM-INSTANCES'});
//TODO: implement when decision task runtime data is stored
// $scope.loadDecisionTables();
$scope.loadFormInstances();
}).error(function (data, status, headers, config) {
if (data && data.message) {
// Extract error-message
$rootScope.addAlert(data.message, 'error');
} else {
// Use default error-message
$rootScope.addAlert($translate.instant('ALERT.GENERAL.HTTP-ERROR'), 'error');
}
});
};
var dateTemplate = '<div><div class="ngCellText" title="{{row.getProperty(col.field) | dateformat:\'full\'}}">{{row.getProperty(col.field) | dateformat}}</div></div>';
// Config for subtasks grid
$q.all([$translate('TASKS.HEADER.ID'),
$translate('TASKS.HEADER.NAME'),
$translate('TASKS.HEADER.ASSIGNEE'),
$translate('TASKS.HEADER.OWNER'),
$translate('TASKS.HEADER.CREATE-TIME'),
$translate('TASKS.HEADER.END-TIME')])
.then(function (headers) {
$scope.gridTasks = {
data: 'tasks.data',
enableRowReordering: false,
multiSelect: false,
keepLastSelected: false,
enableSorting: false,
rowHeight: 36,
afterSelectionChange: $scope.openTask,
columnDefs: [
{field: 'id', displayName: headers[0], width: 50},
{field: 'name', displayName: headers[1]},
{field: 'assignee', displayName: headers[2], cellTemplate: gridConstants.defaultTemplate},
{field: 'owner', displayName: headers[3], cellTemplate: gridConstants.defaultTemplate},
{field: 'startTime', displayName: headers[4], cellTemplate: dateTemplate},
{field: 'endTime', displayName: headers[5], cellTemplate: dateTemplate}
]
};
});
$q.all([$translate('VARIABLES.HEADER.NAME'),
$translate('VARIABLES.HEADER.TYPE'),
$translate('VARIABLES.HEADER.VALUE')])
.then(function (headers) {
var variableValueTemplate = '<div><div class="ngCellText">{{row.getProperty("variable.valueUrl") && "(Binary)" || row.getProperty(col.field)}}</div></div>';
var variableTypeTemplate = '<div><div class="ngCellText">{{row.getProperty(col.field) && row.getProperty(col.field) || "null"}}</div></div>';
$scope.selectedVariables = [];
// Config for variable grid
$scope.gridVariables = {
data: 'variables.data',
enableRowReordering: false,
multiSelect: false,
keepLastSelected: false,
enableSorting: false,
rowHeight: 36,
selectedItems: $scope.selectedVariables,
columnDefs: [
{field: 'variable.name', displayName: headers[0]},
{field: 'variable.type', displayName: headers[1], cellTemplate: variableTypeTemplate},
{field: 'variable.value', displayName: headers[2], cellTemplate: variableValueTemplate}
]
};
});
$q.all([$translate('PROCESS-INSTANCES.HEADER.ID'),
$translate('PROCESS-INSTANCES.HEADER.NAME'),
$translate('PROCESS-INSTANCES.HEADER.PROCESS-DEFINITION'),
$translate('PROCESS-INSTANCES.HEADER.STATUS')])
.then(function (headers) {
var subprocessStateTemplate = '<div><div class="ngCellText">{{row.getProperty("endTime") && "Completed" || "Active"}}</div></div>';
// Config for variable grid
$scope.gridSubprocesses = {
data: 'subprocesses.data',
enableRowReordering: false,
multiSelect: false,
keepLastSelected: false,
enableSorting: false,
rowHeight: 36,
afterSelectionChange: $scope.openProcessInstance,
columnDefs: [
{field: 'id', displayName: headers[0]},
{field: 'name', displayName: headers[1]},
{field: 'processDefinitionId', displayName: headers[2]},
{field: 'endTime', displayName: headers[3], cellTemplate: subprocessStateTemplate}
]
};
});
$q.all([$translate('JOBS.HEADER.ID'),
$translate('JOBS.HEADER.DUE-DATE'),
$translate('JOBS.HEADER.RETRIES'),
$translate('JOBS.HEADER.EXCEPTION')])
.then(function (headers) {
var dateTemplate = '<div><div class="ngCellText" title="{{row.getProperty(col.field) | dateformat:\'full\'}}">{{row.getProperty(col.field) | dateformat}}</div></div>';
// Config for variable grid
$scope.gridJobs = {
data: 'jobs.data',
enableRowReordering: false,
multiSelect: false,
keepLastSelected: false,
enableSorting: false,
rowHeight: 36,
afterSelectionChange: $scope.openJob,
columnDefs: [
{field: 'id', displayName: headers[0], width: 50},
{field: 'dueDate', displayName: headers[1], cellTemplate: dateTemplate},
{field: 'retries', displayName: headers[2]},
{field: 'exceptionMessage', displayName: headers[3]}
]
};
});
$q.all([$translate('DECISION-TABLE-EXECUTION.HEADER.ID'),
$translate('DECISION-TABLE-EXECUTION.HEADER.DECISION-KEY'),
$translate('DECISION-TABLE-EXECUTION.HEADER.DECISION-DEFINITION-ID'),
$translate('DECISION-TABLE-EXECUTION.HEADER.END-TIME'),
$translate('DECISION-TABLE-EXECUTION.HEADER.FAILED')])
.then(function (headers) {
$scope.gridDecisionTables = {
data: 'decisionTables.data',
enableRowReordering: false,
multiSelect: false,
keepLastSelected: false,
enableSorting: false,
rowHeight: 36,
afterSelectionChange: $scope.openDecisionTable,
columnDefs: [
{field: 'id', displayName: headers[0]},
{field: 'decisionKey', displayName: headers[1]},
{field: 'decisionDefinitionId', displayName: headers[2]},
{
field: 'endTime',
displayName: headers[3],
cellTemplate: gridConstants.dateTemplate
},
{field: 'decisionExecutionFailed', displayName: headers[4]}
]
};
});
$q.all([$translate('FORM-INSTANCE.HEADER.ID'),
$translate('FORM-INSTANCE.HEADER.TASK-ID'),
$translate('FORM-INSTANCE.HEADER.PROCESS-ID'),
$translate('FORM-INSTANCE.HEADER.SUBMITTED'),
$translate('FORM-INSTANCE.HEADER.SUBMITTED-BY')])
.then(function (headers) {
$scope.gridFormInstances = {
data: 'formInstances.data',
enableRowReordering: false,
multiSelect: false,
keepLastSelected: false,
enableSorting: false,
rowHeight: 36,
afterSelectionChange: $scope.openFormInstance,
columnDefs: [
{field: 'id', displayName: headers[0]},
{field: 'taskId', displayName: headers[1]},
{field: 'processInstanceId', displayName: headers[2]},
{field: 'submittedDate', displayName: headers[3], cellTemplate: gridConstants.dateTemplate},
{field: 'submittedBy', displayName: headers[4], cellTemplate: gridConstants.userObjectTemplate}
]
};
});
$scope.showAllJobs = function () {
// Populate the job-filter with process id
$rootScope.filters.forced.jobFilter = {
processInstanceId: $scope.process.id
};
$location.path("/jobs");
};
$scope.loadTasks = function () {
$scope.tasks = undefined;
$http({
method: 'GET',
url: '/app/rest/admin/process-instances/' + $scope.process.id + '/tasks'
}).success(function (data, status, headers, config) {
$scope.tasks = data;
$scope.tabData.tabs[0].info = data.total;
});
};
$scope.loadVariables = function () {
$scope.variables = undefined;
$http({
method: 'GET',
url: '/app/rest/admin/process-instances/' + $scope.process.id + '/variables'
}).success(function (data, status, headers, config) {
$scope.variables = data;
$scope.tabData.tabs[1].info = data.total;
});
};
$scope.loadSubProcesses = function () {
$scope.subprocesses = undefined;
$http({
method: 'GET',
url: '/app/rest/admin/process-instances/' + $scope.process.id + '/subprocesses'
}).success(function (data, status, headers, config) {
$scope.subprocesses = data;
$scope.tabData.tabs[2].info = data.total;
});
};
$scope.loadJobs = function () {
$scope.jobs = undefined;
$http({
method: 'GET',
url: '/app/rest/admin/process-instances/' + $scope.process.id + '/jobs'
}).success(function (data, status, headers, config) {
$scope.jobs = data;
$scope.tabData.tabs[3].info = data.total;
});
};
$scope.loadProcessDefinition = function () {
// Load definition
$http({
method: 'GET',
url: '/app/rest/admin/process-definitions/' + $scope.process.processDefinitionId
}).success(function (data, status, headers, config) {
$scope.definition = data;
}).error(function (data, status, headers, config) {
});
};
$scope.loadDecisionTables = function () {
// Load decision tables
$http({
method: 'GET',
url: '/app/rest/admin/process-instances/' + $scope.process.id + '/decision-executions'
}).success(function (data, status, headers, config) {
$scope.decisionTables = data;
$scope.tabData.tabs[4].info = data.total;
}).error(function (data, status, headers, config) {
});
};
$scope.loadFormInstances = function () {
// Load form instances
$http({
method: 'GET',
url: '/app/rest/admin/process-form-instances/' + $scope.process.id
}).success(function (data, status, headers, config) {
$scope.formInstances = data;
$scope.tabData.tabs[5].info = data.total;
}).error(function (data, status, headers, config) {
});
};
$scope.executeWhenReady(function () {
$scope.loadProcessInstance();
});
// Dialogs
$scope.deleteProcessInstance = function (action) {
if (!action) {
action = "delete";
}
var modalInstance = $modal.open({
templateUrl: 'views/process-instance-delete-popup.html',
controller: 'DeleteProcessModalInstanceCtrl',
resolve: {
process: function () {
return $scope.process;
},
action: function () {
return action;
}
}
});
modalInstance.result.then(function (deleteProcessInstance) {
if (deleteProcessInstance) {
if (action == 'delete') {
$scope.addAlert($translate.instant('ALERT.PROCESS-INSTANCE.DELETED', $scope.process), 'info');
$scope.returnToList();
} else {
$scope.addAlert($translate.instant('ALERT.PROCESS-INSTANCE.TERMINATED', $scope.process), 'info');
$scope.loadProcessInstance();
}
}
});
};
$scope.updateSelectedVariable = function () {
if ($scope.selectedVariables && $scope.selectedVariables.length > 0) {
var selectedVariable = $scope.selectedVariables[0];
var modalInstance = $modal.open({
templateUrl: 'views/update-variable-popup.html',
controller: 'UpdateVariableCtrl',
resolve: {
variable: function () {
return selectedVariable.variable;
},
processInstanceId: function () {
return $scope.process.id;
}
}
});
modalInstance.result.then(function (updated) {
if (updated == true) {
$scope.selectedVariables.splice(0, $scope.selectedVariables.length);
$scope.loadVariables();
}
});
}
};
$scope.deleteVariable = function () {
if ($scope.selectedVariables && $scope.selectedVariables.length > 0) {
var selectedVariable = $scope.selectedVariables[0];
var modalInstance = $modal.open({
templateUrl: 'views/variable-delete-popup.html',
controller: 'DeleteVariableCtrl',
resolve: {
variable: function () {
return selectedVariable.variable;
},
processInstanceId: function () {
return $scope.process.id;
}
}
});
modalInstance.result.then(function (updated) {
if (updated == true) {
$scope.selectedVariables.splice(0, $scope.selectedVariables.length);
$scope.loadVariables();
}
});
}
};
$scope.addVariable = function () {
var modalInstance = $modal.open({
templateUrl: 'views/variable-add-popup.html',
controller: 'AddVariableCtrl',
resolve: {
processInstanceId: function () {
return $scope.process.id;
}
}
});
modalInstance.result.then(function (updated) {
if (updated == true) {
$scope.selectedVariables.splice(0, $scope.selectedVariables.length);
$scope.loadVariables();
}
});
};
$scope.terminateProcessInstance = function () {
$scope.deleteProcessInstance("terminate");
};
}]);
flowableAdminApp.controller('DeleteProcessModalInstanceCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'process', 'action', function ($rootScope, $scope, $modalInstance, $http, process, action) {
$scope.process = process;
$scope.action = action;
$scope.status = {loading: false};
$scope.model = {};
$scope.ok = function () {
$scope.status.loading = true;
var dataForPost = {action: $scope.action};
if ($scope.action == 'terminate' && $scope.model.deleteReason) {
dataForPost.deleteReason = $scope.model.deleteReason;
}
$http({
method: 'POST', url: '/app/rest/admin/process-instances/' + $scope.process.id,
data: dataForPost
}).success(function (data, status, headers, config) {
$modalInstance.close(true);
$scope.status.loading = false;
}).error(function (data, status, headers, config) {
$modalInstance.close(false);
$scope.status.loading = false;
});
};
$scope.cancel = function () {
if (!$scope.status.loading) {
$modalInstance.dismiss('cancel');
}
};
}]);
flowableAdminApp.controller('ShowProcessInstanceDiagramPopupCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'process', '$timeout', function ($rootScope, $scope, $modalInstance, $http, process, $timeout) {
$scope.model = {
id: process.id,
name: process.name
};
$scope.status = {loading: false};
$scope.cancel = function () {
if (!$scope.status.loading) {
$modalInstance.dismiss('cancel');
}
};
$timeout(function () {
$("#bpmnModel").attr("data-instance-id", process.id);
$("#bpmnModel").attr("data-definition-id", process.processDefinitionId);
$("#bpmnModel").attr("data-server-id", $rootScope.activeServers['process'].id);
if (process.endTime != undefined) {
$("#bpmnModel").attr("data-history-id", process.id);
}
$("#bpmnModel").load("./display/displaymodel.html?instanceId=" + process.id);
}, 200);
}]);
flowableAdminApp.controller('UpdateVariableCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'variable', 'processInstanceId', function ($rootScope, $scope, $modalInstance, $http, variable, processInstanceId) {
$scope.status = {loading: false};
$scope.originalVariable = variable;
$scope.updateVariable = {
name: variable.name,
value: variable.value,
type: variable.type
};
$scope.executeUpdateVariable = function () {
$scope.status.loading = true;
var dataForPut = {
name: $scope.updateVariable.name,
type: $scope.updateVariable.type
};
if ($scope.updateVariable.value !== null || $scope.updateVariable.value !== undefined || $scope.updateVariable.value !== '') {
if ($scope.updateVariable.type === 'string') {
dataForPut.value = $scope.updateVariable.value;
} else if ($scope.updateVariable.type === 'boolean') {
if ($scope.updateVariable.value) {
dataForPut.value = true;
} else {
dataForPut.value = false;
}
} else if ($scope.updateVariable.type === 'date') {
dataForPut.value = $scope.updateVariable.value;
} else if ($scope.updateVariable.type === 'double'
|| $scope.updateVariable.type === 'long'
|| $scope.updateVariable.type === 'integer'
|| $scope.updateVariable.type === 'short') {
dataForPut.value = Number($scope.updateVariable.value);
}
} else {
dataForPut.value = null;
}
$http({
method: 'PUT',
url: '/app/rest/admin/process-instances/' + processInstanceId + '/variables/' + $scope.updateVariable.name,
data: dataForPut
}).success(function (data, status, headers, config) {
$modalInstance.close(true);
$scope.status.loading = false;
}).error(function (data, status, headers, config) {
$modalInstance.close(false);
$scope.status.loading = false;
});
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
flowableAdminApp.controller('DeleteVariableCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'variable', 'processInstanceId',
function ($rootScope, $scope, $modalInstance, $http, variable, processInstanceId) {
$scope.status = {loading: false};
$scope.variable = variable;
$scope.deleteVariable = function () {
$http({
method: 'DELETE',
url: '/app/rest/admin/process-instances/' + processInstanceId + '/variables/' + $scope.variable.name
}).success(function (data, status, headers, config) {
$modalInstance.close(true);
$scope.status.loading = false;
}).error(function (data, status, headers, config) {
$modalInstance.close(false);
$scope.status.loading = false;
});
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
flowableAdminApp.controller('AddVariableCtrl',
['$rootScope', '$scope', '$modalInstance', '$http', 'processInstanceId',
function ($rootScope, $scope, $modalInstance, $http, processInstanceId) {
$scope.status = {loading: false};
$scope.types = [
"string",
"boolean",
"date",
"double",
"integer",
"long",
"short"
];
$scope.newVariable = {};
$scope.createVariable = function () {
var data = {
name: $scope.newVariable.name,
type: $scope.newVariable.type,
};
if ($scope.newVariable.type === 'string') {
data.value = $scope.newVariable.value;
} else if ($scope.newVariable.type === 'boolean') {
if ($scope.newVariable.value) {
data.value = true;
} else {
data.value = false;
}
} else if ($scope.newVariable.type === 'date') {
data.value = $scope.newVariable.value;
} else if ($scope.newVariable.type === 'double'
|| $scope.newVariable.type === 'long'
|| $scope.newVariable.type === 'integer'
|| $scope.newVariable.type === 'short') {
data.value = Number($scope.newVariable.value);
}
$http({
method: 'POST',
url: '/app/rest/admin/process-instances/' + processInstanceId + '/variables',
data: data
}).success(function (data, status, headers, config) {
$modalInstance.close(true);
$scope.status.loading = false;
}).error(function (data, status, headers, config) {
$modalInstance.close(false);
$scope.status.loading = false;
});
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
|
marcus-nl/flowable-engine
|
modules/flowable-ui-admin/flowable-ui-admin-app/src/main/webapp/scripts/process-instance-controllers.js
|
JavaScript
|
apache-2.0
| 29,675 |
/*
Copyright 2006-2017 Cryptany, 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.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Cryptany.Core.DPO.MetaObjects.Attributes;
namespace Cryptany.Core.ConfigOM
{
[Serializable]
[DbSchema("services")]
[Table("Channels", "ServiceID", ConditionOperation.Equals, "44771D42-3C46-4FDA-B415-8CC8FC8C8DEC")]
public class CashChannel : Channel
{
}
}
|
erupakov/legacy
|
Core/Cryptany.Core.ConfigOM/CashChannel.cs
|
C#
|
apache-2.0
| 979 |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SimpleWorkflow.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleWorkflow.Model.Internal.MarshallTransformations
{
/// <summary>
/// Start Workflow Execution Request Marshaller
/// </summary>
internal class StartWorkflowExecutionRequestMarshaller : IMarshaller<IRequest, StartWorkflowExecutionRequest>
{
public IRequest Marshall(StartWorkflowExecutionRequest startWorkflowExecutionRequest)
{
IRequest request = new DefaultRequest(startWorkflowExecutionRequest, "AmazonSimpleWorkflow");
string target = "SimpleWorkflowService.StartWorkflowExecution";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.0";
string uriResourcePath = "";
if (uriResourcePath.Contains("?"))
{
string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));
foreach (string s in queryString.Split('&', ';'))
{
string[] nameValuePair = s.Split('=');
if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
{
request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
}
else
{
request.Parameters.Add(nameValuePair[0], null);
}
}
}
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter())
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
if (startWorkflowExecutionRequest != null && startWorkflowExecutionRequest.IsSetDomain())
{
writer.WritePropertyName("domain");
writer.Write(startWorkflowExecutionRequest.Domain);
}
if (startWorkflowExecutionRequest != null && startWorkflowExecutionRequest.IsSetWorkflowId())
{
writer.WritePropertyName("workflowId");
writer.Write(startWorkflowExecutionRequest.WorkflowId);
}
if (startWorkflowExecutionRequest != null)
{
WorkflowType workflowType = startWorkflowExecutionRequest.WorkflowType;
if (workflowType != null)
{
writer.WritePropertyName("workflowType");
writer.WriteObjectStart();
if (workflowType != null && workflowType.IsSetName())
{
writer.WritePropertyName("name");
writer.Write(workflowType.Name);
}
if (workflowType != null && workflowType.IsSetVersion())
{
writer.WritePropertyName("version");
writer.Write(workflowType.Version);
}
writer.WriteObjectEnd();
}
}
if (startWorkflowExecutionRequest != null)
{
TaskList taskList = startWorkflowExecutionRequest.TaskList;
if (taskList != null)
{
writer.WritePropertyName("taskList");
writer.WriteObjectStart();
if (taskList != null && taskList.IsSetName())
{
writer.WritePropertyName("name");
writer.Write(taskList.Name);
}
writer.WriteObjectEnd();
}
}
if (startWorkflowExecutionRequest != null && startWorkflowExecutionRequest.IsSetInput())
{
writer.WritePropertyName("input");
writer.Write(startWorkflowExecutionRequest.Input);
}
if (startWorkflowExecutionRequest != null && startWorkflowExecutionRequest.IsSetExecutionStartToCloseTimeout())
{
writer.WritePropertyName("executionStartToCloseTimeout");
writer.Write(startWorkflowExecutionRequest.ExecutionStartToCloseTimeout);
}
if (startWorkflowExecutionRequest != null && startWorkflowExecutionRequest.TagList != null && startWorkflowExecutionRequest.TagList.Count > 0)
{
List<string> tagListList = startWorkflowExecutionRequest.TagList;
writer.WritePropertyName("tagList");
writer.WriteArrayStart();
foreach (string tagListListValue in tagListList)
{
writer.Write(StringUtils.FromString(tagListListValue));
}
writer.WriteArrayEnd();
}
if (startWorkflowExecutionRequest != null && startWorkflowExecutionRequest.IsSetTaskStartToCloseTimeout())
{
writer.WritePropertyName("taskStartToCloseTimeout");
writer.Write(startWorkflowExecutionRequest.TaskStartToCloseTimeout);
}
if (startWorkflowExecutionRequest != null && startWorkflowExecutionRequest.IsSetChildPolicy())
{
writer.WritePropertyName("childPolicy");
writer.Write(startWorkflowExecutionRequest.ChildPolicy);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
}
}
|
emcvipr/dataservices-sdk-dotnet
|
AWSSDK/Amazon.SimpleWorkflow/Model/Internal/MarshallTransformations/StartWorkflowExecutionRequestMarshaller.cs
|
C#
|
apache-2.0
| 7,086 |
/*
* 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 app.metatron.discovery.domain.datasource;
import java.util.List;
import app.metatron.discovery.common.criteria.ListFilterRequest;
/**
*
*/
public class DataSourceFilterRequest extends ListFilterRequest {
List<String> status;
List<String> workspace;
List<String> userGroup;
List<String> dataSourceType;
List<String> sourceType;
List<String> connectionType;
List<Boolean> published;
public List<String> getStatus() {
return status;
}
public void setStatus(List<String> status) {
this.status = status;
}
public List<String> getWorkspace() {
return workspace;
}
public void setWorkspace(List<String> workspace) {
this.workspace = workspace;
}
public List<String> getUserGroup() {
return userGroup;
}
public void setUserGroup(List<String> userGroup) {
this.userGroup = userGroup;
}
public List<String> getDataSourceType() {
return dataSourceType;
}
public void setDataSourceType(List<String> dataSourceType) {
this.dataSourceType = dataSourceType;
}
public List<String> getSourceType() {
return sourceType;
}
public void setSourceType(List<String> sourceType) {
this.sourceType = sourceType;
}
public List<String> getConnectionType() {
return connectionType;
}
public void setConnectionType(List<String> connectionType) {
this.connectionType = connectionType;
}
public List<Boolean> getPublished() {
return published;
}
public void setPublished(List<Boolean> published) {
this.published = published;
}
}
|
metatron-app/metatron-discovery
|
discovery-server/src/main/java/app/metatron/discovery/domain/datasource/DataSourceFilterRequest.java
|
Java
|
apache-2.0
| 2,116 |
package bincache
import (
"archive/zip"
"bytes"
"crypto/sha256"
"encoding/hex"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
)
// Download a file from url and check with a sha1
func Download(url string) (string, error) {
path, err := os.UserCacheDir()
if err != nil {
return "", err
}
path = filepath.Join(path, "concourse-up", "bin")
err = os.MkdirAll(path, 0700)
if err != nil {
return "", err
}
path = filepath.Join(path, hash(url))
if _, err = os.Stat(path); !os.IsNotExist(err) {
return path, nil
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0700)
if err != nil {
return "", err
}
defer f.Close()
resp, err := http.Get(url)
if err != nil {
os.Remove(path)
return "", err
}
defer resp.Body.Close()
var closer io.ReadCloser
// if strings.HasSuffix(url, ".zip") {
// closer, err = handleZipFile(resp)
// if err != nil {
// return "", nil
// }
// } else {
// closer = resp.Body
// }
if isZip(url, resp) {
closer, err = handleZipFile(resp)
if err != nil {
return "", nil
}
} else {
closer = resp.Body
}
_, err = io.Copy(f, closer)
if err != nil {
os.Remove(path)
return "", err
}
return path, nil
}
func handleZipFile(resp *http.Response) (io.ReadCloser, error) {
body, errz := ioutil.ReadAll(resp.Body)
if errz != nil {
return nil, errz
}
r, errz := zip.NewReader(bytes.NewReader(body), resp.ContentLength)
if errz != nil {
return nil, errz
}
firstFile, errz := r.File[0].Open()
if errz != nil {
return nil, errz
}
return firstFile, nil
}
func isZip(url string, resp *http.Response) bool {
if strings.HasSuffix(url, ".zip") {
return true
}
if resp.Header.Get("Content-Type") == "application/zip" {
return true
}
return false
}
func hash(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
|
EngineerBetter/concourse-up
|
util/bincache/bincache.go
|
GO
|
apache-2.0
| 1,871 |
/*
* Copyright 2005-2017 Dozer 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.
*/
package org.dozer;
import org.dozer.config.GlobalSettings;
import org.dozer.util.DozerConstants;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DozerInitializerTest extends AbstractDozerTest {
private DozerInitializer instance;
@Before
public void setUp() throws Exception {
instance = DozerInitializer.getInstance();
instance.destroy();
}
@After
public void tearDown() throws Exception {
instance.destroy();
}
@Test
public void testIsInitialized() {
assertFalse(instance.isInitialized());
instance.init();
assertTrue(instance.isInitialized());
instance.destroy();
assertFalse(instance.isInitialized());
}
@Test
public void testDoubleCalls() {
instance.destroy();
assertFalse(instance.isInitialized());
instance.init();
instance.init();
assertTrue(instance.isInitialized());
instance.destroy();
instance.destroy();
assertFalse(instance.isInitialized());
}
@Test(expected = MappingException.class)
public void testBeanIsMissing() {
GlobalSettings settings = mock(GlobalSettings.class);
when(settings.getClassLoaderName()).thenReturn(DozerConstants.DEFAULT_CLASS_LOADER_BEAN);
when(settings.getProxyResolverName()).thenReturn("no.such.class.Found");
instance.initialize(settings, getClass().getClassLoader());
fail();
}
@Test(expected = MappingException.class)
public void testBeanIsNotAssignable() {
GlobalSettings settings = mock(GlobalSettings.class);
when(settings.getClassLoaderName()).thenReturn("java.lang.String");
when(settings.getProxyResolverName()).thenReturn(DozerConstants.DEFAULT_PROXY_RESOLVER_BEAN);
instance.initialize(settings, getClass().getClassLoader());
fail();
}
}
|
STRiDGE/dozer
|
core/src/test/java/org/dozer/DozerInitializerTest.java
|
Java
|
apache-2.0
| 2,608 |
package algorithm.leet_76_90;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by songheng on 4/18/16.
*/
public class Subsets_78 {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
if(nums == null || nums.length ==0){
return res;
}
for(int i = 1 ; i <= nums.length ; i ++ ){
helper(res,new ArrayList<>(),0,nums.length - 1, i , nums);
}
res.add(new ArrayList<>());
return res ;
}
private void helper(List<List<Integer>> res , List<Integer> prev, int start ,int end , int remaining, int arr[]){
if(remaining == 0 ){
res.add(prev);
return;
}
for(int i = start ; i <= end - remaining + 1 ; i++){
List<Integer> curr = new ArrayList<>(prev);
curr.add(arr[i]);
helper(res,curr,i+1,end,remaining-1,arr);
}
prev = null;
}
}
|
songshu198907/LeetPractise
|
src/main/java/algorithm/leet_76_90/Subsets_78.java
|
Java
|
apache-2.0
| 1,032 |
import("etherpad.log");
import("plugins.openingDesign.hooks");
function openingDesignInit() {
this.hooks = ['modals', 'docbarItemsPad'];
this.description = 'openingDesign';
this.docbarItemsPad = hooks.docbarItemsPad;
this.modals = hooks.modals;
this.install = install;
this.uninstall = uninstall;
}
function install() {
log.info("Installing openingDesign");
}
function uninstall() {
log.info("Uninstalling openingDesign");
}
|
OpeningDesign/SketchSpace
|
etherpad/src/plugins/openingDesign/main.js
|
JavaScript
|
apache-2.0
| 437 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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
*
* 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.
*/
'use strict';
// MODULES //
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var incrmmean = require( '@stdlib/stats/incr/mmean' );
// MAIN //
/**
* Returns an accumulator function which incrementally computes a moving mean percentage error.
*
* @param {PositiveInteger} W - window size
* @throws {TypeError} must provide a positive integer
* @returns {Function} accumulator function
*
* @example
* var accumulator = incrmmpe( 3 );
*
* var m = accumulator();
* // returns null
*
* m = accumulator( 2.0, 3.0 );
* // returns ~33.33
*
* m = accumulator( 5.0, 2.0 );
* // returns ~-58.33
*
* m = accumulator( 3.0, 2.0 );
* // returns ~-55.56
*
* m = accumulator( 2.0, 5.0 );
* // returns ~-46.67
*
* m = accumulator();
* // returns ~-46.67
*/
function incrmmpe( W ) {
var mean;
if ( !isPositiveInteger( W ) ) {
throw new TypeError( 'invalid argument. Must provide a positive integer. Value: `' + W + '`.' );
}
mean = incrmmean( W );
return accumulator;
/**
* If provided input values, the accumulator function returns an updated mean percentage error. If not provided input values, the accumulator function returns the current mean percentage error.
*
* @private
* @param {number} [f] - input value
* @param {number} [a] - input value
* @returns {(number|null)} mean percentage error or null
*/
function accumulator( f, a ) {
if ( arguments.length === 0 ) {
return mean();
}
return mean( 100.0 * ((a-f)/a) );
}
}
// EXPORTS //
module.exports = incrmmpe;
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/stats/incr/mmpe/lib/main.js
|
JavaScript
|
apache-2.0
| 2,139 |
package v1
import (
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1"
)
// ProjectList is a list of Project objects.
type ProjectList struct {
kapi.TypeMeta `json:",inline"`
kapi.ListMeta `json:"metadata,omitempty"`
Items []Project `json:"items"`
}
// These are internal finalizer values to Origin
const (
FinalizerOrigin kapi.FinalizerName = "openshift.io/origin"
)
// ProjectSpec describes the attributes on a Project
type ProjectSpec struct {
// Finalizers is an opaque list of values that must be empty to permanently remove object from storage
Finalizers []kapi.FinalizerName `json:"finalizers,omitempty" description:"an opaque list of values that must be empty to permanently remove object from storage"`
}
// ProjectStatus is information about the current status of a Project
type ProjectStatus struct {
Phase kapi.NamespacePhase `json:"phase,omitempty" description:"phase is the current lifecycle phase of the project"`
}
// Project is a logical top-level container for a set of origin resources
type Project struct {
kapi.TypeMeta `json:",inline"`
kapi.ObjectMeta `json:"metadata,omitempty"`
// Spec defines the behavior of the Namespace.
Spec ProjectSpec `json:"spec,omitempty" description:"spec defines the behavior of the Project"`
// Status describes the current status of a Namespace
Status ProjectStatus `json:"status,omitempty" description:"status describes the current status of a Project; read-only"`
}
type ProjectRequest struct {
kapi.TypeMeta `json:",inline"`
kapi.ObjectMeta `json:"metadata,omitempty"`
DisplayName string `json:"displayName,omitempty"`
}
|
hingstarne/origin
|
pkg/project/api/v1/types.go
|
GO
|
apache-2.0
| 1,629 |
#
# 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.
#
'''
Example main program for ESGF-RCMES integration.
'''
# constant parameters
DATA_DIRECTORY = "/tmp"
from ocw.esgf.logon import logon
from ocw.esgf.search import SearchClient
from ocw.esgf.download import download
def main():
'''Example driver program'''
username = raw_input('Enter your ESGF Username:\n')
password = raw_input('Enter your ESGF Password:\n')
# step 1: obtain short-term certificate
print 'Retrieving ESGF certificate...'
# logon using client-side MyProxy libraries
if logon(username, password):
print "...done."
# step 2: execute faceted search for files
urls = main_obs4mips()
#urls = main_cmip5()
# step 3: download file(s)
for i, url in enumerate(urls):
if i>=1:
break
download(url, toDirectory=DATA_DIRECTORY)
def main_cmip5():
'''
Example workflow to search for CMIP5 files
'''
searchClient = SearchClient(searchServiceUrl="http://pcmdi9.llnl.gov/esg-search/search", distrib=False)
print '\nAvailable projects=%s' % searchClient.getFacets('project')
searchClient.setConstraint(project='CMIP5')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable models=%s' % searchClient.getFacets('model')
searchClient.setConstraint(model='INM-CM4')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable experiments=%s' % searchClient.getFacets('experiment')
searchClient.setConstraint(experiment='historical')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable time frequencies=%s' % searchClient.getFacets('time_frequency')
searchClient.setConstraint(time_frequency='mon')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable CF standard names=%s' % searchClient.getFacets('cf_standard_name')
searchClient.setConstraint(cf_standard_name='air_temperature')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
urls = searchClient.getFiles()
return urls
def main_obs4mips():
'''
Example workflow to search for obs4MIPs files.
'''
searchClient = SearchClient(distrib=False)
# obs4MIPs
print '\nAvailable projects=%s' % searchClient.getFacets('project')
searchClient.setConstraint(project='obs4MIPs')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable variables=%s' % searchClient.getFacets('variable')
searchClient.setConstraint(variable='hus')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable time frequencies=%s' % searchClient.getFacets('time_frequency')
searchClient.setConstraint(time_frequency='mon')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
print '\nAvailable models=%s' % searchClient.getFacets('model')
searchClient.setConstraint(model='Obs-MLS')
print "Number of Datasets=%d" % searchClient.getNumberOfDatasets()
urls = searchClient.getFiles()
return urls
if __name__ == '__main__':
main()
|
MBoustani/climate
|
ocw/esgf/main.py
|
Python
|
apache-2.0
| 3,986 |
package org.schema.api.model.thing.creativeWork.article.newsArticle;
public class ReviewNewsArticle extends NewsArticle
{
}
|
omindra/schema_org_java_api
|
core_with_extensions/src/main/java/org/schema/api/model/thing/creativeWork/article/newsArticle/ReviewNewsArticle.java
|
Java
|
apache-2.0
| 124 |
/**
*
* @author greg (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.control;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.myrobotlab.logging.LoggerFactory;
import javax.swing.JTabbedPane;
import org.myrobotlab.service.Proxy;
import org.myrobotlab.service.GUIService;
import org.slf4j.Logger;
public class ProxyGUI extends ServiceGUI implements ActionListener {
static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(ProxyGUI.class.getCanonicalName());
public ProxyGUI(final String boundServiceName, final GUIService myService, final JTabbedPane tabs) {
super(boundServiceName, myService, tabs);
}
public void init() {
}
public void getState(Proxy template) {
}
@Override
public void attachGUI() {
//subscribe("publishState", "getState", _TemplateServiceGUI.class);
myService.send(boundServiceName, "publishState");
}
@Override
public void detachGUI() {
//unsubscribe("publishState", "getState", _TemplateServiceGUI.class);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
|
DarkRebel/myrobotlab
|
src/org/myrobotlab/control/ProxyGUI.java
|
Java
|
apache-2.0
| 2,022 |
class Timecop
# A data class for carrying around "time movement" objects. Makes it easy to keep track of the time
# movements on a simple stack.
class TimeStackItem #:nodoc:
attr_reader :mock_type
def initialize(mock_type, *args)
raise "Unknown mock_type #{mock_type}" unless [:freeze, :travel].include?(mock_type)
@mock_type = mock_type
@time = parse_time(*args)
@travel_offset = compute_travel_offset
@dst_adjustment = compute_dst_adjustment(@time)
end
def year
time.year
end
def month
time.month
end
def day
time.day
end
def hour
time.hour
end
def min
time.min
end
def sec
time.sec
end
def utc_offset
time.utc_offset
end
def travel_offset
@travel_offset
end
def time(time_klass=Time) #:nodoc:
if travel_offset.nil?
time_klass.at( @time.to_f )
else
time_klass.at( ( Time.now_without_mock_time + travel_offset ).to_f )
end
end
def date(date_klass=Date)
date_klass.jd( time.to_date.jd )
end
def datetime(datetime_klass=DateTime)
# DateTime doesn't know about DST, so let's remove its presence
our_offset = utc_offset + dst_adjustment
fractions_of_a_second = time.to_f % 1
datetime_klass.new(year, month, day, hour, min, sec + fractions_of_a_second,
utc_offset_to_rational(our_offset))
end
def dst_adjustment
@dst_adjustment
end
private
def rational_to_utc_offset(rational)
((24.0 / rational.denominator) * rational.numerator) * (60 * 60)
end
def utc_offset_to_rational(utc_offset)
Rational(utc_offset, 24 * 60 * 60)
end
def parse_time(*args)
time_klass = Time
time_klass = Time.zone if Time.respond_to? :zone
arg = args.shift
if arg.is_a?(Time)
if Timecop.active_support != false && arg.respond_to?(:in_time_zone)
arg.in_time_zone
else
arg.getlocal
end
elsif Object.const_defined?(:DateTime) && arg.is_a?(DateTime)
expected_time = time_klass.local(arg.year, arg.month, arg.day, arg.hour, arg.min, arg.sec)
expected_time += expected_time.utc_offset - rational_to_utc_offset(arg.offset)
expected_time + compute_dst_adjustment(expected_time)
elsif Object.const_defined?(:Date) && arg.is_a?(Date)
time_klass.local(arg.year, arg.month, arg.day, 0, 0, 0)
elsif args.empty? && arg.kind_of?(Integer)
Time.now + arg
elsif arg.nil?
Time.now
else
if arg.is_a?(String) && Timecop.active_support != false && Time.respond_to?(:parse)
Time.parse(arg)
else
# we'll just assume it's a list of y/m/d/h/m/s
year = arg || 2000
month = args.shift || 1
day = args.shift || 1
hour = args.shift || 0
minute = args.shift || 0
second = args.shift || 0
time_klass.local(year, month, day, hour, minute, second)
end
end
end
def compute_dst_adjustment(time)
return 0 if !(time.dst? ^ Time.now.dst?)
return -1 * 60 * 60 if time.dst?
return 60 * 60
end
def compute_travel_offset
return nil if mock_type == :freeze
time - Time.now_without_mock_time
end
end
end
|
masukomi/mobtvse
|
vendor/bundle/gems/timecop-0.4.5/lib/timecop/time_stack_item.rb
|
Ruby
|
apache-2.0
| 3,600 |
from datetime import datetime
from bson import ObjectId
class SettingsService(object):
def __init__(self, db):
self.db = db
self.settings = db.settings_collection
self._id = ObjectId("5bbbaee7bacf833c1203d7b3")
def save(self, item):
item['_id'] = self._id
item['created_at'] = datetime.now()
item['status'] = True
return self.settings.save(item)
def get(self):
return self.settings.find_one({'_id': self._id})
|
cackharot/fbeazt
|
src/foodbeazt/service/SettingsService.py
|
Python
|
apache-2.0
| 491 |
/*
* Copyright (c) 2010-2015 Evolveum
*
* 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.evolveum.midpoint.web.page.admin.resources;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismProperty;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.query.*;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.security.api.AuthorizationConstants;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.page.admin.PageAdmin;
import com.evolveum.midpoint.web.page.admin.resources.dto.ResourceDto;
import com.evolveum.midpoint.web.util.OnePageParameterEncoder;
import com.evolveum.midpoint.web.util.WebMiscUtil;
import com.evolveum.midpoint.web.util.WebModelUtils;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.string.StringValue;
import java.util.Collection;
import java.util.List;
/**
* @author lazyman
*/
public class PageAdminResources extends PageAdmin {
private static final String DOT_CLASS = PageAdminResources.class.getName() + ".";
private static final String OPERATION_LOAD_RESOURCE = DOT_CLASS + "loadResource";
private static final String OPERATION_DELETE_SYNC_TOKEN = DOT_CLASS + "deleteSyncToken";
private static final String OPERATION_SAVE_SYNC_TASK = DOT_CLASS + "saveSyncTask";
protected static final Trace LOGGER = TraceManager.getTrace(PageAdminResources.class);
public static final String AUTH_RESOURCE_ALL = AuthorizationConstants.AUTZ_UI_RESOURCES_ALL_URL;
public static final String AUTH_RESOURCE_ALL_LABEL = "PageAdminResources.auth.resourcesAll.label";
public static final String AUTH_RESOURCE_ALL_DESCRIPTION = "PageAdminResources.auth.resourcesAll.description";
protected boolean isResourceOidAvailable() {
StringValue resourceOid = getPageParameters().get(OnePageParameterEncoder.PARAMETER);
return resourceOid != null && StringUtils.isNotEmpty(resourceOid.toString());
}
protected String getResourceOid() {
StringValue resourceOid = getPageParameters().get(OnePageParameterEncoder.PARAMETER);
return resourceOid != null ? resourceOid.toString() : null;
}
protected PrismObject<ResourceType> loadResource(Collection<SelectorOptions<GetOperationOptions>> options) {
OperationResult result = new OperationResult(OPERATION_LOAD_RESOURCE);
PrismObject<ResourceType> resource = null;
try {
Task task = createSimpleTask(OPERATION_LOAD_RESOURCE);
LOGGER.trace("getObject(resource) oid={}, options={}", getResourceOid(), options);
resource = getModelService().getObject(ResourceType.class, getResourceOid(), options, task, result);
result.recomputeStatus();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("getObject(resource) result\n:{}", result.debugDump());
}
} catch (Exception ex) {
LoggingUtils.logException(LOGGER, "Couldn't get resource", ex);
result.recordFatalError("Couldn't get resource, reason: " + ex.getMessage(), ex);
}
if (!WebMiscUtil.isSuccessOrHandledError(result)) {
if (resource != null) {
showResult(result);
} else {
getSession().error(getString("pageAdminResources.message.cantLoadResource"));
throw new RestartResponseException(PageResources.class);
}
}
return resource;
}
protected void deleteSyncTokenPerformed(AjaxRequestTarget target, IModel<ResourceDto> model){
ResourceDto dto = model.getObject();
String resourceOid = dto.getOid();
String handlerUri = "http://midpoint.evolveum.com/xml/ns/public/model/synchronization/task/live-sync/handler-3";
ObjectReferenceType resourceRef = new ObjectReferenceType();
resourceRef.setOid(resourceOid);
PrismObject<TaskType> oldTask;
OperationResult result = new OperationResult(OPERATION_DELETE_SYNC_TOKEN);
ObjectQuery query;
ObjectFilter refFilter = RefFilter.createReferenceEqual(TaskType.F_OBJECT_REF, TaskType.class,
getPrismContext(), resourceOid);
ObjectFilter filterHandleUri = EqualFilter.createEqual(TaskType.F_HANDLER_URI, TaskType.class,
getPrismContext(), null, handlerUri);
query = new ObjectQuery();
query.setFilter(AndFilter.createAnd(refFilter, filterHandleUri));
List<PrismObject<TaskType>> taskList = WebModelUtils.searchObjects(TaskType.class, query,
result, this);
if(taskList.size() != 1){
error(getString("pageResource.message.invalidTaskSearch"));
} else {
oldTask = taskList.get(0);
saveTask(oldTask, result);
}
result.recomputeStatus();
showResult(result);
target.add(getFeedbackPanel());
}
private void saveTask(PrismObject<TaskType> oldTask, OperationResult result){
Task task = createSimpleTask(OPERATION_SAVE_SYNC_TASK);
PrismProperty property = oldTask.findProperty(new ItemPath(TaskType.F_EXTENSION, SchemaConstants.SYNC_TOKEN));
if(property == null){
return;
}
Object value = property.getRealValue();
ObjectDelta<TaskType> delta = ObjectDelta.createModifyDelta(oldTask.getOid(),
PropertyDelta.createModificationDeleteProperty(new ItemPath(TaskType.F_EXTENSION, SchemaConstants.SYNC_TOKEN), property.getDefinition(), value),
TaskType.class, getPrismContext());
if(LOGGER.isTraceEnabled()){
LOGGER.trace(delta.debugDump());
}
try {
getModelService().executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);
} catch (Exception e){
LoggingUtils.logException(LOGGER, "Couldn't save task.", e);
result.recordFatalError("Couldn't save task.", e);
}
result.recomputeStatus();
}
}
|
gureronder/midpoint
|
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageAdminResources.java
|
Java
|
apache-2.0
| 7,479 |
import { of } from 'rxjs';
import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { DomainService } from 'app/services/domain/domain.service';
import { GeneralModalService } from 'app/services/general-modal/general-modal.service';
import { MessageModal } from 'app/models/message-modal';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class DomainGuard implements CanActivate {
constructor(private domainService: DomainService, private generalModalService: GeneralModalService) { }
canActivate() {
return this.domainService.getDomains().pipe(
map(domain => true),
catchError(() => {
this.generalModalService.triggerMessage(new MessageModal(
'There was an error, please contact with your administrator', 'There was an error getting Domains'
));
return of(false);
})
);
}
}
|
BVier/Taskana
|
web/src/app/guards/domain.guard.ts
|
TypeScript
|
apache-2.0
| 907 |
# vim: et
require_relative 'base'
module Tui module Model
# Model for floating point number objects.
class Float < Base
# Constructor.
public
def initialize ( label, value = 0.0, ro = false )
super( label, value, ro )
if not ro
self.value = value # validation step
end
end # initialize
# Check if the provided value is indeed a floating point number.
# @override
public
def valid? ( value )
return value.is_a? ::Float
end # valid?
# @overriden
public
def from_s ( value )
self.value= Float( value )
end # from_s
end # Float
end # ::Model
end # ::Tui
|
giorno/tui
|
src/model/float.rb
|
Ruby
|
apache-2.0
| 656 |
/**
*
*/
package net.java.dev.blog.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.java.dev.blog.security.ui.SecurityContextUtil;
import net.java.dev.blog.service.Blog;
import net.java.dev.blog.service.BlogService;
import net.java.dev.blog.service.Label;
import net.java.dev.blog.service.ManagerService;
import net.java.dev.blog.service.User;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
/**
* @author Jeff.Yu
*
*/
public class BlogManagerController extends MultiActionController {
private BlogService blogService;
private ManagerService managerService;
public ModelAndView getBlog(HttpServletRequest request, HttpServletResponse response) throws Exception {
String blogId = request.getParameter("blogID");
if (blogId == null || "".equals(blogId)) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("allLabels", blogService.getLabels());
return new ModelAndView("manager/blog", data);
} else {
Blog blog = blogService.getBlog(Long.valueOf(blogId));
StringBuffer blogLabels = new StringBuffer();
for(Label label : blog.getLabels()) {
blogLabels.append(label.getLabelName());
blogLabels.append(",");
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("blog", blog);
data.put("blogLabels", blogLabels.toString());
data.put("allLabels", blogService.getLabels());
return new ModelAndView("manager/blog", data);
}
}
public ModelAndView removeBlog(HttpServletRequest request, HttpServletResponse response) throws Exception {
String blogId = request.getParameter("blogID");
User currentUser = SecurityContextUtil.getBloggingUser();
managerService.removeBlog(Long.valueOf(blogId), currentUser);
return new ModelAndView("redirect:index.do");
}
public ModelAndView removeComment(HttpServletRequest request, HttpServletResponse response) throws Exception {
String blogId = request.getParameter("blogID");
String commentId = request.getParameter("commentID");
managerService.removeComment(Long.valueOf(commentId));
return new ModelAndView("redirect:editBlog.do?blogID=" + blogId);
}
public void setBlogService(BlogService blogService) {
this.blogService = blogService;
}
public void setManagerService(ManagerService managerService) {
this.managerService = managerService;
}
}
|
jeffyu/blogging
|
ims-web/src/main/java/net/java/dev/blog/action/BlogManagerController.java
|
Java
|
apache-2.0
| 2,522 |
import React from 'react'
import PropTypes from 'prop-types'
import Immutable from 'immutable'
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
import NavigationPrompt from 'react-router-navigation-prompt'
import Switch from 'react-bootstrap-switch'
import {
generateUnique,
templateNameRenderer,
filterOsByArchitecture,
findOsByName,
isWindows,
} from '_/helpers'
import { isRunning, getVmIconId, isValidOsIcon, isVmNameValid } from '../utils'
import style from './style.css'
import sharedStyle from '../sharedStyle.css'
import CloudInitEditor from '../CloudInitEditor'
import DetailContainer from '../DetailContainer'
import IconUpload from './IconUpload'
import ErrorAlert from '../ErrorAlert'
import FieldHelp from '../FieldHelp'
import NavigationConfirmationModal from '../NavigationConfirmationModal'
import SelectBox from '../SelectBox'
import VmIcon from '../VmIcon'
import timezones from '_/components/utils/timezones.json'
import { createVm, editVm } from '_/actions'
import { MAX_VM_MEMORY_FACTOR } from '_/constants'
import { msg } from '_/intl'
const zeroUID = '00000000-0000-0000-0000-000000000000'
const FIRST_DEVICE = 0
const SECOND_DEVICE = 1
const defaultDevices = ['hd', null]
class VmDialog extends React.Component {
constructor (props) {
super(props)
this.state = {
correlationId: '',
id: undefined,
name: '',
description: '',
cpus: 1,
memory: 1024 * 1024 * 1024,
cdrom: {
fileId: '',
},
clusterId: undefined,
templateId: undefined,
osId: undefined,
bootDevices: defaultDevices,
saved: false,
isChanged: false,
bootMenuEnabled: false,
cloudInit: {
enabled: false,
hostName: '',
sshAuthorizedKeys: '',
},
icon: {
id: undefined,
mediaType: undefined,
data: undefined,
},
uiErrors: {
icon: undefined,
},
timeZone: null,
}
this.submitHandler = this.submitHandler.bind(this)
this.initDefaults = this.initDefaults.bind(this)
this.onIntegerChanged = this.onIntegerChanged.bind(this)
this.getMemoryPolicy = this.getMemoryPolicy.bind(this)
this.getCluster = this.getCluster.bind(this)
this.getTemplate = this.getTemplate.bind(this)
this.getOS = this.getOS.bind(this)
this.getOsIdFromType = this.getOsIdFromType.bind(this)
this.checkTimeZone = this.checkTimeZone.bind(this)
this.onChangeCluster = this.onChangeCluster.bind(this)
this.onChangeTemplate = this.onChangeTemplate.bind(this)
this.doChangeTemplateIdTo = this.doChangeTemplateIdTo.bind(this)
this.onChangeOperatingSystem = this.onChangeOperatingSystem.bind(this)
this.doChangeOsIdTo = this.doChangeOsIdTo.bind(this)
this.onChangeVmName = this.onChangeVmName.bind(this)
this.onChangeVmDescription = this.onChangeVmDescription.bind(this)
this.onChangeVmMemory = this.onChangeVmMemory.bind(this)
this.onChangeVmCpu = this.onChangeVmCpu.bind(this)
this.onChangeCD = this.onChangeCD.bind(this)
this.onChangeBootMenuEnabled = this.onChangeBootMenuEnabled.bind(this)
this.onChangeBootDevice = this.onChangeBootDevice.bind(this)
this.handleCloudInitChange = this.handleCloudInitChange.bind(this)
this.onIconChange = this.onIconChange.bind(this)
this.setUiError = this.setUiError.bind(this)
}
componentDidMount () {
const vm = this.props.vm
if (vm) { // 'edit' mode
const bootDevices = vm.getIn(['os', 'bootDevices']).toJS()
const resultDevices = []
for (let i = 0; i < defaultDevices.length; i++) {
resultDevices.push(bootDevices[i] ? bootDevices[i] : defaultDevices[i])
}
this.setState({
id: vm.get('id'),
name: vm.get('name'),
description: vm.get('description'),
cpus: vm.getIn(['cpu', 'vCPUs']),
memory: vm.getIn(['memory', 'total']),
clusterId: vm.getIn(['cluster', 'id']),
templateId: vm.getIn(['template', 'id']),
osId: this.getOsIdFromType(vm.getIn(['os', 'type'])),
bootDevices: resultDevices,
cdrom: {
fileId: null,
},
bootMenuEnabled: vm.get('bootMenuEnabled'),
cloudInit: vm.get('cloudInit').toJS(),
icon: {
id: getVmIconId(this.props.operatingSystems, vm),
mediaType: undefined,
data: undefined,
},
timeZone: null,
})
}
setTimeout(() => this.initDefaults(), 0)
}
static getDerivedStateFromProps (props, state) {
// If a user message correlating to the correlationId exists, the add/edit failed and
// the state should still be marked as isChanged to prevent page navigation.
if (props.userMessages.get('records').find(record => record.getIn([ 'failedAction', 'meta', 'correlationId' ]) === state.correlationId)) {
return { isChanged: true }
}
return null
}
setUiError (name, error) {
this.setState((prevState) => ({
uiErrors: Object.assign({}, prevState.uiErrors, {
[name]: error,
}),
}))
}
submitHandler (e) {
e.preventDefault()
const correlationId = generateUnique('vm-dialog-')
const template = this.getTemplate(this.state.templateId)
const clone = !!(template && template.get('type') === 'server')
this.props.vm
? this.props.updateVm(this.composeVm(), correlationId)
: this.props.addVm(this.composeVm(), correlationId, clone)
this.setState({
saved: true,
isChanged: false,
correlationId,
})
}
getLatestUserMessage () {
const { correlationId } = this.state
const filtered = this.props.userMessages
.get('records')
.filter(record => record.getIn([ 'failedAction', 'meta', 'correlationId' ]) === correlationId)
const last = filtered.last()
return last && last.get('message')
}
getMemoryPolicy () {
const cluster = this.getCluster()
const overCommitPercent = cluster && cluster.getIn(['memoryPolicy', 'overCommitPercent'])
let guaranteed = overCommitPercent ? (this.state.memory * (100 / overCommitPercent)) : this.state.memory
const memoryPolicy = {
'max': this.state.memory * MAX_VM_MEMORY_FACTOR,
'guaranteed': Math.round(guaranteed),
}
console.log('getMemoryPolicy() resulting memory_policy: ', memoryPolicy)
return memoryPolicy
}
/**
* Compose vm object from entered values
*
* Structure conforms vmToInternal()
*/
composeVm () {
// TODO: Here is the old compose!!
const os = this.props.operatingSystems.get(this.state.osId)
return {
'id': this.state.id,
'name': this.state.name,
'description': this.state.description,
'template': { 'id': this.state.templateId },
'cluster': { 'id': this.state.clusterId },
'memory': this.state.memory || 0,
'memory_policy': this.getMemoryPolicy(),
'cdrom': {
'fileId': this.state.cdrom.fileId === null ? '' : this.state.cdrom.fileId,
},
'os': {
'type': os ? os.get('name') : null,
'bootDevices': this.state.bootDevices || [],
},
'cpu': {
'topology': {
'cores': '1', // TODO: fix to conform topology in template!
'sockets': this.state.cpus || 1,
'threads': '1',
},
},
bootMenuEnabled: this.state.bootMenuEnabled,
cloudInit: this.state.cloudInit,
'status': this.props.vm ? this.props.vm.get('status') : '',
icons: {
large: {
id: this.state.icon.id,
media_type: this.state.icon.id ? undefined : this.state.icon.mediaType,
data: this.state.icon.id ? undefined : this.state.icon.data,
},
},
timeZone: this.state.timeZone,
}
}
onChangeVmName (event) {
const newName = event.target.value
const vmNameErrorText = isVmNameValid(newName)
? null
: msg.pleaseEnterValidVmName()
this.setState({ name: newName, isChanged: true, vmNameErrorText })
const template = this.getTemplate()
if (!template) {
return
}
const templateHostName = template.getIn(['cloudInit', 'hostName'])
if (templateHostName) {
return
}
this.setState(state => { state.cloudInit.hostName = newName })
}
onChangeVmDescription (event) {
this.setState({ description: event.target.value, isChanged: true })
}
onChangeVmMemory (event) {
this.onIntegerChanged({ stateProp: 'memory', value: event.target.value, factor: 1024 * 1024, isChanged: true })
}
onChangeVmCpu (event) {
this.onIntegerChanged({ stateProp: 'cpus', value: event.target.value })
}
onChangeCD (fileId) {
this.setState({ cdrom: { fileId }, isChanged: true })
}
onIntegerChanged ({ value, stateProp, factor = 1 }) {
let intVal = parseInt(value)
if (!isNaN(intVal)) {
value = intVal * factor
} else {
console.log('not an integer: ', value)
value = ''
}
const stateChange = {}
stateChange[stateProp] = value
stateChange['isChanged'] = true
this.setState(stateChange)
}
onChangeOperatingSystem (osId) {
this.doChangeOsIdTo(osId)
}
doChangeOsIdTo (osId) {
const os = this.props.operatingSystems.get(osId)
if (os) {
this.onChangeOsIconId(os.getIn(['icons', 'large', 'id']))
this.checkTimeZone({ osType: os.get('name') })
}
this.setState({
osId,
isChanged: true,
})
}
onChangeOsIconId (iconId) {
if (this.state.icon.id && isValidOsIcon(this.props.operatingSystems, this.state.icon.id)) { // change unless custom icon is selected
this.doChangeIconId(iconId)
}
}
checkTimeZone ({ osType }) {
const { config } = this.props
let timeZone = this.state.timeZone
const template = this.getTemplate()
if (template && template.getIn(['timeZone', 'name'])) {
timeZone = timeZone || template.get('timeZone').toJS()
}
const isWindowsTimeZone = timeZone && timezones.find(timezone => timezone.id === timeZone.name)
const isWindowsVm = isWindows(osType)
if (isWindowsVm && !isWindowsTimeZone) {
timeZone = {
name: config.get('defaultWindowsTimezone'),
}
}
if (!isWindowsVm && isWindowsTimeZone) {
timeZone = {
name: config.get('defaultGeneralTimezone'),
}
}
if (timeZone) {
this.setState({
timeZone,
})
}
}
doChangeIconId (iconId) {
this.setUiError('icon')
this.setState({
icon: {
id: iconId,
},
isChanged: true,
})
}
onIconChange (icon) {
if (icon) {
this.setUiError('icon')
this.setState({
icon,
isChanged: true,
})
} else {
// set default os icon
const os = this.getOS()
if (os) {
this.doChangeIconId(os.getIn(['icons', 'large', 'id']))
}
}
}
getOsIdFromType (type) {
const os = findOsByName(this.props.operatingSystems, type)
return os ? os.get('id') : undefined
}
/**
* @returns OperatingSystem object conforming this.state.osId
*/
getOS () {
const osId = this.state.osId
if (osId) {
const os = this.props.operatingSystems.get(osId)
if (os) {
return os
}
}
return undefined
}
/**
* User selected different template.
*/
onChangeTemplate (templateId) {
this.doChangeTemplateIdTo(templateId)
}
doChangeTemplateIdTo (templateId) {
const template = this.getTemplate(templateId)
let { memory, cpus, osId, cloudInit, bootMenuEnabled } = this.state
if (template) {
memory = template.get('memory')
cpus = template.getIn(['cpu', 'topology', 'cores'], 1) * template.getIn(['cpu', 'topology', 'sockets'], 1) * template.getIn(['cpu', 'topology', 'threads'], 1)
osId = this.getOsIdFromType(template.getIn(['os', 'type'], 'Blank'))
cloudInit = template.get('cloudInit').toJS()
bootMenuEnabled = template.get('bootMenuEnabled')
}
this.setState({
templateId,
memory,
cpus,
isChanged: true,
cloudInit,
bootMenuEnabled,
})
const osType = this.props.operatingSystems.getIn([ osId, 'name' ])
this.checkTimeZone({ osType })
if (this.state.osId !== osId) {
this.doChangeOsIdTo(osId)
}
// fire external data retrieval here if needed after Template change
}
/**
* @returns template object conforming this.state.templateId
*/
getTemplate (templateId) {
templateId = templateId || this.state.templateId
if (templateId) {
const template = this.props.templates.get(templateId)
if (template) {
return template
}
}
return undefined
}
/**
* User selected different cluster.
*/
onChangeCluster (clusterId) {
this.setState({
clusterId,
})
const template = this.getTemplate(this.state.templateId)
if (template && template.get('clusterId') && template.get('clusterId') !== clusterId) {
this.doChangeTemplateIdTo(zeroUID) // Careful: this.state.clusterId still contains previous clusterId, call setTimeout(function, 0) if needed otherwise
}
// fire external data retrieval here if needed after Cluster change
}
onChangeBootMenuEnabled (switchComponent, value) {
this.setState({ bootMenuEnabled: value })
}
/**
* @returns cluster object conforming this.state.clusterId
*/
getCluster () {
const clusterId = this.state.clusterId
if (clusterId) {
const cluster = this.props.clusters.get(clusterId)
if (cluster) {
return cluster
}
}
return undefined
}
getCDRomFileId () {
if (this.state.cdrom.fileId !== null) {
return this.state.cdrom.fileId
} else {
return this.props.vm.getIn(['cdrom', 'fileId']) || ''
}
}
initDefaults () {
const { clusters, templates, operatingSystems } = this.props
const stateChange = {}
const defaultClusterName = 'Default'
if (!this.getCluster()) {
const clustersList = clusters.toList()
const def = (clustersList.filter(item => item.get('name') === defaultClusterName).first()) || clustersList.first()
stateChange.clusterId = def ? def.get('id') : undefined
console.log(`VmDialog initDefaults(): Setting initial value for clusterId = ${this.state.clusterId} to ${stateChange.clusterId}`)
}
if (!this.getTemplate()) {
const def = templates.get(zeroUID) || this.props.templates.toList().first()
stateChange.templateId = def ? def.get('id') : undefined
console.log(`VmDialog initDefaults(): Setting initial value for templateId = ${this.state.templateId} to ${stateChange.templateId}`)
}
if (!this.getOS()) {
const osList = operatingSystems.toList()
const os = osList.sort((a, b) => a.get('id').localeCompare(b.get('id'))).first()
if (os) {
stateChange.osId = os.get('id')
stateChange.icon = {
id: os.getIn(['icons', 'large', 'id']),
}
}
console.log(`VmDialog initDefaults(): Setting initial value for osId = ${this.state.osId} to ${stateChange.osId}`)
}
if (this.getTemplate(stateChange.templateId).get('timeZone')) {
stateChange.timeZone = this.getTemplate(stateChange.templateId).get('timeZone').toJS()
console.log(`VmDialog initDefaults(): Setting initial value for timeZone = ${JSON.stringify(this.state.timeZone)} to ${JSON.stringify(stateChange.timeZone)}`)
}
this.setState(stateChange)
}
handleCloudInitChange (key) {
return (value) => {
this.setState((prevState) => {
return { cloudInit: Object.assign({}, prevState.cloudInit, { [key]: value }) }
})
}
}
onChangeBootDevice (id) {
return (device) => {
this.setState((prevState) => {
const copiedDevices = prevState.bootDevices.slice()
copiedDevices[id] = device
for (let i = id + 1; i < copiedDevices.length; i++) {
copiedDevices[i] = copiedDevices[i] === device ? null : copiedDevices[i]
}
return { bootDevices: copiedDevices }
})
}
}
render () {
const {
icons,
templates,
clusters,
storages,
previousPath,
operatingSystems,
} = this.props
const { bootDevices } = this.state
const vm = this.props.vm
const idPrefix = `vmdialog-${vm ? vm.get('name') : '_new'}`
const files = [{ id: '', value: '[Eject]' }]
storages.toList().forEach(storageDomain => {
const fileList = storageDomain.get('files')
if (fileList) {
files.push(...fileList.map(item => (
{ id: item['id'], value: item['name'] }
)))
}
})
const isEdit = !!vm
const isUp = (isEdit && isRunning(vm.get('status')))
const filteredTemplates = templates
.filter(template => template.get('clusterId') === this.state.clusterId || !template.get('clusterId'))
const cluster = this.getCluster()
const architecture = cluster && cluster.get('architecture')
const osMap = filterOsByArchitecture(operatingSystems, architecture)
const os = this.getOS()
const template = this.getTemplate()
const cdromFileId = this.getCDRomFileId()
const submitText = isEdit ? msg.updateVm() : msg.createVm()
const allowedBootDevices = ['hd', 'network', 'cdrom']
const dialogHeader = isEdit ? `${vm.get('name')} - ${msg.edit()}` : msg.createANewVm()
const icon = this.state.icon.id ? icons.get(this.state.icon.id) : Immutable.fromJS(this.state.icon)
const bootMenuHint = isUp
? (<React.Fragment>
{msg.bootMenuTooltip()}
<br />
<span className='pficon pficon-warning-triangle-o' />
{msg.bootMenuWarning()}
</React.Fragment>)
: msg.bootMenuTooltip()
const vmNameError = this.state.vmNameErrorText
? (<span className={`help-block ${style['error-text']}`}>{this.state.vmNameErrorText}</span>)
: null
return (
<div className='detail-container'><DetailContainer>
<h1 className={style['header']} id={`${idPrefix}-${isEdit ? 'edit' : 'create'}-title`}>
<VmIcon icon={icon} missingIconClassName='pficon pficon-virtual-machine' />
{dialogHeader}
</h1>
{this.getLatestUserMessage() && (<ErrorAlert message={this.getLatestUserMessage()} id={`${idPrefix}-erroralert`} />)}
<br />
<form>
<NavigationPrompt when={this.state.isChanged}>
{({ isActive, onConfirm, onCancel }) => (
<NavigationConfirmationModal show={isActive} onYes={onConfirm} onNo={onCancel} />
)}
</NavigationPrompt>
<div className={style['vm-dialog-container']}>
<dl className={sharedStyle['vm-properties']}>
<dt>
<FieldHelp content={msg.uniqueNameOfTheVirtualMachine()} text={msg.name()} />
</dt>
<dd className={this.state.vmNameErrorText ? 'has-error' : ''}>
<input
type='text'
className='form-control'
id='vmName'
placeholder={msg.enterVmName()}
onChange={this.onChangeVmName}
value={this.state.name || ''} />
{vmNameError}
</dd>
<dt>
<FieldHelp content={msg.optionalUserDescriptionOfVm()} text={msg.description()} />
</dt>
<dd>
<input
type='text'
className='form-control'
id='vmDescription'
placeholder={msg.enterVmDescription()}
onChange={this.onChangeVmDescription}
value={this.state.description || ''} />
</dd>
<dt>
<FieldHelp content={msg.groupOfHostsVmCanBeRunningOn()} text={msg.cluster()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeCluster}
selected={cluster ? cluster.get('id') : ''}
idPrefix='select-cluster'
sort
items={clusters.toList().map(item => (
{ id: item.get('id'), value: item.get('name') }
)).toJS()}
/>
</dd>
<dt>
<FieldHelp content={msg.containsConfigurationAndDisksWhichWillBeUsedToCreateThisVm()} text={msg.template()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeTemplate}
selected={template ? template.get('id') : ''}
idPrefix='select-template'
sort
items={filteredTemplates.toList().map(item => (
{ id: item.get('id'), value: templateNameRenderer(item) }
)).toJS()}
/>
</dd>
<dt>
<FieldHelp content={msg.operatingSystemInstalledOnVm()} text={msg.operatingSystem()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeOperatingSystem}
selected={os ? os.get('id') : ''}
idPrefix='select-os'
sort
items={osMap.toList().map(item => (
{ id: item.get('id'), value: item.get('description') }
)).toJS()}
/>
</dd>
<dt>
<span className='pficon pficon-memory' />
<FieldHelp content={msg.totalMemoryVmWillBeEquippedWith()} text={msg.definedMemory()} />
</dt>
<dd>
<input
type='number'
className='form-control'
id='vmMemory'
placeholder={msg.vmMemory()}
onChange={this.onChangeVmMemory}
value={this.state.memory / 1024 / 1024 || ''}
min={0}
step={256} />
</dd>
<dt>
<span className='pficon pficon-cpu' />
<FieldHelp content={msg.totalCountOfVirtualProcessorsVmWillBeEquippedWith()} text={msg.cpus()} />
</dt>
<dd>
<input
type='number'
className='form-control'
id='vmCpus'
placeholder={msg.cpus()}
onChange={this.onChangeVmCpu}
value={this.state.cpus || ''}
min={1}
step={1} />
</dd>
{ isEdit && (
<div> {/* this <div> is ugly anti-pattern and should be replaced by React.Fragment as soon as upgraded to React 16 */}
<dt>
<span className='pficon pficon-storage-domain' />
<FieldHelp content={msg.changeCd()} text={msg.cd()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeCD}
idPrefix='select-changecd'
selected={cdromFileId}
sort
items={files}
/>
</dd>
</div>
)}
<dt>
{
(isUp && vm.get('bootMenuEnabled') !== this.state.bootMenuEnabled) &&
<span className={'pficon pficon-warning-triangle-o ' + style['space-right']} />
}
<FieldHelp content={bootMenuHint} text={msg.bootMenu()} />
</dt>
<dd>
<Switch
animate
bsSize='mini'
value={!!this.state.bootMenuEnabled}
onChange={this.onChangeBootMenuEnabled}
/>
</dd>
<dt>
<FieldHelp content={msg.bootSequenceTooltip()} text={msg.bootSequence()} />
</dt>
<dd />
<div>
<dt className={style['field-shifted']}>
<FieldHelp content={msg.firstDeviceTooltip()} text={msg.firstDevice()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeBootDevice(FIRST_DEVICE)}
selected={bootDevices[FIRST_DEVICE]}
idPrefix='select-first-device'
items={allowedBootDevices.map(item => (
{ id: item, value: msg[`${item}Boot`]() }
))}
/>
</dd>
<dt className={style['field-shifted']}>
<FieldHelp content={msg.secondDeviceTooltip()} text={msg.secondDevice()} />
</dt>
<dd className={style['field-overflow-visible']}>
<SelectBox
onChange={this.onChangeBootDevice(SECOND_DEVICE)}
selected={bootDevices[SECOND_DEVICE]}
idPrefix='select-second-device'
items={[{ id: null, value: '[None]' }, ...allowedBootDevices.filter(item => (
item !== bootDevices[FIRST_DEVICE]
)).map(item => (
{ id: item, value: msg[`${item}Boot`]() }
))]}
/>
</dd>
</div>
<CloudInitEditor
enabled={this.state.cloudInit.enabled}
hostName={this.state.cloudInit.hostName}
sshAuthorizedKeys={this.state.cloudInit.sshAuthorizedKeys}
onEnabledChange={this.handleCloudInitChange('enabled')}
onHostNameChange={this.handleCloudInitChange('hostName')}
onSshAuthorizedKeysChange={this.handleCloudInitChange('sshAuthorizedKeys')}
/>
<IconUpload
onIconChange={this.onIconChange}
onErrorChange={(error) => this.setUiError('icon', error)}
error={this.state.uiErrors.icon} />
</dl>
</div>
<div className={style['vm-dialog-buttons']}>
<Link id='button-close' className='btn btn-default' to={previousPath}>{msg.close()}</Link>
<button id='button-submit' className='btn btn-primary' type='button' onClick={this.submitHandler}>{submitText}</button>
</div>
</form>
</DetailContainer></div>
)
}
}
VmDialog.propTypes = {
vm: PropTypes.object, // optional, VM object to edit
clusters: PropTypes.object.isRequired, // deep immutable, {[id: string]: Cluster}
templates: PropTypes.object.isRequired, // deep immutable, {[id: string]: Template}
operatingSystems: PropTypes.object.isRequired, // deep immutable, {[id: string]: OperatingSystem}
userMessages: PropTypes.object.isRequired,
icons: PropTypes.object.isRequired,
config: PropTypes.object.isRequired,
storages: PropTypes.object.isRequired, // deep immutable, {[id: string]: StorageDomain}
previousPath: PropTypes.string.isRequired,
addVm: PropTypes.func.isRequired,
updateVm: PropTypes.func.isRequired,
}
export default connect(
(state) => ({
clusters: state.clusters.filter(cluster => cluster.get('canUserUseCluster')),
templates: state.templates.filter(cluster => cluster.get('canUserUseTemplate')),
operatingSystems: state.operatingSystems,
userMessages: state.userMessages,
icons: state.icons,
storages: state.storageDomains,
config: state.config,
}),
(dispatch) => ({
addVm: (vm, correlationId, clone) => dispatch(createVm({ vm, pushToDetailsOnSuccess: true, clone }, { correlationId })),
updateVm: (vm, correlationId) => dispatch(editVm({ vm }, { correlationId })),
})
)(VmDialog)
|
mareklibra/userportal
|
src/components/VmDialog/index.js
|
JavaScript
|
apache-2.0
| 28,260 |
/* Copyright 2016 Sven van der Meer <vdmeer.sven@mykolab.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 de.vandermeer.skb.interfaces.coin;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.commons.lang3.text.StrBuilder;
import de.vandermeer.skb.interfaces.messagesets.IsErrorSet;
import de.vandermeer.skb.interfaces.render.DoesRender;
/**
* A tails (error) coin with a value and errors.
*
* @author Sven van der Meer <vdmeer.sven@mykolab.com>
* @version v0.0.2 build 170502 (02-May-17) for Java 1.8
* @since v0.0.1
*/
public interface TailsErrorWithErrors<R, M> extends TailsError<R>, IsErrorSet<M> {
@Override
default boolean reportsErrors(){
return true;
}
@Override
default boolean hasErrorReports(){
return this.hasErrors();
}
/**
* Renders the error set.
* The method uses {@link DoesRender} or simple toString to render errors.
* Each element in the error set is rendered in a single line, preceded by the type (error).
* @return rendered object
*/
@Override
default String render() {
StrBuilder ret = new StrBuilder(100);
for(M m : this.getErrorMessages()){
ret.append("errors: ");
if(m instanceof DoesRender){
ret.append(((DoesRender)m).render());
}
else{
ret.append(m);
}
ret.appendNewLine();
}
return ret.toString();
}
/**
* Creates a new error coin with given value and errors.
* @param <R> type of the return value
* @param <M> the message type for the set
* @param value the actual return value
* @return new error coin
*/
static <R, M> TailsErrorWithErrors<R, M> create(final R value){
return new TailsErrorWithErrors<R, M>() {
final Set<M> errorSet = new LinkedHashSet<>();
@Override
public Set<M> getErrorMessages() {
return this.errorSet;
}
@Override
public R getReturn() {
return value;
}
};
}
}
|
vdmeer/skb-java-interfaces
|
src/main/java/de/vandermeer/skb/interfaces/coin/TailsErrorWithErrors.java
|
Java
|
apache-2.0
| 2,493 |
package com.prom.by.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import android.os.Parcel;
import android.os.Parcelable;
@Element(name = "order")
public class Order implements Parcelable{
@Attribute (name = "id", required = false)
Long id;
@Attribute (name = "state", required = false)
String state;
@Element(name = "name", required = false)
String name;
@Element(name = "phone", required = false)
String phone;
@Element(name = "company", required = false)
String company;
@Element(name = "email", required = false)
String email;
@Element(name = "date", required = false)
String date;
@Element(name = "address", required = false)
String address;
@Element(name = "index", required = false)
String index;
@Element(name = "payercomment", required = false)
String payerComment;
@Element(name = "salescomment", required = false)
String salesComment;
@Element(name = "paymentType", required = false)
String paymentType;
@Element(name = "deliveryType", required = false)
String deliveryType;
@Element(name = "deliveryCost", required = false)
Double deliveryCost;
@Element(name = "priceBYR", required = false)
Double price;
@ElementList(name = "items", required = false)
List<Item> items;
public String getName() {
return name==null?"":name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getDeliveryType() {
return deliveryType;
}
public void setDeliveryType(String deliveryType) {
this.deliveryType = deliveryType;
}
public Double getDeliveryCost() {
return deliveryCost;
}
public void setDeliveryCost(Double deliveryCost) {
this.deliveryCost = deliveryCost;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public String getPayerComment() {
return payerComment;
}
public void setPayerComment(String payerComment) {
this.payerComment = payerComment;
}
public String getSalesComment() {
return salesComment;
}
public void setSalesComment(String salesComment) {
this.salesComment = salesComment;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Double getItemsTotalPrice () {
Double price = 0.0;
for (Item item: items) {
price += item.getPrice()==null?0.d:item.getPrice();
}
return price;
}
public String getAllItems () {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
builder.append(items.get(i).getName());
if (i != items.size() - 1) {
builder.append("; ");
}
}
return builder.toString();
}
public boolean itemSKUStartsWith (String prefix) {
for (Item item: items) {
if (item.getSku().toString().startsWith(prefix)) {
return true;
}
}
return false;
}
public boolean itemNameContains (String str) {
Locale locale = new Locale ("ru");
for (Item item: items) {
if (item.getName().toLowerCase(locale).contains(str)) {
return true;
}
}
return false;
}
@Override
public String toString () {
StringBuilder builder = new StringBuilder();
builder.append("{Name:");
builder.append(name);
builder.append(", Email : ");
builder.append(email);
builder.append(", Phone : ");
builder.append(phone);
for (Item item: items) {
builder.append("Item: ");
builder.append(item.toString());
}
builder.append("}\n");
return builder.toString();
}
@Override
public int describeContents() {
return id.hashCode();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
//have to write this way, as values can be null.
dest.writeValue(id);
dest.writeValue(state);
dest.writeValue(name);
dest.writeValue(phone);
dest.writeValue(company);
dest.writeValue(email);
dest.writeValue(date);
dest.writeValue(address);
dest.writeValue(index);
dest.writeValue(payerComment);
dest.writeValue(salesComment);
dest.writeValue(paymentType);
dest.writeValue(deliveryType);
dest.writeValue(deliveryCost);
dest.writeValue(price);
dest.writeList(items);
}
public static final Parcelable.Creator<Order> CREATOR = new Parcelable.Creator<Order>() {
@Override
public Order createFromParcel(Parcel in) {
return new Order(in);
}
@Override
public Order[] newArray(int size) {
return new Order[size];
}
};
public Order () {
}
public Order (Parcel parcel) {
id = (Long) parcel.readValue(Long.class.getClassLoader());
state =(String) parcel.readValue(String.class.getClassLoader());
name = (String)parcel.readValue(String.class.getClassLoader());
phone =(String) parcel.readValue(String.class.getClassLoader());
company =(String) parcel.readValue(String.class.getClassLoader());
email = (String)parcel.readValue(String.class.getClassLoader());
date = (String)parcel.readValue(String.class.getClassLoader());
address = (String)parcel.readValue(String.class.getClassLoader());
index = (String)parcel.readValue(String.class.getClassLoader());
payerComment = (String)parcel.readValue(String.class.getClassLoader());
salesComment = (String)parcel.readValue(String.class.getClassLoader());
paymentType = (String)parcel.readValue(String.class.getClassLoader());
deliveryType = (String)parcel.readValue(String.class.getClassLoader());
deliveryCost = (Double)parcel.readValue(Double.class.getClassLoader());
price = (Double) parcel.readValue(Double.class.getClassLoader());
items = new ArrayList<Item>();
parcel.readList(items, Item.class.getClassLoader());
}
}
|
cliffroot/prom.by
|
project/src/com/prom/by/model/Order.java
|
Java
|
apache-2.0
| 6,736 |
package io.github.lijunguan.imgselector.model.entity;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
/**
* Created by lijunguan on 2016/4/8
* email: lijunguan199210@gmail.com
* blog : https://lijunguan.github.io
*/
public class AlbumFolder implements Parcelable {
/**
* 相册目录的路径
*/
private String mPath;
/**
* 相册目录名
*/
private String mFloderName;
/**
* 目录下的所有图片集合
*/
private List<ImageInfo> mImgInfos;
/**
* 目录封面
*/
private ImageInfo mCover;
public String getPath() {
return mPath;
}
public void setPath(String mPath) {
this.mPath = mPath;
}
public String getFloderName() {
return mFloderName;
}
public void setFloderName(String mFloderName) {
this.mFloderName = mFloderName;
}
public List<ImageInfo> getImgInfos() {
return mImgInfos;
}
public void setImgInfos(List<ImageInfo> mImgInfos) {
this.mImgInfos = mImgInfos;
}
public ImageInfo getCover() {
return mCover;
}
public void setCover(ImageInfo mCover) {
this.mCover = mCover;
}
public AlbumFolder() {
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mPath);
dest.writeString(this.mFloderName);
dest.writeTypedList(mImgInfos);
dest.writeParcelable(this.mCover, flags);
}
protected AlbumFolder(Parcel in) {
this.mPath = in.readString();
this.mFloderName = in.readString();
this.mImgInfos = in.createTypedArrayList(ImageInfo.CREATOR);
this.mCover = in.readParcelable(ImageInfo.class.getClassLoader());
}
public static final Creator<AlbumFolder> CREATOR = new Creator<AlbumFolder>() {
@Override
public AlbumFolder createFromParcel(Parcel source) {
return new AlbumFolder(source);
}
@Override
public AlbumFolder[] newArray(int size) {
return new AlbumFolder[size];
}
};
}
|
lijunguan/AlbumSelector
|
imageseletor/src/main/java/io/github/lijunguan/imgselector/model/entity/AlbumFolder.java
|
Java
|
apache-2.0
| 2,209 |
/**
* Copyright 2017 The AMP HTML Authors. 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.
*/
import {HostServices} from '../../../src/inabox/host-services';
import {ScrollManager} from './scroll-manager';
import {Services} from '../../../src/services';
import {VisibilityManagerForMApp} from './visibility-manager-for-mapp';
import {
closestAncestorElementBySelector,
matches,
scopedQuerySelector,
} from '../../../src/dom';
import {dev, user, userAssert} from '../../../src/log';
import {getMode} from '../../../src/mode';
import {layoutRectLtwh} from '../../../src/layout-rect';
import {map} from '../../../src/utils/object';
import {provideVisibilityManager} from './visibility-manager';
import {tryResolve} from '../../../src/utils/promise';
import {whenContentIniLoad} from '../../../src/ini-load';
const TAG = 'amp-analytics/analytics-root';
/**
* An analytics root. Analytics can be scoped to either ampdoc, embed or
* an arbitrary AMP element.
*
* TODO(#22733): merge analytics root properties into ampdoc.
*
* @implements {../../../src/service.Disposable}
* @abstract
*/
export class AnalyticsRoot {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
/** @const */
this.ampdoc = ampdoc;
/** @const */
this.trackers_ = map();
/** @private {?./visibility-manager.VisibilityManager} */
this.visibilityManager_ = null;
/** @private {?./scroll-manager.ScrollManager} */
this.scrollManager_ = null;
/** @private {?Promise} */
this.usingHostAPIPromise_ = null;
/** @private {?../../../src/inabox/host-services.VisibilityInterface} */
this.hostVisibilityService_ = null;
}
/**
* @return {!Promise<boolean>}
*/
isUsingHostAPI() {
if (this.usingHostAPIPromise_) {
return this.usingHostAPIPromise_;
}
if (!HostServices.isAvailable(this.ampdoc)) {
this.usingHostAPIPromise_ = Promise.resolve(false);
} else {
// TODO: Using the visibility service and apply it for all tracking types
const promise = HostServices.visibilityForDoc(this.ampdoc);
this.usingHostAPIPromise_ = promise
.then(visibilityService => {
this.hostVisibilityService_ = visibilityService;
return true;
})
.catch(error => {
dev().fine(
TAG,
'VisibilityServiceError - fallback=' + error.fallback
);
if (error.fallback) {
// Do not use HostAPI, fallback to original implementation.
return false;
}
// Cannot fallback, service error. Throw user error.
throw user().createError('Host Visibility Service Error');
});
}
return this.usingHostAPIPromise_;
}
/** @override */
dispose() {
for (const k in this.trackers_) {
this.trackers_[k].dispose();
delete this.trackers_[k];
}
if (this.visibilityManager_) {
this.visibilityManager_.dispose();
}
if (this.scrollManager_) {
this.scrollManager_.dispose();
}
}
/**
* Returns the type of the tracker.
* @return {string}
* @abstract
*/
getType() {}
/**
* The root node the analytics is scoped to.
*
* @return {!Document|!ShadowRoot}
* @abstract
*/
getRoot() {}
/**
* The viewer of analytics root
* @return {!../../../src/service/viewer-interface.ViewerInterface}
*/
getViewer() {
return Services.viewerForDoc(this.ampdoc);
}
/**
* The root element within the analytics root.
*
* @return {!Element}
*/
getRootElement() {
const root = this.getRoot();
return dev().assertElement(root.documentElement || root.body || root);
}
/**
* The host element of the analytics root.
*
* @return {?Element}
* @abstract
*/
getHostElement() {}
/**
* The signals for the root.
*
* @return {!../../../src/utils/signals.Signals}
* @abstract
*/
signals() {}
/**
* Whether this analytics root contains the specified node.
*
* @param {!Node} node
* @return {boolean}
*/
contains(node) {
return this.getRoot().contains(node);
}
/**
* Returns the element with the specified ID in the scope of this root.
*
* @param {string} unusedId
* @return {?Element}
* @abstract
*/
getElementById(unusedId) {}
/**
* Returns the tracker for the specified name and list of allowed types.
*
* @param {string} name
* @param {!Object<string, typeof ./events.EventTracker>} whitelist
* @return {?./events.EventTracker}
*/
getTrackerForWhitelist(name, whitelist) {
const trackerProfile = whitelist[name];
if (trackerProfile) {
return this.getTracker(name, trackerProfile);
}
return null;
}
/**
* Returns the tracker for the specified name and type. If the tracker
* has not been requested before, it will be created.
*
* @param {string} name
* @param {typeof ./events.CustomEventTracker|typeof ./events.ClickEventTracker|typeof ./events.ScrollEventTracker|typeof ./events.SignalTracker|typeof ./events.IniLoadTracker|typeof ./events.VideoEventTracker|typeof ./events.VideoEventTracker|typeof ./events.VisibilityTracker|typeof ./events.AmpStoryEventTracker} klass
* @return {!./events.EventTracker}
*/
getTracker(name, klass) {
let tracker = this.trackers_[name];
if (!tracker) {
tracker = new klass(this);
this.trackers_[name] = tracker;
}
return tracker;
}
/**
* Returns the tracker for the specified name or `null`.
* @param {string} name
* @return {?./events.EventTracker}
*/
getTrackerOptional(name) {
return this.trackers_[name] || null;
}
/**
* Searches the element that matches the selector within the scope of the
* analytics root in relationship to the specified context node.
*
* @param {!Element} context
* @param {string} selector DOM query selector.
* @param {?string=} selectionMethod Allowed values are `null`,
* `'closest'` and `'scope'`.
* @return {!Promise<!Element>} Element corresponding to the selector.
*/
getElement(context, selector, selectionMethod = null) {
// Special case selectors. The selection method is irrelavant.
// And no need to wait for document ready.
if (selector == ':root') {
return tryResolve(() => this.getRootElement());
}
if (selector == ':host') {
return new Promise(resolve => {
resolve(
user().assertElement(
this.getHostElement(),
`Element "${selector}" not found`
)
);
});
}
// Wait for document-ready to avoid false missed searches
return this.ampdoc.whenReady().then(() => {
let found;
let result = null;
// Query search based on the selection method.
try {
if (selectionMethod == 'scope') {
found = scopedQuerySelector(context, selector);
} else if (selectionMethod == 'closest') {
found = closestAncestorElementBySelector(context, selector);
} else {
found = this.getRoot().querySelector(selector);
}
} catch (e) {
userAssert(false, `Invalid query selector ${selector}`);
}
// DOM search can "look" outside the boundaries of the root, thus make
// sure the result is contained.
if (found && this.contains(found)) {
result = found;
}
return user().assertElement(result, `Element "${selector}" not found`);
});
}
/**
* Searches the AMP element that matches the selector within the scope of the
* analytics root in relationship to the specified context node.
*
* @param {!Element} context
* @param {string} selector DOM query selector.
* @param {?string=} selectionMethod Allowed values are `null`,
* `'closest'` and `'scope'`.
* @return {!Promise<!AmpElement>} AMP element corresponding to the selector if found.
*/
getAmpElement(context, selector, selectionMethod) {
return this.getElement(context, selector, selectionMethod).then(element => {
userAssert(
element.classList.contains('i-amphtml-element'),
'Element "%s" is required to be an AMP element',
selector
);
return element;
});
}
/**
* Creates listener-filter for DOM events to check against the specified
* selector. If the node (or its ancestors) match the selector the listener
* will be called.
*
* @param {function(!Element, !Event)} listener The first argument is the
* matched target node and the second is the original event.
* @param {!Element} context
* @param {string} selector DOM query selector.
* @param {?string=} selectionMethod Allowed values are `null`,
* `'closest'` and `'scope'`.
* @return {function(!Event)}
*/
createSelectiveListener(listener, context, selector, selectionMethod = null) {
return event => {
if (selector == ':host') {
// `:host` is not reachable via selective listener b/c event path
// cannot be retargeted across the boundary of the embed.
return;
}
// Navigate up the DOM tree to find the actual target.
const rootElement = this.getRootElement();
const isSelectAny = selector == '*';
const isSelectRoot = selector == ':root';
let {target} = event;
while (target) {
// Target must be contained by this root.
if (!this.contains(target)) {
break;
}
// `:scope` context must contain the target.
if (
selectionMethod == 'scope' &&
!isSelectRoot &&
!context.contains(target)
) {
break;
}
// `closest()` target must contain the conext.
if (selectionMethod == 'closest' && !target.contains(context)) {
// However, the search must continue!
target = target.parentElement;
continue;
}
// Check if the target matches the selector.
if (
isSelectAny ||
(isSelectRoot && target == rootElement) ||
tryMatches_(target, selector)
) {
listener(target, event);
// Don't fire the event multiple times even if the more than one
// ancestor matches the selector.
break;
}
target = target.parentElement;
}
};
}
/**
* Returns the promise that will be resolved as soon as the elements within
* the root have been loaded inside the first viewport of the root.
* @return {!Promise}
* @abstract
*/
whenIniLoaded() {}
/**
* Returns the visibility root corresponding to this analytics root (ampdoc
* or embed). The visibility root is created lazily as needed and takes
* care of all visibility tracking functions.
*
* The caller needs to make sure to call getVisibilityManager after
* usingHostAPIPromise has resolved
* @return {!./visibility-manager.VisibilityManager}
*/
getVisibilityManager() {
if (!this.visibilityManager_) {
if (this.hostVisibilityService_) {
// If there is hostAPI (hostAPI never exist with the FIE case)
this.visibilityManager_ = new VisibilityManagerForMApp(
this.ampdoc,
this.hostVisibilityService_
);
} else {
this.visibilityManager_ = provideVisibilityManager(this.getRoot());
}
}
return this.visibilityManager_;
}
/**
* Returns the Scroll Managet corresponding to this analytics root.
* The Scroll Manager is created lazily as needed, and will handle
* calling all handlers for a scroll event.
* @return {!./scroll-manager.ScrollManager}
*/
getScrollManager() {
// TODO (zhouyx@): Disallow scroll trigger with host API
if (!this.scrollManager_) {
this.scrollManager_ = new ScrollManager(this.ampdoc);
}
return this.scrollManager_;
}
}
/**
* The implementation of the analytics root for an ampdoc.
*/
export class AmpdocAnalyticsRoot extends AnalyticsRoot {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
super(ampdoc);
}
/** @override */
getType() {
return 'ampdoc';
}
/** @override */
getRoot() {
return this.ampdoc.getRootNode();
}
/** @override */
getHostElement() {
// ampdoc is always the root of everything - no host.
return null;
}
/** @override */
signals() {
return this.ampdoc.signals();
}
/** @override */
getElementById(id) {
return this.ampdoc.getElementById(id);
}
/** @override */
whenIniLoaded() {
const viewport = Services.viewportForDoc(this.ampdoc);
let rect;
if (getMode(this.ampdoc.win).runtime == 'inabox') {
// TODO(dvoytenko, #7971): This is currently addresses incorrect position
// calculations in a in-a-box viewport where all elements are offset
// to the bottom of the embed. The current approach, even if fixed, still
// creates a significant probability of risk condition.
// Once address, we can simply switch to the 0/0 approach in the `else`
// clause.
rect = viewport.getLayoutRect(this.getRootElement());
} else {
const size = viewport.getSize();
rect = layoutRectLtwh(0, 0, size.width, size.height);
}
return whenContentIniLoad(this.ampdoc, this.ampdoc.win, rect);
}
}
/**
* The implementation of the analytics root for FIE.
* TODO(#22733): merge into AnalyticsRoot once ampdoc-fie is launched.
*/
export class EmbedAnalyticsRoot extends AnalyticsRoot {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {!../../../src/friendly-iframe-embed.FriendlyIframeEmbed} embed
*/
constructor(ampdoc, embed) {
super(ampdoc);
/** @const */
this.embed = embed;
}
/** @override */
getType() {
return 'embed';
}
/** @override */
getRoot() {
return this.embed.win.document;
}
/** @override */
getHostElement() {
return this.embed.iframe;
}
/** @override */
signals() {
return this.embed.signals();
}
/** @override */
getElementById(id) {
return this.embed.win.document.getElementById(id);
}
/** @override */
whenIniLoaded() {
return this.embed.whenIniLoaded();
}
}
/**
* @param {!Element} el
* @param {string} selector
* @return {boolean}
* @noinline
*/
function tryMatches_(el, selector) {
try {
return matches(el, selector);
} catch (e) {
user().error(TAG, 'Bad query selector.', selector, e);
return false;
}
}
|
src-code/amphtml
|
extensions/amp-analytics/0.1/analytics-root.js
|
JavaScript
|
apache-2.0
| 15,094 |
package com.gudnam.bringluck.common;
import java.util.ArrayList;
import android.support.v4.app.FragmentActivity;
public class BLFragmentActivity extends FragmentActivity{
public static ArrayList<FragmentActivity> frgActList = new ArrayList<FragmentActivity>();
}
|
gudnam/bringluck
|
bringluck/src/com/gudnam/bringluck/common/BLFragmentActivity.java
|
Java
|
apache-2.0
| 282 |
package com.coderfun.library;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
coderFun/RadarView
|
library/src/androidTest/java/com/coderfun/library/ApplicationTest.java
|
Java
|
apache-2.0
| 351 |
class Addindex < ActiveRecord::Migration
def self.up
add_index :assignments, [:assign_date,:status]
add_index :assignments, :title
end
def self.down
remove_index :assignments, [:assign_date,:status]
remove_index :assignments, :title
end
end
|
xiviwo/config_track
|
db/migrate/20111013080753_addindex.rb
|
Ruby
|
apache-2.0
| 260 |
/*
* Meego-handset-video is an video player for MeeGo handset.
* Copyright (C) 2010, Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*
*/
#include <QProcess>
#include <QtDebug>
#include <QDir>
#include "xdgpath.h"
XDGPath::XDGPath()
{
m_p = new QProcess();
m_xdgPath.clear();
m_usedProcess = false;
connect(m_p, SIGNAL(readyReadStandardOutput()), this, SLOT(readProcessOutput()));
}
XDGPath::~XDGPath()
{
delete m_p;
}
void XDGPath::readProcessOutput()
{
QByteArray b = m_p->readAllStandardOutput();
m_xdgPath = QString(b).simplified();
qDebug() << "XDG result is " << m_xdgPath;
}
QString XDGPath::getXDGVideosPath()
{
if (!m_usedProcess) {
m_usedProcess = true;
QString command = "xdg-user-dir";
QStringList args;
args << "VIDEOS";
m_p->start(command, args);
m_p->waitForFinished(2000);
if (m_xdgPath.isEmpty())
m_xdgPath = (QDir::homePath() + QString("/Videos"));
return m_xdgPath;
} else {
return m_xdgPath;
}
}
|
dudochkin-victor/handset-video
|
src/xdgpath.cpp
|
C++
|
apache-2.0
| 1,217 |
package ar.edu.ungs.commons.exception;
public class JdbcBatchException extends Exception {
private static final long serialVersionUID = 1;
private String codigoDeError;
/**
* Constructor sin Argumentos
*/
public JdbcBatchException() {
super();
}
/**
* Contructor con el Mensaje de Error
*
* @param message Mensaje de Error
*/
public JdbcBatchException(String message) {
super(message);
}
/**
* Contructor con la Causa de la Excepción
*
* @param cause Causa de la Excepción
*/
public JdbcBatchException(Throwable cause) {
super(cause);
}
/**
* Contructor con el Mensaje de Error y la Causa de la Excepción
*
* @param message Mensaje de Error
* @param cause Causa de la Excepción
*/
public JdbcBatchException(String message, Throwable cause) {
super(message, cause);
}
/**
* Contructor con la Causa de la Excepción y el Código de Error
*
* @param cause Causa de la Excepción
* @param codigoDeError Código de Error
*/
public JdbcBatchException(Throwable cause, String codigoDeError) {
super(cause);
this.codigoDeError = codigoDeError;
}
/**
* Contructor con el Mensaje de Error y el Código de Error
*
* @param message Mensaje de Error
* @param codigoDeError Código de Error
*/
public JdbcBatchException(String message, String codigoDeError) {
super(message);
this.codigoDeError = codigoDeError;
}
/**
* Devuelve el Código de Error
*
* @return Devuelve el Código de Error
*/
public String getCodigoDeError() {
return codigoDeError;
}
/**
* Setea el Código de Error
*
* @param codigoDeError Código de Error
*/
public void setCodigoDeError(String codigoDeError) {
this.codigoDeError = codigoDeError;
}
}
|
alefherrera/sisalud
|
SiSaludSRL/src/main/java/ar/edu/ungs/commons/exception/JdbcBatchException.java
|
Java
|
apache-2.0
| 2,039 |
define({
"map": {
"error": "无法创建地图",
"licenseError": {
"message": "您的帐户无权使用非公共的可配置应用程序。 请联系您的组织管理员为您分配包含基本应用程序或附加基本应用程序许可的用户类型。",
"title": "未经许可"
}
},
"viewer": {
"content_title": "过滤器",
"button_text": "应用",
"filterInstructions": "通过指定值来过滤图层。",
"filterOr": "以下任意表达式必须为 true。",
"filterAnd": "以下表达式必须全部为 true。",
"filterNo": "此 Web 地图不包含任何交互式过滤器。要启用交互式过滤器表达式,请选中 Web 地图过滤器对话框中的“请求值”。<br><br>更多有关帮助,请查看 ${link} 帮助主题了解有关如何在 web 地图中创建交互式过滤器表达式的详细信息。",
"filterLink": "http://doc.arcgis.com/en/arcgis-online/use-maps/apply-filters.htm",
"errors": {
"message": "创建过滤器应用时出现问题"
}
},
"tools": {
"toggle": "切换面板",
"clear": "清除",
"zoom": "缩放"
},
"legend": {
"title": "图例"
}
});
|
Esri/InteractiveFilter
|
js/nls/zh-CN/resources.js
|
JavaScript
|
apache-2.0
| 1,195 |
<?php
/**
* Created by PhpStorm.
* User: yaolihui
* Date: 2018/2/11
* Time: 10:46
*/
namespace Report\Controller;
class ApiController extends WebInfoController {
public function index(){
//定义可以查的平台
$branch=['全部','保险服务','安鑫保','车险APP','易鑫车服','微信','第三方'];
//接收传递参数
$_SESSION['branch']=I('branch');
$search=trim(I('search'));
// dump($_POST);
$this->assign('branch',$branch);
$this->assign('search',$search);
if($_SESSION['branch']=='全部'){
$_SESSION['branch']='';
}else{
if($_SESSION['branch']){
$where['branch']=$_SESSION['branch'];
}
}
$where['client|apiName|adress|author']=array('like','%'.$search.'%');
$where['deleted']='0';
$m=M("tp_apitest");
$data=$m->where($where)->order('branch,adress')->select();
$this->assign('data',$data);
$count=$m->where($where)->count();
$this->assign('count',$count);
$this->display();
}
public function details(){
$id=I(id);
$data=M("tp_apitest")->find($id);
$this->assign('data',$data);
$where=array('api'=>$id,'deleted'=>'0');
$version=M('tp_apiversion')->where($where)->order('atime desc')->select();
$this->assign('version',$version);
$parameter=M('tp_api_parameter')->where($where)->order('sn,id')->select();
$this->assign('parameter',$parameter);
$scene=M('tp_api_scene')->where($where)->order('sn,id')->select();
$this->assign('scene',$scene);
// dump($scene);
$this->display();
}
}
|
yaolihui129/Xinda
|
Apps/Report/Controller/ApiController.class.php
|
PHP
|
apache-2.0
| 1,723 |
package com.zlate87.sample_transport_app;
import android.annotation.TargetApi;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
/**
* Class containing custom matchers.
*/
public class CustomMatchers {
/**
* Matcher that matches ImageView drawable with a drawable from resources.
*
* @param resourceId the resource id for the drawable.
* @return {@code true} if the drawable matches, {@code false} if not
*/
public static Matcher<View> withDrawable(final int resourceId) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText(String.format("with drawable from resource id: [%s]", resourceId));
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean matchesSafely(View view) {
final Drawable resourcesDrawable = getDrawable(view, resourceId);
final ImageView imageView = (ImageView) view;
if (imageView.getDrawable() == null) {
return resourcesDrawable == null;
}
return areDrawablesIdentical(imageView.getDrawable(), resourcesDrawable);
}
};
}
/**
* Matcher that matches view with a given id at given position in a recycler view.
*
* @param recyclerViewId the recycler view id
* @param position element position where the view is at recycler view
* @param viewId the view id
* @return {@code true} if the view matches, {@code false} if not
*/
public static Matcher<View> viewAtPositionInRecyclerView(final int recyclerViewId, final int position,
final int viewId) {
return new TypeSafeMatcher<View>() {
Resources resources = null;
View childView;
public void describeTo(Description description) {
String idDescription = Integer.toString(recyclerViewId);
if (resources != null) {
try {
idDescription = this.resources.getResourceName(recyclerViewId);
} catch (Resources.NotFoundException var4) {
idDescription = String.format("%d (resource name not found)", recyclerViewId);
}
}
description.appendText("with id: " + idDescription);
}
public boolean matchesSafely(View view) {
resources = view.getResources();
if (childView == null) {
RecyclerView recyclerView = (RecyclerView) view.getRootView().findViewById(recyclerViewId);
if (recyclerView != null && recyclerView.getId() == recyclerViewId) {
childView = recyclerView.getChildAt(position);
} else {
return false;
}
}
if (viewId == -1) {
return view == childView;
} else {
View targetView = childView.findViewById(viewId);
return view == targetView;
}
}
};
}
/**
* Matches dynamic view in a linear layout within a recycler view for a given:
*
* @param recyclerViewId the id of the recycler view
* @param viewPosition the position index of the route preview view in the recycler view
* @param iconsLayout the id of the layout for the icon attributes
* @param iconPosition the icon position inside the icons layout
* @return the matcher
*/
public static Matcher<View> dynamicView(final int recyclerViewId,
final int viewPosition,
final int iconsLayout,
final int iconPosition) {
return new TypeSafeMatcher<View>() {
Resources resources = null;
View routePreviewView;
public void describeTo(Description description) {
String idDescription = Integer.toString(recyclerViewId);
if (resources != null) {
try {
idDescription = this.resources.getResourceName(recyclerViewId);
} catch (Resources.NotFoundException var4) {
idDescription = String.format("%d (resource name not found)", recyclerViewId);
}
}
description.appendText("with id: " + idDescription);
}
public boolean matchesSafely(View view) {
resources = view.getResources();
if (routePreviewView == null) {
RecyclerView recyclerView = (RecyclerView) view.getRootView().findViewById(recyclerViewId);
if (recyclerView != null && recyclerView.getId() == recyclerViewId) {
routePreviewView = recyclerView.getChildAt(viewPosition);
} else {
return false;
}
}
LinearLayout iconsLinearLayout = (LinearLayout) routePreviewView.findViewById(iconsLayout);
View targetView = iconsLinearLayout.getChildAt(iconPosition);
return view == targetView;
}
};
}
private static Drawable getDrawable(View view, int resourceId) {
final Drawable resourcesDrawable;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
resourcesDrawable = view.getResources().getDrawable(resourceId);
} else {
resourcesDrawable = view.getContext().getDrawable(resourceId);
}
return resourcesDrawable;
}
private static boolean areDrawablesIdentical(Drawable drawableA, Drawable drawableB) {
Drawable.ConstantState constantStateA = drawableA.getConstantState();
Drawable.ConstantState constantStateB = drawableB.getConstantState();
return (constantStateA != null && constantStateB != null && constantStateA.equals(constantStateB))
|| getBitmap(drawableA).sameAs(getBitmap(drawableB));
}
private static Bitmap getBitmap(Drawable drawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
}
|
Zlate87/sample-transport-app
|
app/src/androidTest/java/com/zlate87/sample_transport_app/CustomMatchers.java
|
Java
|
apache-2.0
| 5,643 |
package net.rubygrapefruit.platform.terminal;
/**
* Receives terminal input.
*/
public interface TerminalInputListener {
enum Key {
// Order is significant, used by Windows native code
Enter,
UpArrow,
DownArrow,
LeftArrow,
RightArrow,
Home,
End,
EraseBack,
EraseForward,
BackTab,
PageUp,
PageDown
}
/**
* Called when a character is typed. Note that this method is not called for the 'enter' key.
*/
void character(char ch);
/**
* Called when a control key is typed.
*/
void controlKey(Key key);
/**
* Called on the end of input.
*/
void endInput();
}
|
adammurdoch/native-platform
|
native-platform/src/main/java/net/rubygrapefruit/platform/terminal/TerminalInputListener.java
|
Java
|
apache-2.0
| 723 |
/*
* Copyright 2012 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
*
* 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.sprintapi.api.http.servlet.todo.action;
import org.sprintapi.api.Context;
import org.sprintapi.api.action.Action;
import org.sprintapi.api.content.ContentBuilder;
import org.sprintapi.api.error.ApiErrorException;
import org.sprintapi.api.http.servlet.todo.TodoItem;
import org.sprintapi.api.meta.type.Language;
import org.sprintapi.api.request.Request;
import org.sprintapi.api.response.Response;
public class TodoReadItemAction implements Action<Void, TodoItem> {
@Override
public void invoke(Request<Void> request, Response<TodoItem> response, Context<Void, TodoItem> ctx) throws ApiErrorException {
TodoItem item1 = new TodoItem();
item1.setDescription("Todo Item 1");
response.setContent(
(new ContentBuilder<TodoItem>())
.language(Language.EN_US)
.body(item1)
);
}
@Override
public TodoReadItemAction getThreadSafeInstance() {
return this;
}
}
|
filip26/api-machine
|
src/test/java/org/sprintapi/api/http/servlet/todo/action/TodoReadItemAction.java
|
Java
|
apache-2.0
| 1,529 |
#
# Cookbook Name:: ratpoison
# Recipe:: default
#
# Copyright 2014, Shuberg Philis B.V.
#
# 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.
#
include_recipe 'xvfb'
include_recipe 'ratpoison::windowmanager'
|
miguelaferreira/ratpoison
|
recipes/default.rb
|
Ruby
|
apache-2.0
| 702 |
using System.Text;
using Google.GData.Client;
namespace Google.GData.ContentForShopping
{
/// <summary>
/// A subclass of FeedQuery, to create a ContentForShopping managedaccounts
/// query URI. Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
/// </summary>
public class ManagedAccountsQuery : FeedQuery
{
/// <summary>
/// Constructor
/// </summary>
public ManagedAccountsQuery()
: base(ContentForShoppingNameTable.AllFeedsBaseUri)
{
}
/// <summary>
/// Constructor
/// </summary>
public ManagedAccountsQuery(string accountId)
: base(ContentForShoppingNameTable.AllFeedsBaseUri)
{
AccountId = accountId;
}
/// <summary>
/// Accessor method for AccountId.
/// </summary>
public string AccountId { get; set; }
/// <summary>
/// Returns the base Uri for the feed.
/// </summary>
protected override string GetBaseUri()
{
StringBuilder sb = new StringBuilder(baseUri, 2048);
sb.Append("/");
sb.Append(AccountId);
sb.Append("/managedaccounts/");
return sb.ToString();
}
}
}
|
jonny-novikov/google-gdata
|
src/contentforshopping/managedaccountsquery.cs
|
C#
|
apache-2.0
| 1,341 |
/* 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.flowable.cmmn.editor.json.converter;
import java.util.Map;
import org.flowable.cmmn.editor.constants.CmmnStencilConstants;
import org.flowable.cmmn.editor.json.converter.CmmnJsonConverter.CmmnModelIdHelper;
import org.flowable.cmmn.model.BaseElement;
import org.flowable.cmmn.model.CaseTask;
import org.flowable.cmmn.model.CmmnModel;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* @author Tijs Rademakers
*/
public class CaseTaskJsonConverter extends BaseCmmnJsonConverter implements CaseModelAwareConverter {
protected Map<String, String> caseModelMap;
public static void fillTypes(Map<String, Class<? extends BaseCmmnJsonConverter>> convertersToCmmnMap,
Map<Class<? extends BaseElement>, Class<? extends BaseCmmnJsonConverter>> convertersToJsonMap) {
fillJsonTypes(convertersToCmmnMap);
fillCmmnTypes(convertersToJsonMap);
}
public static void fillJsonTypes(Map<String, Class<? extends BaseCmmnJsonConverter>> convertersToBpmnMap) {
convertersToBpmnMap.put(STENCIL_TASK_CASE, CaseTaskJsonConverter.class);
}
public static void fillCmmnTypes(Map<Class<? extends BaseElement>, Class<? extends BaseCmmnJsonConverter>> convertersToJsonMap) {
convertersToJsonMap.put(CaseTask.class, CaseTaskJsonConverter.class);
}
@Override
protected String getStencilId(BaseElement baseElement) {
return CmmnStencilConstants.STENCIL_TASK_CASE;
}
@Override
protected void convertElementToJson(ObjectNode elementNode, ObjectNode propertiesNode, ActivityProcessor processor,
BaseElement baseElement, CmmnModel cmmnModel) {
// todo
}
@Override
protected BaseElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, ActivityProcessor processor,
BaseElement parentElement, Map<String, JsonNode> shapeMap, CmmnModel cmmnModel, CmmnModelIdHelper cmmnModelIdHelper) {
CaseTask task = new CaseTask();
JsonNode caseModelReferenceNode = CmmnJsonConverterUtil.getProperty(PROPERTY_CASE_REFERENCE, elementNode);
if (caseModelReferenceNode != null && caseModelReferenceNode.has("id") && !caseModelReferenceNode.get("id").isNull()) {
String caseModelId = caseModelReferenceNode.get("id").asText();
if (caseModelMap != null) {
String caseModelKey = caseModelMap.get(caseModelId);
task.setCaseRef(caseModelKey);
}
}
return task;
}
@Override
public void setCaseModelMap(Map<String, String> caseModelMap) {
this.caseModelMap = caseModelMap;
}
}
|
marcus-nl/flowable-engine
|
modules/flowable-cmmn-json-converter/src/main/java/org/flowable/cmmn/editor/json/converter/CaseTaskJsonConverter.java
|
Java
|
apache-2.0
| 3,292 |
//===---------- MIRVRegNamerUtils.cpp - MIR VReg Renaming Utilities -------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "MIRVRegNamerUtils.h"
using namespace llvm;
#define DEBUG_TYPE "mir-vregnamer-utils"
namespace {
// TypedVReg and VRType are used to tell the renamer what to do at points in a
// sequence of values to be renamed. A TypedVReg can either contain
// an actual VReg, a FrameIndex, or it could just be a barrier for the next
// candidate (side-effecting instruction). This tells the renamer to increment
// to the next vreg name, or to skip modulo some skip-gap value.
enum VRType { RSE_Reg = 0, RSE_FrameIndex, RSE_NewCandidate };
class TypedVReg {
VRType Type;
Register Reg;
public:
TypedVReg(Register Reg) : Type(RSE_Reg), Reg(Reg) {}
TypedVReg(VRType Type) : Type(Type), Reg(~0U) {
assert(Type != RSE_Reg && "Expected a non-Register Type.");
}
bool isReg() const { return Type == RSE_Reg; }
bool isFrameIndex() const { return Type == RSE_FrameIndex; }
bool isCandidate() const { return Type == RSE_NewCandidate; }
VRType getType() const { return Type; }
Register getReg() const {
assert(this->isReg() && "Expected a virtual or physical Register.");
return Reg;
}
};
/// Here we find our candidates. What makes an interesting candidate?
/// A candidate for a canonicalization tree root is normally any kind of
/// instruction that causes side effects such as a store to memory or a copy to
/// a physical register or a return instruction. We use these as an expression
/// tree root that we walk in order to build a canonical walk which should
/// result in canonical vreg renaming.
std::vector<MachineInstr *> populateCandidates(MachineBasicBlock *MBB) {
std::vector<MachineInstr *> Candidates;
MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
for (auto II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
MachineInstr *MI = &*II;
bool DoesMISideEffect = false;
if (MI->getNumOperands() > 0 && MI->getOperand(0).isReg()) {
const Register Dst = MI->getOperand(0).getReg();
DoesMISideEffect |= !Register::isVirtualRegister(Dst);
for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI) {
if (DoesMISideEffect)
break;
DoesMISideEffect |= (UI->getParent()->getParent() != MI->getParent());
}
}
if (!MI->mayStore() && !MI->isBranch() && !DoesMISideEffect)
continue;
LLVM_DEBUG(dbgs() << "Found Candidate: "; MI->dump(););
Candidates.push_back(MI);
}
return Candidates;
}
void doCandidateWalk(std::vector<TypedVReg> &VRegs,
std::queue<TypedVReg> &RegQueue,
std::vector<MachineInstr *> &VisitedMIs,
const MachineBasicBlock *MBB) {
const MachineFunction &MF = *MBB->getParent();
const MachineRegisterInfo &MRI = MF.getRegInfo();
while (!RegQueue.empty()) {
auto TReg = RegQueue.front();
RegQueue.pop();
if (TReg.isFrameIndex()) {
LLVM_DEBUG(dbgs() << "Popping frame index.\n";);
VRegs.push_back(TypedVReg(RSE_FrameIndex));
continue;
}
assert(TReg.isReg() && "Expected vreg or physreg.");
Register Reg = TReg.getReg();
if (Register::isVirtualRegister(Reg)) {
LLVM_DEBUG({
dbgs() << "Popping vreg ";
MRI.def_begin(Reg)->dump();
dbgs() << "\n";
});
if (!llvm::any_of(VRegs, [&](const TypedVReg &TR) {
return TR.isReg() && TR.getReg() == Reg;
})) {
VRegs.push_back(TypedVReg(Reg));
}
} else {
LLVM_DEBUG(dbgs() << "Popping physreg.\n";);
VRegs.push_back(TypedVReg(Reg));
continue;
}
for (auto RI = MRI.def_begin(Reg), RE = MRI.def_end(); RI != RE; ++RI) {
MachineInstr *Def = RI->getParent();
if (Def->getParent() != MBB)
continue;
if (llvm::any_of(VisitedMIs,
[&](const MachineInstr *VMI) { return Def == VMI; })) {
break;
}
LLVM_DEBUG({
dbgs() << "\n========================\n";
dbgs() << "Visited MI: ";
Def->dump();
dbgs() << "BB Name: " << Def->getParent()->getName() << "\n";
dbgs() << "\n========================\n";
});
VisitedMIs.push_back(Def);
for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
MachineOperand &MO = Def->getOperand(I);
if (MO.isFI()) {
LLVM_DEBUG(dbgs() << "Pushing frame index.\n";);
RegQueue.push(TypedVReg(RSE_FrameIndex));
}
if (!MO.isReg())
continue;
RegQueue.push(TypedVReg(MO.getReg()));
}
}
}
}
std::map<unsigned, unsigned>
getVRegRenameMap(const std::vector<TypedVReg> &VRegs,
const std::vector<Register> &renamedInOtherBB,
MachineRegisterInfo &MRI, NamedVRegCursor &NVC) {
std::map<unsigned, unsigned> VRegRenameMap;
bool FirstCandidate = true;
for (auto &vreg : VRegs) {
if (vreg.isFrameIndex()) {
// We skip one vreg for any frame index because there is a good chance
// (especially when comparing SelectionDAG to GlobalISel generated MIR)
// that in the other file we are just getting an incoming vreg that comes
// from a copy from a frame index. So it's safe to skip by one.
unsigned LastRenameReg = NVC.incrementVirtualVReg();
(void)LastRenameReg;
LLVM_DEBUG(dbgs() << "Skipping rename for FI " << LastRenameReg << "\n";);
continue;
} else if (vreg.isCandidate()) {
// After the first candidate, for every subsequent candidate, we skip mod
// 10 registers so that the candidates are more likely to start at the
// same vreg number making it more likely that the canonical walk from the
// candidate insruction. We don't need to skip from the first candidate of
// the BasicBlock because we already skip ahead several vregs for each BB.
unsigned LastRenameReg = NVC.getVirtualVReg();
if (FirstCandidate)
NVC.incrementVirtualVReg(LastRenameReg % 10);
FirstCandidate = false;
continue;
} else if (!Register::isVirtualRegister(vreg.getReg())) {
unsigned LastRenameReg = NVC.incrementVirtualVReg();
(void)LastRenameReg;
LLVM_DEBUG({
dbgs() << "Skipping rename for Phys Reg " << LastRenameReg << "\n";
});
continue;
}
auto Reg = vreg.getReg();
if (llvm::find(renamedInOtherBB, Reg) != renamedInOtherBB.end()) {
LLVM_DEBUG(dbgs() << "Vreg " << Reg
<< " already renamed in other BB.\n";);
continue;
}
auto Rename = NVC.createVirtualRegister(Reg);
if (VRegRenameMap.find(Reg) == VRegRenameMap.end()) {
LLVM_DEBUG(dbgs() << "Mapping vreg ";);
if (MRI.reg_begin(Reg) != MRI.reg_end()) {
LLVM_DEBUG(auto foo = &*MRI.reg_begin(Reg); foo->dump(););
} else {
LLVM_DEBUG(dbgs() << Reg;);
}
LLVM_DEBUG(dbgs() << " to ";);
if (MRI.reg_begin(Rename) != MRI.reg_end()) {
LLVM_DEBUG(auto foo = &*MRI.reg_begin(Rename); foo->dump(););
} else {
LLVM_DEBUG(dbgs() << Rename;);
}
LLVM_DEBUG(dbgs() << "\n";);
VRegRenameMap.insert(std::pair<unsigned, unsigned>(Reg, Rename));
}
}
return VRegRenameMap;
}
bool doVRegRenaming(std::vector<Register> &renamedInOtherBB,
const std::map<unsigned, unsigned> &VRegRenameMap,
MachineRegisterInfo &MRI) {
bool Changed = false;
for (auto I = VRegRenameMap.begin(), E = VRegRenameMap.end(); I != E; ++I) {
auto VReg = I->first;
auto Rename = I->second;
renamedInOtherBB.push_back(Rename);
std::vector<MachineOperand *> RenameMOs;
for (auto &MO : MRI.reg_operands(VReg)) {
RenameMOs.push_back(&MO);
}
for (auto *MO : RenameMOs) {
Changed = true;
MO->setReg(Rename);
if (!MO->isDef())
MO->setIsKill(false);
}
}
return Changed;
}
bool renameVRegs(MachineBasicBlock *MBB,
std::vector<Register> &renamedInOtherBB,
NamedVRegCursor &NVC) {
bool Changed = false;
MachineFunction &MF = *MBB->getParent();
MachineRegisterInfo &MRI = MF.getRegInfo();
std::vector<MachineInstr *> Candidates = populateCandidates(MBB);
std::vector<MachineInstr *> VisitedMIs;
llvm::copy(Candidates, std::back_inserter(VisitedMIs));
std::vector<TypedVReg> VRegs;
for (auto candidate : Candidates) {
VRegs.push_back(TypedVReg(RSE_NewCandidate));
std::queue<TypedVReg> RegQueue;
// Here we walk the vreg operands of a non-root node along our walk.
// The root nodes are the original candidates (stores normally).
// These are normally not the root nodes (except for the case of copies to
// physical registers).
for (unsigned i = 1; i < candidate->getNumOperands(); i++) {
if (candidate->mayStore() || candidate->isBranch())
break;
MachineOperand &MO = candidate->getOperand(i);
if (!(MO.isReg() && Register::isVirtualRegister(MO.getReg())))
continue;
LLVM_DEBUG(dbgs() << "Enqueue register"; MO.dump(); dbgs() << "\n";);
RegQueue.push(TypedVReg(MO.getReg()));
}
// Here we walk the root candidates. We start from the 0th operand because
// the root is normally a store to a vreg.
for (unsigned i = 0; i < candidate->getNumOperands(); i++) {
if (!candidate->mayStore() && !candidate->isBranch())
break;
MachineOperand &MO = candidate->getOperand(i);
// TODO: Do we want to only add vregs here?
if (!MO.isReg() && !MO.isFI())
continue;
LLVM_DEBUG(dbgs() << "Enqueue Reg/FI"; MO.dump(); dbgs() << "\n";);
RegQueue.push(MO.isReg() ? TypedVReg(MO.getReg())
: TypedVReg(RSE_FrameIndex));
}
doCandidateWalk(VRegs, RegQueue, VisitedMIs, MBB);
}
// If we have populated no vregs to rename then bail.
// The rest of this function does the vreg remaping.
if (VRegs.size() == 0)
return Changed;
auto VRegRenameMap = getVRegRenameMap(VRegs, renamedInOtherBB, MRI, NVC);
Changed |= doVRegRenaming(renamedInOtherBB, VRegRenameMap, MRI);
return Changed;
}
} // anonymous namespace
void NamedVRegCursor::skipVRegs() {
unsigned VRegGapIndex = 1;
if (!virtualVRegNumber) {
VRegGapIndex = 0;
virtualVRegNumber = MRI.createIncompleteVirtualRegister();
}
const unsigned VR_GAP = (++VRegGapIndex * SkipGapSize);
unsigned I = virtualVRegNumber;
const unsigned E = (((I + VR_GAP) / VR_GAP) + 1) * VR_GAP;
virtualVRegNumber = E;
}
unsigned NamedVRegCursor::createVirtualRegister(unsigned VReg) {
if (!virtualVRegNumber)
skipVRegs();
std::string S;
raw_string_ostream OS(S);
OS << "namedVReg" << (virtualVRegNumber & ~0x80000000);
OS.flush();
virtualVRegNumber++;
if (auto RC = MRI.getRegClassOrNull(VReg))
return MRI.createVirtualRegister(RC, OS.str());
return MRI.createGenericVirtualRegister(MRI.getType(VReg), OS.str());
}
bool NamedVRegCursor::renameVRegs(MachineBasicBlock *MBB) {
return ::renameVRegs(MBB, RenamedInOtherBB, *this);
}
|
GPUOpen-Drivers/llvm
|
lib/CodeGen/MIRVRegNamerUtils.cpp
|
C++
|
apache-2.0
| 11,427 |
package eu.leads.processor.common.infinispan;
import org.infinispan.commons.util.concurrent.NotifyingFuture;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ExecutionException;
/**
* Created by vagvaz on 19/05/15.
*/
public class ClearCompletedRunnable extends Thread {
private final Set<Thread> threads;
private final Queue<NotifyingFuture<Void>> concurrentQueue;
private volatile Object mutex;
public ClearCompletedRunnable(Queue<NotifyingFuture<Void>> concurrentQuue, Object mutex,
Set<Thread> threads) {
this.concurrentQueue = concurrentQuue;
this.mutex = mutex;
this.threads = threads;
}
@Override public void run() {
super.run();
Iterator<NotifyingFuture<Void>> iterator = concurrentQueue.iterator();
NotifyingFuture current = concurrentQueue.poll();
while(current != null){
try {
// iterator.next().get();
current.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// iterator.remove();
// if(iterator.next().isDone()){
// iterator.remove();
// }
current = concurrentQueue.poll();
}
// synchronized (mutex){
// threads.remove(this);
// }
}
}
|
leads-project/multicloud-mr
|
common/src/main/java/eu/leads/processor/common/infinispan/ClearCompletedRunnable.java
|
Java
|
apache-2.0
| 1,476 |
/*
* Copyright 2015 "Henry Tao <hi@henrytao.me>"
*
* 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 me.henrytao.smoothappbarlayoutdemo.fragment;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import me.henrytao.smoothappbarlayoutdemo.R;
public class DummyNestedScrollViewFragment extends Fragment implements ObservableScrollView {
private static final String ARG_HEADER_LAYOUT = "ARG_HEADER_LAYOUT";
private static final String ARG_TEXT = "ARG_TEXT";
public static DummyNestedScrollViewFragment newInstance(String text) {
return DummyNestedScrollViewFragment.newInstance(text, 0);
}
public static DummyNestedScrollViewFragment newInstance(String text, @LayoutRes int headerLayout) {
DummyNestedScrollViewFragment fragment = new DummyNestedScrollViewFragment();
Bundle bundle = new Bundle();
bundle.putString(ARG_TEXT, text);
bundle.putInt(ARG_HEADER_LAYOUT, headerLayout);
fragment.setArguments(bundle);
return fragment;
}
@Bind(R.id.frame_layout)
FrameLayout vFrameLayout;
@Bind(android.R.id.list)
NestedScrollView vNestedScrollView;
@Bind(R.id.text)
TextView vText;
public DummyNestedScrollViewFragment() {
// Required empty public constructor
}
@Override
public View getScrollView() {
if (isAdded()) {
return vNestedScrollView;
}
return null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dummy_nested_scroll_view, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
vText.setText(getArgText());
int headerLayout = getArgHeaderLayout();
if (headerLayout > 0) {
vFrameLayout.removeAllViews();
vFrameLayout.addView(LayoutInflater.from(getContext()).inflate(headerLayout, null));
}
}
private int getArgHeaderLayout() {
Bundle bundle = getArguments();
if (bundle != null) {
return bundle.getInt(ARG_HEADER_LAYOUT);
}
return 0;
}
private String getArgText() {
Bundle bundle = getArguments();
if (bundle != null) {
return bundle.getString(ARG_TEXT);
}
return "";
}
}
|
eneim/smooth-app-bar-layout
|
sample/src/main/java/me/henrytao/smoothappbarlayoutdemo/fragment/DummyNestedScrollViewFragment.java
|
Java
|
apache-2.0
| 3,280 |
require 'spec_helper'
describe file('/etc/scylla/scylla.yaml') do
it { should be_file }
its(:content_as_yaml) do
should include('listen_address' => '123.135.147.159')
end
its(:content_as_yaml) do
should include('rpc_address' => '0.0.0.0')
end
its(:content_as_yaml) do
should include('broadcast_rpc_address' => '123.135.147.159')
end
its(:content_as_yaml) do
should include(
'seed_provider' => include(
'class_name' => 'org.apache.cassandra.locator.SimpleSeedProvider',
'parameters' => include(
'seeds' => '111.11.1.123,111.11.1.124'
)
)
)
end
its(:content_as_yaml) do
should include('conf_1' => 'string_value')
end
its(:content_as_yaml) do
should include('conf_2' => 123)
end
its(:content_as_yaml) do
should include(
'conf_3' => include(
'this' => 'is',
'nested' => 'dict',
'with' => %w(array of strings)
)
)
end
end
describe file('/etc/scylla/cassandra-rackdc.properties') do
it { should be_file }
end
|
dice-project/DICE-Chef-Repository
|
cookbooks/scylla/test/integration/config/serverspec/config_spec.rb
|
Ruby
|
apache-2.0
| 1,055 |
using System;
using System.IO;
using FluentAssertions;
using JetBrains.Annotations;
using TestableFileSystem.Fakes.Builders;
using TestableFileSystem.Interfaces;
using Xunit;
namespace TestableFileSystem.Fakes.Tests.Specs.DiskSpace
{
public sealed class InsufficientSpaceSpecs
{
[Fact]
private void When_writing_to_file_it_must_fail()
{
// Arrange
const string path = @"C:\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(512))
.Build();
// Act
Action action = () => fileSystem.File.WriteAllBytes(path, BufferFactory.Create(1024));
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFileSize(fileSystem, path, 0);
AssertFreeSpaceOnDrive(fileSystem, "C:", 512);
}
[Fact]
private void When_overwriting_file_it_must_fail()
{
// Arrange
const string path = @"C:\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(3072))
.IncludingBinaryFile(path, BufferFactory.Create(1024))
.Build();
// Act
Action action = () => fileSystem.File.WriteAllBytes(path, BufferFactory.Create(4000));
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 3072);
AssertFileSize(fileSystem, path, 0);
}
[Fact]
private void When_increasing_file_size_using_SetLength_it_must_fail()
{
// Arrange
const string path = @"C:\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(512))
.IncludingBinaryFile(path, BufferFactory.Create(32))
.Build();
using (IFileStream stream = fileSystem.File.OpenWrite(path))
{
byte[] buffer = BufferFactory.Create(64);
stream.Write(buffer, 0, buffer.Length);
// Act
// ReSharper disable once AccessToDisposedClosure
Action action = () => stream.SetLength(1280);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 448);
}
AssertFileSize(fileSystem, path, 64);
}
[Fact]
private void When_increasing_file_size_using_Seek_followed_by_write_it_must_fail()
{
// Arrange
const string path = @"C:\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(512))
.IncludingBinaryFile(path, BufferFactory.Create(32))
.Build();
using (IFileStream stream = fileSystem.File.OpenWrite(path))
{
byte[] buffer = BufferFactory.Create(64);
stream.Write(buffer, 0, buffer.Length);
stream.Seek(1280, SeekOrigin.Begin);
// Act
// ReSharper disable once AccessToDisposedClosure
Action action = () => stream.WriteByte(0x33);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 448);
}
AssertFileSize(fileSystem, path, 64);
}
[Fact]
private void When_increasing_file_size_using_Position_followed_by_write_it_must_fail()
{
// Arrange
const string path = @"C:\file.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(512))
.IncludingBinaryFile(path, BufferFactory.Create(32))
.Build();
using (IFileStream stream = fileSystem.File.OpenWrite(path))
{
byte[] buffer = BufferFactory.Create(64);
stream.Write(buffer, 0, buffer.Length);
stream.Position = 1280;
// Act
// ReSharper disable once AccessToDisposedClosure
Action action = () => stream.WriteByte(0x33);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 448);
}
AssertFileSize(fileSystem, path, 64);
}
[Fact]
private void When_copying_file_to_same_drive_it_must_fail()
{
// Arrange
const string sourcePath = @"C:\source.txt";
const string targetPath = @"C:\target.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(1024))
.IncludingBinaryFile(sourcePath, BufferFactory.Create(768))
.Build();
// Act
Action action = () => fileSystem.File.Copy(sourcePath, targetPath);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 256);
AssertFileSize(fileSystem, sourcePath, 768);
fileSystem.File.Exists(targetPath).Should().BeFalse();
}
[Fact]
private void When_copying_over_existing_file_to_same_drive_it_must_fail()
{
// Arrange
const string sourcePath = @"C:\source.txt";
const string targetPath = @"C:\target.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(1024))
.IncludingBinaryFile(sourcePath, BufferFactory.Create(768))
.IncludingEmptyFile(targetPath)
.Build();
// Act
Action action = () => fileSystem.File.Copy(sourcePath, targetPath, true);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 256);
AssertFileSize(fileSystem, sourcePath, 768);
fileSystem.File.Exists(targetPath).Should().BeTrue();
}
[Fact]
private void When_copying_file_to_other_drive_it_must_fail()
{
// Arrange
const string sourcePath = @"C:\source.txt";
const string targetPath = @"D:\target.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(4096))
.IncludingBinaryFile(sourcePath, BufferFactory.Create(768))
.IncludingVolume("D:", new FakeVolumeInfoBuilder()
.OfCapacity(16384)
.WithFreeSpace(512))
.Build();
// Act
Action action = () => fileSystem.File.Copy(sourcePath, targetPath);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 3328);
AssertFileSize(fileSystem, sourcePath, 768);
AssertFreeSpaceOnDrive(fileSystem, "D:", 512);
fileSystem.File.Exists(targetPath).Should().BeFalse();
}
[Fact]
private void When_copying_over_existing_file_to_other_drive_it_must_fail()
{
// Arrange
const string sourcePath = @"C:\source.txt";
const string targetPath = @"D:\target.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(4096))
.IncludingBinaryFile(sourcePath, BufferFactory.Create(768))
.IncludingVolume("D:", new FakeVolumeInfoBuilder()
.OfCapacity(16384)
.WithFreeSpace(512))
.IncludingEmptyFile(targetPath)
.Build();
// Act
Action action = () => fileSystem.File.Copy(sourcePath, targetPath, true);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
AssertFreeSpaceOnDrive(fileSystem, "C:", 3328);
AssertFileSize(fileSystem, sourcePath, 768);
AssertFreeSpaceOnDrive(fileSystem, "D:", 512);
fileSystem.File.Exists(targetPath).Should().BeTrue();
}
[Fact]
private void When_moving_file_to_other_drive_it_must_fail()
{
// Arrange
const string sourcePath = @"C:\source.txt";
const string targetPath = @"D:\target.txt";
IFileSystem fileSystem = new FakeFileSystemBuilder()
.IncludingVolume("C:", new FakeVolumeInfoBuilder()
.OfCapacity(8192)
.WithFreeSpace(4096))
.IncludingBinaryFile(sourcePath, BufferFactory.Create(768))
.IncludingVolume("D:", new FakeVolumeInfoBuilder()
.OfCapacity(16384)
.WithFreeSpace(512))
.Build();
// Act
Action action = () => fileSystem.File.Move(sourcePath, targetPath);
// Assert
action.Should().ThrowExactly<IOException>().WithMessage("There is not enough space on the disk.");
// Assert
AssertFreeSpaceOnDrive(fileSystem, "C:", 3328);
AssertFileSize(fileSystem, sourcePath, 768);
AssertFreeSpaceOnDrive(fileSystem, "D:", 512);
fileSystem.File.Exists(targetPath).Should().BeFalse();
}
[AssertionMethod]
private static void AssertFileSize([NotNull] IFileSystem fileSystem, [NotNull] string path, long fileSizeExpected)
{
IFileInfo fileInfo = fileSystem.ConstructFileInfo(path);
fileInfo.Length.Should().Be(fileSizeExpected);
}
[AssertionMethod]
private static void AssertFreeSpaceOnDrive([NotNull] IFileSystem fileSystem, [NotNull] string driveName,
long freeSpaceExpected)
{
#if !NETCOREAPP1_1
IDriveInfo driveInfo = fileSystem.ConstructDriveInfo(driveName);
driveInfo.AvailableFreeSpace.Should().Be(freeSpaceExpected);
#endif
}
}
}
|
bkoelman/TestableFileSystem
|
src/Fakes.Tests/Specs/DiskSpace/InsufficientSpaceSpecs.cs
|
C#
|
apache-2.0
| 11,685 |
package com.zandero.rest;
import com.zandero.rest.test.*;
import com.zandero.rest.test.json.Dummy;
import com.zandero.utils.extra.JsonUtils;
import io.vertx.core.buffer.Buffer;
import io.vertx.ext.web.Router;
import io.vertx.junit5.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(VertxExtension.class)
class RouteRegistrationTest extends VertxTest {
@BeforeAll
static void start() {
before();
TestRest testRest = new TestRest();
TestPostRest testPostRest = new TestPostRest();
Router router = RestRouter.register(vertx, testRest, testPostRest);
vertx.createHttpServer()
.requestHandler(router)
.listen(PORT);
}
@Test
void registerTwoRoutesTest(VertxTestContext context) {
// check if both are active
Dummy json = new Dummy("test", "me");
// 2nd REST
client.post(PORT, HOST, "/post/json")
.putHeader("content-type", "application/json")
.sendBuffer(Buffer.buffer(JsonUtils.toJson(json)),
context.succeeding(response -> context.verify(() -> {
assertEquals(200, response.statusCode());
assertEquals("{\"name\":\"Received-test\",\"value\":\"Received-me\"}", response.bodyAsString());
context.completeNow();
})));
}
@Test
void registerTwoRoutesSeparate(VertxTestContext context) {
// check if both are active
Dummy json = new Dummy("test", "me");
client.post(PORT, HOST, "/test/json/post")
.putHeader("content-type", "application/json")
.sendBuffer(Buffer.buffer(JsonUtils.toJson(json)),
context.succeeding(response -> context.verify(() -> {
assertEquals(200, response.statusCode());
assertEquals("{\"name\":\"Received-test\",\"value\":\"Received-me\"}", response.bodyAsString());
context.completeNow();
})));
// 2nd REST
client.post(PORT, HOST, "/post/json")
.putHeader("content-type", "application/json")
.sendBuffer(Buffer.buffer(JsonUtils.toJson(json)),
context.succeeding(response -> context.verify(() -> {
assertEquals(200, response.statusCode());
assertEquals("{\"name\":\"Received-test\",\"value\":\"Received-me\"}", response.bodyAsString());
context.completeNow();
})));
}
}
|
zandero/rest.vertx
|
src/test/java/com/zandero/rest/RouteRegistrationTest.java
|
Java
|
apache-2.0
| 2,744 |
/*
* SHS -- The Scalable Hyperlink Store
*
* Copyright (c) Microsoft Corporation
* 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
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using SHS;
public class ASP {
private static void ProcessBatch(Store shs, UidState<byte> dists, UidState<long> seeds, long[] uids, byte dist, Dir dir) {
var uidSeeds = seeds.GetMany(uids);
var nborUids = shs.BatchedGetLinks(uids, dir);
var map = new UidMap(nborUids);
var distChunk = dists.GetMany(map);
var seedChunk = seeds.GetMany(map);
for (int i = 0; i < nborUids.Length; i++) {
for (int j = 0; j < nborUids[i].Length; j++) {
int x = map[nborUids[i][j]];
if (distChunk[x] > dist) {
distChunk[x] = dist;
seedChunk[x] = uidSeeds[i];
}
}
}
dists.SetMany(map, distChunk);
seeds.SetMany(map, seedChunk);
}
public static void Main(string[] args) {
if (args.Length != 3) {
Console.Error.WriteLine("Usage: SHS.ASP <leader> <store> [f|b|u]");
} else {
var sw = Stopwatch.StartNew();
var shs = new Service(args[0]).OpenStore(Guid.Parse(args[1]));
var dists = shs.AllocateUidState<byte>();
var seeds = shs.AllocateUidState<long>();
var cands = shs.AllocateUidState<bool>();
var batch = new Batch<long>(1000000);
long numCands = 0;
bool fwd = args[2] == "f" || args[2] == "u";
bool bwd = args[2] == "b" || args[2] == "u";
foreach (long u in shs.Uids()) {
batch.Add(u);
if (batch.Full || shs.IsLastUid(u)) {
int[] fwdDegs = shs.BatchedGetDegree(batch, Dir.Fwd);
int[] bwdDegs = shs.BatchedGetDegree(batch, Dir.Bwd);
bool[] isCands = new bool[batch.Count];
for (int i = 0; i < batch.Count; i++) {
isCands[i] = fwd && bwd ? fwdDegs[i] + bwdDegs[i] > 1 : fwdDegs[i] > 0 && bwdDegs[i] > 0;
if (isCands[i]) numCands++;
}
cands.SetMany(batch, isCands);
batch.Reset();
}
}
System.Random rand = new System.Random(12345);
int dim = 0;
batch = new Batch<long>(1000);
for (; (long)1 << dim <= numCands; dim++) {
long numSeeds = (long)1 << dim;
dists.SetAll(x => 0xff);
seeds.SetAll(x => -1);
double remainingSamps = numSeeds;
double remainingCands = numCands;
foreach (var uc in cands.GetAll()) {
if (uc.val) {
if (rand.NextDouble() < remainingSamps / remainingCands) {
batch.Add(uc.uid);
remainingSamps--;
}
remainingCands--;
}
if (batch.Full || shs.IsLastUid(uc.uid)) {
dists.SetMany(batch, ((long[])batch).Select(x => (byte)0).ToArray());
seeds.SetMany(batch, batch);
batch.Reset();
}
}
for (byte k = 0; k < 0xff; k++) {
long hits = 0;
foreach (var x in dists.GetAll()) {
if (x.val == k) {
batch.Add(x.uid);
hits++;
}
if (batch.Full || shs.IsLastUid(x.uid)) {
if (bwd) ProcessBatch(shs, dists, seeds, batch, (byte)(k + 1), Dir.Fwd);
if (fwd) ProcessBatch(shs, dists, seeds, batch, (byte)(k + 1), Dir.Bwd);
batch.Reset();
}
}
if (hits == 0) break;
}
using (var wr = new BinaryWriter(new GZipStream(new BufferedStream(new FileStream("sketchslice-" + args[2] + "-" + dim.ToString("d2") + ".bin", FileMode.Create, FileAccess.Write)), CompressionMode.Compress))) {
long rch = 0; // Number of reachable URls
foreach (var x in dists.GetAll().Zip(seeds.GetAll(), (d, s) => System.Tuple.Create(d, s))) {
if (x.Item1.val < 0xff) rch++;
wr.Write(x.Item1.val);
wr.Write(x.Item2.val);
}
}
}
using (var wr = new BinaryWriter(new GZipStream(new BufferedStream(new FileStream("sketches-" + args[2] + ".bin", FileMode.Create, FileAccess.Write)), CompressionMode.Compress))) {
wr.Write(dim);
var readers = new BinaryReader[dim];
for (int i = 0; i < dim; i++) {
readers[i] = new BinaryReader(new GZipStream(new BufferedStream(new FileStream("sketchslice-" + args[2] + "-" + i.ToString("d2") + ".bin", FileMode.Open, FileAccess.Read)), CompressionMode.Decompress));
}
while (true) {
try {
for (int i = 0; i < dim; i++) {
wr.Write(readers[i].ReadByte());
wr.Write(readers[i].ReadInt64());
}
} catch (EndOfStreamException) {
break;
}
}
for (int i = 0; i < dim; i++) {
readers[i].Close();
}
}
Console.WriteLine("Done. Job took {0} seconds.", 0.001 * sw.ElapsedMilliseconds);
}
}
}
|
MicrosoftResearch/SHS
|
ASP/ASP.cs
|
C#
|
apache-2.0
| 5,581 |
package ca.uhn.fhir.rest.server;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* 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 static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBaseBinary;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.Include;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.api.Tag;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.valueset.BundleTypeEnum;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.api.PreferReturnEnum;
import ca.uhn.fhir.rest.api.SummaryEnum;
import ca.uhn.fhir.rest.method.ElementsParameter;
import ca.uhn.fhir.rest.method.RequestDetails;
import ca.uhn.fhir.rest.method.SummaryEnumParameter;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
public class RestfulServerUtils {
static final Pattern ACCEPT_HEADER_PATTERN = Pattern.compile("\\s*([a-zA-Z0-9+.*/-]+)\\s*(;\\s*([a-zA-Z]+)\\s*=\\s*([a-zA-Z0-9.]+)\\s*)?(,?)");
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(RestfulServerUtils.class);
private static final HashSet<String> TEXT_ENCODE_ELEMENTS = new HashSet<String>(Arrays.asList("Bundle", "*.text"));
public static void addProfileToBundleEntry(FhirContext theContext, IBaseResource theResource, String theServerBase) {
if (theResource instanceof IResource) {
TagList tl = ResourceMetadataKeyEnum.TAG_LIST.get((IResource) theResource);
if (tl == null) {
tl = new TagList();
ResourceMetadataKeyEnum.TAG_LIST.put((IResource) theResource, tl);
}
RuntimeResourceDefinition nextDef = theContext.getResourceDefinition(theResource);
String profile = nextDef.getResourceProfile(theServerBase);
if (isNotBlank(profile)) {
tl.add(new Tag(Tag.HL7_ORG_PROFILE_TAG, profile, null));
}
}
}
public static void configureResponseParser(RequestDetails theRequestDetails, IParser parser) {
// Pretty print
boolean prettyPrint = RestfulServerUtils.prettyPrintResponse(theRequestDetails.getServer(), theRequestDetails);
parser.setPrettyPrint(prettyPrint);
parser.setServerBaseUrl(theRequestDetails.getFhirServerBase());
// Summary mode
Set<SummaryEnum> summaryMode = RestfulServerUtils.determineSummaryMode(theRequestDetails);
// _elements
Set<String> elements = ElementsParameter.getElementsValueOrNull(theRequestDetails);
if (elements != null && summaryMode != null && !summaryMode.equals(Collections.singleton(SummaryEnum.FALSE))) {
throw new InvalidRequestException("Cannot combine the " + Constants.PARAM_SUMMARY + " and " + Constants.PARAM_ELEMENTS + " parameters");
}
Set<String> elementsAppliesTo = null;
if (elements != null && isNotBlank(theRequestDetails.getResourceName())) {
elementsAppliesTo = Collections.singleton(theRequestDetails.getResourceName());
}
if (summaryMode != null) {
if (summaryMode.contains(SummaryEnum.COUNT)) {
parser.setEncodeElements(Collections.singleton("Bundle.total"));
} else if (summaryMode.contains(SummaryEnum.TEXT)) {
parser.setEncodeElements(TEXT_ENCODE_ELEMENTS);
} else {
parser.setSuppressNarratives(summaryMode.contains(SummaryEnum.DATA));
parser.setSummaryMode(summaryMode.contains(SummaryEnum.TRUE));
}
}
if (elements != null && elements.size() > 0) {
Set<String> newElements = new HashSet<String>();
for (String next : elements) {
newElements.add("*." + next);
}
parser.setEncodeElements(newElements);
parser.setEncodeElementsAppliesToResourceTypes(elementsAppliesTo);
}
}
public static String createPagingLink(Set<Include> theIncludes, String theServerBase, String theSearchId, int theOffset, int theCount, EncodingEnum theResponseEncoding, boolean thePrettyPrint, BundleTypeEnum theBundleType) {
try {
StringBuilder b = new StringBuilder();
b.append(theServerBase);
b.append('?');
b.append(Constants.PARAM_PAGINGACTION);
b.append('=');
b.append(URLEncoder.encode(theSearchId, "UTF-8"));
b.append('&');
b.append(Constants.PARAM_PAGINGOFFSET);
b.append('=');
b.append(theOffset);
b.append('&');
b.append(Constants.PARAM_COUNT);
b.append('=');
b.append(theCount);
if (theResponseEncoding != null) {
b.append('&');
b.append(Constants.PARAM_FORMAT);
b.append('=');
b.append(theResponseEncoding.getRequestContentType());
}
if (thePrettyPrint) {
b.append('&');
b.append(Constants.PARAM_PRETTY);
b.append('=');
b.append(Constants.PARAM_PRETTY_VALUE_TRUE);
}
if (theIncludes != null) {
for (Include nextInclude : theIncludes) {
if (isNotBlank(nextInclude.getValue())) {
b.append('&');
b.append(Constants.PARAM_INCLUDE);
b.append('=');
b.append(URLEncoder.encode(nextInclude.getValue(), "UTF-8"));
}
}
}
if (theBundleType != null) {
b.append('&');
b.append(Constants.PARAM_BUNDLETYPE);
b.append('=');
b.append(theBundleType.getCode());
}
return b.toString();
} catch (UnsupportedEncodingException e) {
throw new Error("UTF-8 not supported", e);// should not happen
}
}
public static EncodingEnum determineRequestEncoding(RequestDetails theReq) {
EncodingEnum retVal = determineRequestEncodingNoDefault(theReq);
if (retVal != null) {
return retVal;
}
return EncodingEnum.XML;
}
public static EncodingEnum determineRequestEncodingNoDefault(RequestDetails theReq) {
EncodingEnum retVal = null;
Enumeration<String> acceptValues = theReq.getServletRequest().getHeaders(Constants.HEADER_CONTENT_TYPE);
if (acceptValues != null) {
while (acceptValues.hasMoreElements() && retVal == null) {
String nextAcceptHeaderValue = acceptValues.nextElement();
if (nextAcceptHeaderValue != null && isNotBlank(nextAcceptHeaderValue)) {
for (String nextPart : nextAcceptHeaderValue.split(",")) {
int scIdx = nextPart.indexOf(';');
if (scIdx == 0) {
continue;
}
if (scIdx != -1) {
nextPart = nextPart.substring(0, scIdx);
}
nextPart = nextPart.trim();
retVal = Constants.FORMAT_VAL_TO_ENCODING.get(nextPart);
if (retVal != null) {
break;
}
}
}
}
}
return retVal;
}
/**
* Returns null if the request doesn't express that it wants FHIR. If it expresses that it wants
* XML and JSON equally, returns thePrefer.
*/
public static EncodingEnum determineResponseEncodingNoDefault(HttpServletRequest theReq, EncodingEnum thePrefer) {
String[] format = theReq.getParameterValues(Constants.PARAM_FORMAT);
if (format != null) {
for (String nextFormat : format) {
EncodingEnum retVal = Constants.FORMAT_VAL_TO_ENCODING.get(nextFormat);
if (retVal != null) {
return retVal;
}
}
}
/*
* The Accept header is kind of ridiculous, e.g.
*/
// text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png, */*;q=0.5
Enumeration<String> acceptValues = theReq.getHeaders(Constants.HEADER_ACCEPT);
if (acceptValues != null) {
float bestQ = -1f;
EncodingEnum retVal = null;
while (acceptValues.hasMoreElements()) {
String nextAcceptHeaderValue = acceptValues.nextElement();
StringTokenizer tok = new StringTokenizer(nextAcceptHeaderValue, ",");
while (tok.hasMoreTokens()) {
String nextToken = tok.nextToken();
int startSpaceIndex = -1;
for (int i = 0; i < nextToken.length(); i++) {
if (nextToken.charAt(i) != ' ') {
startSpaceIndex = i;
break;
}
}
if (startSpaceIndex == -1) {
continue;
}
int endSpaceIndex = -1;
for (int i = startSpaceIndex; i < nextToken.length(); i++) {
if (nextToken.charAt(i) == ' ' || nextToken.charAt(i) == ';') {
endSpaceIndex = i;
break;
}
}
float q = 1.0f;
EncodingEnum encoding;
boolean pretty = false;
if (endSpaceIndex == -1) {
if (startSpaceIndex == 0) {
encoding = Constants.FORMAT_VAL_TO_ENCODING.get(nextToken);
} else {
encoding = Constants.FORMAT_VAL_TO_ENCODING.get(nextToken.substring(startSpaceIndex));
}
} else {
encoding = Constants.FORMAT_VAL_TO_ENCODING.get(nextToken.substring(startSpaceIndex, endSpaceIndex));
String remaining = nextToken.substring(endSpaceIndex + 1);
StringTokenizer qualifierTok = new StringTokenizer(remaining, ";");
while (qualifierTok.hasMoreTokens()) {
String nextQualifier = qualifierTok.nextToken();
int equalsIndex = nextQualifier.indexOf('=');
if (equalsIndex != -1) {
String nextQualifierKey = nextQualifier.substring(0, equalsIndex).trim();
String nextQualifierValue = nextQualifier.substring(equalsIndex+1, nextQualifier.length()).trim();
if (nextQualifierKey.equals("q")) {
try {
q = Float.parseFloat(nextQualifierValue);
q = Math.max(q, 0.0f);
} catch (NumberFormatException e) {
ourLog.debug("Invalid Accept header q value: {}", nextQualifierValue);
}
}
}
}
}
if (encoding != null) {
if (q > bestQ || (q == bestQ && encoding == thePrefer)) {
retVal = encoding;
bestQ = q;
}
}
}
//
//
//
//
// Matcher m = ACCEPT_HEADER_PATTERN.matcher(nextAcceptHeaderValue);
// float q = 1.0f;
// while (m.find()) {
// String contentTypeGroup = m.group(1);
// EncodingEnum encoding = Constants.FORMAT_VAL_TO_ENCODING.get(contentTypeGroup);
// if (encoding != null) {
//
// String name = m.group(3);
// String value = m.group(4);
// if (name != null && value != null) {
// if ("q".equals(name)) {
// try {
// q = Float.parseFloat(value);
// q = Math.max(q, 0.0f);
// } catch (NumberFormatException e) {
// ourLog.debug("Invalid Accept header q value: {}", value);
// }
// }
// }
// }
//
// if (encoding != null) {
// if (q > bestQ || (q == bestQ && encoding == thePrefer)) {
// retVal = encoding;
// bestQ = q;
// }
// }
//
// if (!",".equals(m.group(5))) {
// break;
// }
// }
//
}
return retVal;
}
return null;
}
/**
* Determine whether a response should be given in JSON or XML format based on the incoming HttpServletRequest's <code>"_format"</code> parameter and <code>"Accept:"</code> HTTP header.
*/
public static EncodingEnum determineResponseEncodingWithDefault(RestfulServer theServer, HttpServletRequest theReq) {
EncodingEnum retVal = determineResponseEncodingNoDefault(theReq, theServer.getDefaultResponseEncoding());
if (retVal == null) {
retVal = theServer.getDefaultResponseEncoding();
}
return retVal;
}
public static Set<SummaryEnum> determineSummaryMode(RequestDetails theRequest) {
Map<String, String[]> requestParams = theRequest.getParameters();
Set<SummaryEnum> retVal = SummaryEnumParameter.getSummaryValueOrNull(theRequest);
if (retVal == null) {
/*
* HAPI originally supported a custom parameter called _narrative, but this has been superceded by an official parameter called _summary
*/
String[] narrative = requestParams.get(Constants.PARAM_NARRATIVE);
if (narrative != null && narrative.length > 0) {
try {
NarrativeModeEnum narrativeMode = NarrativeModeEnum.valueOfCaseInsensitive(narrative[0]);
switch (narrativeMode) {
case NORMAL:
retVal = Collections.singleton(SummaryEnum.FALSE);
break;
case ONLY:
retVal = Collections.singleton(SummaryEnum.TEXT);
break;
case SUPPRESS:
retVal = Collections.singleton(SummaryEnum.DATA);
break;
}
} catch (IllegalArgumentException e) {
ourLog.debug("Invalid {} parameger: {}", Constants.PARAM_NARRATIVE, narrative[0]);
}
}
}
if (retVal == null) {
retVal = Collections.singleton(SummaryEnum.FALSE);
}
return retVal;
}
public static Integer extractCountParameter(RequestDetails theRequest) {
String paramName = Constants.PARAM_COUNT;
return tryToExtractNamedParameter(theRequest, paramName);
}
public static IParser getNewParser(FhirContext theContext, RequestDetails theRequestDetails) {
// Determine response encoding
EncodingEnum responseEncoding = RestfulServerUtils.determineResponseEncodingWithDefault(theRequestDetails.getServer(), theRequestDetails.getServletRequest());
IParser parser;
switch (responseEncoding) {
case JSON:
parser = theContext.newJsonParser();
break;
case XML:
default:
parser = theContext.newXmlParser();
break;
}
configureResponseParser(theRequestDetails, parser);
return parser;
}
static Writer getWriter(HttpServletResponse theHttpResponse, boolean theRespondGzip) throws UnsupportedEncodingException, IOException {
Writer writer;
if (theRespondGzip) {
theHttpResponse.addHeader(Constants.HEADER_CONTENT_ENCODING, Constants.ENCODING_GZIP);
writer = new OutputStreamWriter(new GZIPOutputStream(theHttpResponse.getOutputStream()), "UTF-8");
} else {
writer = theHttpResponse.getWriter();
}
return writer;
}
public static Set<String> parseAcceptHeaderAndReturnHighestRankedOptions(HttpServletRequest theRequest) {
Set<String> retVal = new HashSet<String>();
Enumeration<String> acceptValues = theRequest.getHeaders(Constants.HEADER_ACCEPT);
if (acceptValues != null) {
float bestQ = -1f;
while (acceptValues.hasMoreElements()) {
String nextAcceptHeaderValue = acceptValues.nextElement();
Matcher m = ACCEPT_HEADER_PATTERN.matcher(nextAcceptHeaderValue);
float q = 1.0f;
while (m.find()) {
String contentTypeGroup = m.group(1);
if (isNotBlank(contentTypeGroup)) {
String name = m.group(3);
String value = m.group(4);
if (name != null && value != null) {
if ("q".equals(name)) {
try {
q = Float.parseFloat(value);
q = Math.max(q, 0.0f);
} catch (NumberFormatException e) {
ourLog.debug("Invalid Accept header q value: {}", value);
}
}
}
if (q > bestQ) {
retVal.clear();
bestQ = q;
}
if (q == bestQ) {
retVal.add(contentTypeGroup.trim());
}
}
if (!",".equals(m.group(5))) {
break;
}
}
}
}
return retVal;
}
public static PreferReturnEnum parsePreferHeader(String theValue) {
if (isBlank(theValue)) {
return null;
}
StringTokenizer tok = new StringTokenizer(theValue, ",");
while (tok.hasMoreTokens()) {
String next = tok.nextToken();
int eqIndex = next.indexOf('=');
if (eqIndex == -1 || eqIndex >= next.length() - 2) {
continue;
}
String key = next.substring(0, eqIndex).trim();
if (key.equals(Constants.HEADER_PREFER_RETURN) == false) {
continue;
}
String value = next.substring(eqIndex + 1).trim();
if (value.length() < 2) {
continue;
}
if ('"' == value.charAt(0) && '"' == value.charAt(value.length() - 1)) {
value = value.substring(1, value.length() - 1);
}
return PreferReturnEnum.fromHeaderValue(value);
}
return null;
}
public static boolean prettyPrintResponse(RestfulServer theServer, RequestDetails theRequest) {
Map<String, String[]> requestParams = theRequest.getParameters();
String[] pretty = requestParams.get(Constants.PARAM_PRETTY);
boolean prettyPrint;
if (pretty != null && pretty.length > 0) {
if (Constants.PARAM_PRETTY_VALUE_TRUE.equals(pretty[0])) {
prettyPrint = true;
} else {
prettyPrint = false;
}
} else {
prettyPrint = theServer.isDefaultPrettyPrint();
Enumeration<String> acceptValues = theRequest.getServletRequest().getHeaders(Constants.HEADER_ACCEPT);
if (acceptValues != null) {
while (acceptValues.hasMoreElements()) {
String nextAcceptHeaderValue = acceptValues.nextElement();
if (nextAcceptHeaderValue.contains("pretty=true")) {
prettyPrint = true;
}
}
}
}
return prettyPrint;
}
public static void streamResponseAsBundle(RestfulServer theServer, HttpServletResponse theHttpResponse, Bundle bundle, String theServerBase, Set<SummaryEnum> theSummaryMode, boolean theRespondGzip,
boolean theRequestIsBrowser, RequestDetails theRequestDetails) throws IOException {
assert!theServerBase.endsWith("/");
theHttpResponse.setStatus(200);
// Determine response encoding
EncodingEnum responseEncoding = RestfulServerUtils.determineResponseEncodingWithDefault(theServer, theRequestDetails.getServletRequest());
if (theRequestIsBrowser && theServer.isUseBrowserFriendlyContentTypes()) {
theHttpResponse.setContentType(responseEncoding.getBrowserFriendlyBundleContentType());
} else {
theHttpResponse.setContentType(responseEncoding.getBundleContentType());
}
theHttpResponse.setCharacterEncoding(Constants.CHARSET_NAME_UTF8);
theServer.addHeadersToResponse(theHttpResponse);
Writer writer = RestfulServerUtils.getWriter(theHttpResponse, theRespondGzip);
try {
IParser parser = RestfulServerUtils.getNewParser(theServer.getFhirContext(), theRequestDetails);
if (theSummaryMode.contains(SummaryEnum.TEXT)) {
parser.setEncodeElements(TEXT_ENCODE_ELEMENTS);
}
parser.encodeBundleToWriter(bundle, writer);
} finally {
writer.close();
}
}
public static void streamResponseAsResource(RestfulServer theServer, HttpServletResponse theHttpResponse, IBaseResource theResource, boolean theRequestIsBrowser, Set<SummaryEnum> theSummaryMode,
int stausCode, boolean theRespondGzip, boolean theAddContentLocationHeader, RequestDetails theRequestDetails) throws IOException {
theHttpResponse.setStatus(stausCode);
// Determine response encoding
EncodingEnum responseEncoding = RestfulServerUtils.determineResponseEncodingNoDefault(theRequestDetails.getServletRequest(), theServer.getDefaultResponseEncoding());
String serverBase = theRequestDetails.getFhirServerBase();
if (theAddContentLocationHeader && theResource.getIdElement() != null && theResource.getIdElement().hasIdPart() && isNotBlank(serverBase)) {
String resName = theServer.getFhirContext().getResourceDefinition(theResource).getName();
IIdType fullId = theResource.getIdElement().withServerBase(serverBase, resName);
theHttpResponse.addHeader(Constants.HEADER_CONTENT_LOCATION, fullId.getValue());
}
if (theServer.getETagSupport() == ETagSupportEnum.ENABLED) {
if (theResource.getIdElement().hasVersionIdPart()) {
theHttpResponse.addHeader(Constants.HEADER_ETAG, "W/\"" + theResource.getIdElement().getVersionIdPart() + '"');
}
}
if (theServer.getAddProfileTag() != AddProfileTagEnum.NEVER) {
RuntimeResourceDefinition def = theServer.getFhirContext().getResourceDefinition(theResource);
if (theServer.getAddProfileTag() == AddProfileTagEnum.ALWAYS || !def.isStandardProfile()) {
addProfileToBundleEntry(theServer.getFhirContext(), theResource, serverBase);
}
}
if (theResource instanceof IBaseBinary && responseEncoding == null) {
IBaseBinary bin = (IBaseBinary) theResource;
if (isNotBlank(bin.getContentType())) {
theHttpResponse.setContentType(bin.getContentType());
} else {
theHttpResponse.setContentType(Constants.CT_OCTET_STREAM);
}
if (bin.getContent() == null || bin.getContent().length == 0) {
return;
}
// Force binary resources to download - This is a security measure to prevent
// malicious images or HTML blocks being served up as content.
theHttpResponse.addHeader(Constants.HEADER_CONTENT_DISPOSITION, "Attachment;");
theHttpResponse.setContentLength(bin.getContent().length);
ServletOutputStream oos = theHttpResponse.getOutputStream();
oos.write(bin.getContent());
oos.close();
return;
}
// Ok, we're not serving a binary resource, so apply default encoding
responseEncoding = responseEncoding != null ? responseEncoding : theServer.getDefaultResponseEncoding();
boolean encodingDomainResourceAsText = theSummaryMode.contains(SummaryEnum.TEXT);
if (encodingDomainResourceAsText) {
/*
* If the user requests "text" for a bundle, only suppress the non text elements in the Element.entry.resource parts, we're not streaming just the narrative as HTML (since bundles don't even
* have one)
*/
if ("Bundle".equals(theServer.getFhirContext().getResourceDefinition(theResource).getName())) {
encodingDomainResourceAsText = false;
}
}
if (theRequestIsBrowser && theServer.isUseBrowserFriendlyContentTypes()) {
theHttpResponse.setContentType(responseEncoding.getBrowserFriendlyBundleContentType());
} else if (encodingDomainResourceAsText) {
theHttpResponse.setContentType(Constants.CT_HTML);
} else {
theHttpResponse.setContentType(responseEncoding.getResourceContentType());
}
theHttpResponse.setCharacterEncoding(Constants.CHARSET_NAME_UTF8);
theServer.addHeadersToResponse(theHttpResponse);
if (theResource instanceof IResource) {
InstantDt lastUpdated = ResourceMetadataKeyEnum.UPDATED.get((IResource) theResource);
if (lastUpdated != null && lastUpdated.isEmpty() == false) {
theHttpResponse.addHeader(Constants.HEADER_LAST_MODIFIED, DateUtils.formatDate(lastUpdated.getValue()));
}
TagList list = (TagList) ((IResource) theResource).getResourceMetadata().get(ResourceMetadataKeyEnum.TAG_LIST);
if (list != null) {
for (Tag tag : list) {
if (StringUtils.isNotBlank(tag.getTerm())) {
theHttpResponse.addHeader(Constants.HEADER_CATEGORY, tag.toHeaderValue());
}
}
}
} else {
Date lastUpdated = ((IAnyResource) theResource).getMeta().getLastUpdated();
if (lastUpdated != null) {
theHttpResponse.addHeader(Constants.HEADER_LAST_MODIFIED, DateUtils.formatDate(lastUpdated));
}
}
Writer writer = getWriter(theHttpResponse, theRespondGzip);
try {
if (encodingDomainResourceAsText && theResource instanceof IResource) {
writer.append(((IResource) theResource).getText().getDiv().getValueAsString());
} else {
IParser parser = getNewParser(theServer.getFhirContext(), theRequestDetails);
parser.encodeResourceToWriter(theResource, writer);
}
} finally {
writer.close();
}
}
// static Integer tryToExtractNamedParameter(HttpServletRequest theRequest, String name) {
// String countString = theRequest.getParameter(name);
// Integer count = null;
// if (isNotBlank(countString)) {
// try {
// count = Integer.parseInt(countString);
// } catch (NumberFormatException e) {
// ourLog.debug("Failed to parse _count value '{}': {}", countString, e);
// }
// }
// return count;
// }
public static void validateResourceListNotNull(List<? extends IBaseResource> theResourceList) {
if (theResourceList == null) {
throw new InternalErrorException("IBundleProvider returned a null list of resources - This is not allowed");
}
}
private static enum NarrativeModeEnum {
NORMAL, ONLY, SUPPRESS;
public static NarrativeModeEnum valueOfCaseInsensitive(String theCode) {
return valueOf(NarrativeModeEnum.class, theCode.toUpperCase());
}
}
public static Integer tryToExtractNamedParameter(RequestDetails theRequest, String theParamName) {
String[] retVal = theRequest.getParameters().get(theParamName);
if (retVal == null) {
return null;
}
try {
return Integer.parseInt(retVal[0]);
} catch (NumberFormatException e) {
ourLog.debug("Failed to parse {} value '{}': {}", new Object[] {theParamName, retVal[0], e});
return null;
}
}
}
|
bjornna/hapi-fhir
|
hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/RestfulServerUtils.java
|
Java
|
apache-2.0
| 25,340 |
/***
Copyright (c) 2012-2015 CommonsWare, LLC
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.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.mapsv2.popups;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class AbstractMapActivity extends Activity {
static final String TAG_ERROR_DIALOG_FRAGMENT="errorDialog";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.legal) {
startActivity(new Intent(this, LegalNoticesActivity.class));
return(true);
}
return super.onOptionsItemSelected(item);
}
protected boolean readyToGo() {
GoogleApiAvailability checker=
GoogleApiAvailability.getInstance();
int status=checker.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS) {
if (getVersionFromPackageManager(this)>=2) {
return(true);
}
else {
Toast.makeText(this, R.string.no_maps, Toast.LENGTH_LONG).show();
finish();
}
}
else if (checker.isUserResolvableError(status)) {
ErrorDialogFragment.newInstance(status)
.show(getFragmentManager(),
TAG_ERROR_DIALOG_FRAGMENT);
}
else {
Toast.makeText(this, R.string.no_maps, Toast.LENGTH_LONG).show();
finish();
}
return(false);
}
public static class ErrorDialogFragment extends DialogFragment {
static final String ARG_ERROR_CODE="errorCode";
static ErrorDialogFragment newInstance(int errorCode) {
Bundle args=new Bundle();
ErrorDialogFragment result=new ErrorDialogFragment();
args.putInt(ARG_ERROR_CODE, errorCode);
result.setArguments(args);
return(result);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args=getArguments();
GoogleApiAvailability checker=
GoogleApiAvailability.getInstance();
return(checker.getErrorDialog(getActivity(),
args.getInt(ARG_ERROR_CODE), 0));
}
@Override
public void onDismiss(DialogInterface dlg) {
if (getActivity()!=null) {
getActivity().finish();
}
}
}
// following from
// https://android.googlesource.com/platform/cts/+/master/tests/tests/graphics/src/android/opengl/cts/OpenGlEsVersionTest.java
/*
* Copyright (C) 2010 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.
*/
private static int getVersionFromPackageManager(Context context) {
PackageManager packageManager=context.getPackageManager();
FeatureInfo[] featureInfos=
packageManager.getSystemAvailableFeatures();
if (featureInfos != null && featureInfos.length > 0) {
for (FeatureInfo featureInfo : featureInfos) {
// Null feature name means this feature is the open
// gl es version feature.
if (featureInfo.name == null) {
if (featureInfo.reqGlEsVersion != FeatureInfo.GL_ES_VERSION_UNDEFINED) {
return getMajorVersion(featureInfo.reqGlEsVersion);
}
else {
return 1; // Lack of property means OpenGL ES
// version 1
}
}
}
}
return 1;
}
/** @see FeatureInfo#getGlEsVersion() */
private static int getMajorVersion(int glEsVersion) {
return((glEsVersion & 0xffff0000) >> 16);
}
}
|
janzoner/cw-omnibus
|
MapsV2/Popups/app/src/main/java/com/commonsware/android/mapsv2/popups/AbstractMapActivity.java
|
Java
|
apache-2.0
| 5,111 |
/*
* 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.intellij.refactoring.extractMethod;
import com.intellij.codeInsight.*;
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil;
import com.intellij.codeInsight.daemon.impl.quickfix.AnonymousTargetClassPreselectionUtil;
import com.intellij.codeInsight.generation.GenerateMembersUtil;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInsight.intention.AddAnnotationPsiFix;
import com.intellij.codeInsight.intention.impl.AddNullableNotNullAnnotationFix;
import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.codeInspection.dataFlow.*;
import com.intellij.codeInspection.dataFlow.instructions.BranchingInstruction;
import com.intellij.codeInspection.dataFlow.instructions.CheckReturnValueInstruction;
import com.intellij.codeInspection.dataFlow.instructions.Instruction;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.PsiClassListCellRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Pass;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.*;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.controlFlow.ControlFlow;
import com.intellij.psi.impl.source.codeStyle.JavaCodeStyleManagerImpl;
import com.intellij.psi.scope.processor.VariablesProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.*;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.extractMethodObject.ExtractMethodObjectHandler;
import com.intellij.refactoring.introduceField.ElementToWorkOn;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
import com.intellij.refactoring.util.*;
import com.intellij.refactoring.util.classMembers.ElementNeedsThis;
import com.intellij.refactoring.util.duplicates.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.*;
public class ExtractMethodProcessor implements MatchProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.extractMethod.ExtractMethodProcessor");
protected final Project myProject;
private final Editor myEditor;
protected final PsiElement[] myElements;
private final PsiBlockStatement myEnclosingBlockStatement;
private final PsiType myForcedReturnType;
private final String myRefactoringName;
protected final String myInitialMethodName;
private final String myHelpId;
private final PsiManager myManager;
private final PsiElementFactory myElementFactory;
private final CodeStyleManager myStyleManager;
private PsiExpression myExpression;
private PsiElement myCodeFragmentMember; // parent of myCodeFragment
protected String myMethodName; // name for extracted method
protected PsiType myReturnType; // return type for extracted method
protected PsiTypeParameterList myTypeParameterList; //type parameter list of extracted method
protected VariableData[] myVariableDatum; // parameter data for extracted method
protected PsiClassType[] myThrownExceptions; // exception to declare as thrown by extracted method
protected boolean myStatic; // whether to declare extracted method static
protected PsiClass myTargetClass; // class to create the extracted method in
private PsiElement myAnchor; // anchor to insert extracted method after it
protected ControlFlowWrapper myControlFlowWrapper;
protected InputVariables myInputVariables; // input variables
protected PsiVariable[] myOutputVariables; // output variables
protected PsiVariable myOutputVariable; // the only output variable
protected PsiVariable myArtificialOutputVariable;
private Collection<PsiStatement> myExitStatements;
private boolean myHasReturnStatement; // there is a return statement
private boolean myHasReturnStatementOutput; // there is a return statement and its type is not void
protected boolean myHasExpressionOutput; // extracted code is an expression with non-void type
private boolean myNeedChangeContext; // target class is not immediate container of the code to be extracted
private boolean myShowErrorDialogs = true;
protected boolean myCanBeStatic;
protected boolean myCanBeChainedConstructor;
protected boolean myIsChainedConstructor;
private List<Match> myDuplicates;
@PsiModifier.ModifierConstant protected String myMethodVisibility = PsiModifier.PRIVATE;
protected boolean myGenerateConditionalExit;
protected PsiStatement myFirstExitStatementCopy;
protected PsiMethod myExtractedMethod;
private PsiMethodCallExpression myMethodCall;
protected boolean myNullConditionalCheck;
protected boolean myNotNullConditionalCheck;
private Nullness myNullness;
public ExtractMethodProcessor(Project project,
Editor editor,
PsiElement[] elements,
PsiType forcedReturnType,
String refactoringName,
String initialMethodName,
String helpId) {
myProject = project;
myEditor = editor;
if (elements.length != 1 || !(elements[0] instanceof PsiBlockStatement)) {
myElements = elements.length == 1 && elements[0] instanceof PsiParenthesizedExpression
? new PsiElement[] {PsiUtil.skipParenthesizedExprDown((PsiExpression)elements[0])} : elements;
myEnclosingBlockStatement = null;
}
else {
myEnclosingBlockStatement = (PsiBlockStatement)elements[0];
PsiElement[] codeBlockChildren = myEnclosingBlockStatement.getCodeBlock().getChildren();
myElements = processCodeBlockChildren(codeBlockChildren);
}
myForcedReturnType = forcedReturnType;
myRefactoringName = refactoringName;
myInitialMethodName = initialMethodName;
myHelpId = helpId;
myManager = PsiManager.getInstance(myProject);
myElementFactory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
myStyleManager = CodeStyleManager.getInstance(myProject);
}
private static PsiElement[] processCodeBlockChildren(PsiElement[] codeBlockChildren) {
int resultLast = codeBlockChildren.length;
if (codeBlockChildren.length == 0) return PsiElement.EMPTY_ARRAY;
final PsiElement first = codeBlockChildren[0];
int resultStart = 0;
if (PsiUtil.isJavaToken(first, JavaTokenType.LBRACE)) {
resultStart++;
}
final PsiElement last = codeBlockChildren[codeBlockChildren.length - 1];
if (PsiUtil.isJavaToken(last, JavaTokenType.RBRACE)) {
resultLast--;
}
final ArrayList<PsiElement> result = new ArrayList<>();
for (int i = resultStart; i < resultLast; i++) {
PsiElement element = codeBlockChildren[i];
if (!(element instanceof PsiWhiteSpace)) {
result.add(element);
}
}
return PsiUtilCore.toPsiElementArray(result);
}
/**
* Method for test purposes
*/
public void setShowErrorDialogs(boolean showErrorDialogs) {
myShowErrorDialogs = showErrorDialogs;
}
public void setChainedConstructor(final boolean isChainedConstructor) {
myIsChainedConstructor = isChainedConstructor;
}
public boolean prepare() throws PrepareFailedException {
return prepare(null);
}
/**
* Invoked in atomic action
*/
public boolean prepare(@Nullable Pass<ExtractMethodProcessor> pass) throws PrepareFailedException {
myExpression = null;
if (myElements.length == 1 && myElements[0] instanceof PsiExpression) {
final PsiExpression expression = (PsiExpression)myElements[0];
if (expression instanceof PsiAssignmentExpression && expression.getParent() instanceof PsiExpressionStatement) {
myElements[0] = expression.getParent();
}
else {
myExpression = expression;
}
}
final PsiElement codeFragment = ControlFlowUtil.findCodeFragment(myElements[0]);
myCodeFragmentMember = codeFragment.getUserData(ElementToWorkOn.PARENT);
if (myCodeFragmentMember == null) {
myCodeFragmentMember = codeFragment.getParent();
}
if (myCodeFragmentMember == null) {
myCodeFragmentMember = ControlFlowUtil.findCodeFragment(codeFragment.getContext()).getParent();
}
myControlFlowWrapper = new ControlFlowWrapper(myProject, codeFragment, myElements);
try {
myExitStatements = myControlFlowWrapper.prepareExitStatements(myElements, codeFragment);
if (myControlFlowWrapper.isGenerateConditionalExit()) {
myGenerateConditionalExit = true;
} else {
myHasReturnStatement = myExpression == null && myControlFlowWrapper.isReturnPresentBetween();
}
myFirstExitStatementCopy = myControlFlowWrapper.getFirstExitStatementCopy();
}
catch (ControlFlowWrapper.ExitStatementsNotSameException e) {
myExitStatements = myControlFlowWrapper.getExitStatements();
myNotNullConditionalCheck = areAllExitPointsNotNull(getExpectedReturnType());
if (!myNotNullConditionalCheck) {
showMultipleExitPointsMessage();
return false;
}
}
myOutputVariables = myControlFlowWrapper.getOutputVariables();
return chooseTargetClass(codeFragment, pass);
}
private boolean checkExitPoints() throws PrepareFailedException {
PsiType expressionType = null;
if (myExpression != null) {
if (myForcedReturnType != null) {
expressionType = myForcedReturnType;
}
else {
expressionType = RefactoringUtil.getTypeByExpressionWithExpectedType(myExpression);
if (expressionType == null && !(myExpression.getParent() instanceof PsiExpressionStatement)) {
expressionType = PsiType.getJavaLangObject(myExpression.getManager(), GlobalSearchScope.allScope(myProject));
}
}
}
if (expressionType == null) {
expressionType = PsiType.VOID;
}
myHasExpressionOutput = !PsiType.VOID.equals(expressionType);
final PsiType returnStatementType = getExpectedReturnType();
myHasReturnStatementOutput = myHasReturnStatement && returnStatementType != null && !PsiType.VOID.equals(returnStatementType);
if (myGenerateConditionalExit && myOutputVariables.length == 1) {
if (!(myOutputVariables[0].getType() instanceof PsiPrimitiveType)) {
myNullConditionalCheck = isNullInferred(myOutputVariables[0].getName()) && getReturnsNullability(true);
}
myNotNullConditionalCheck = areAllExitPointsNotNull(returnStatementType);
}
if (!myHasReturnStatementOutput && checkOutputVariablesCount() && !myNullConditionalCheck && !myNotNullConditionalCheck) {
showMultipleOutputMessage(expressionType);
return false;
}
myOutputVariable = myOutputVariables.length > 0 ? myOutputVariables[0] : null;
if (myNotNullConditionalCheck) {
myReturnType = returnStatementType instanceof PsiPrimitiveType ? ((PsiPrimitiveType)returnStatementType).getBoxedType(myCodeFragmentMember)
: returnStatementType;
} else if (myHasReturnStatementOutput) {
myReturnType = returnStatementType;
}
else if (myOutputVariable != null) {
myReturnType = myOutputVariable.getType();
}
else if (myGenerateConditionalExit) {
myReturnType = PsiType.BOOLEAN;
}
else {
myReturnType = expressionType;
}
PsiElement container = PsiTreeUtil.getParentOfType(myElements[0], PsiClass.class, PsiMethod.class);
while (container instanceof PsiMethod && ((PsiMethod)container).getContainingClass() != myTargetClass) {
container = PsiTreeUtil.getParentOfType(container, PsiMethod.class, true);
}
if (container instanceof PsiMethod) {
PsiElement[] elements = myElements;
if (myExpression == null) {
if (myOutputVariable != null) {
elements = ArrayUtil.append(myElements, myOutputVariable, PsiElement.class);
}
if (myCodeFragmentMember instanceof PsiMethod && myReturnType == ((PsiMethod)myCodeFragmentMember).getReturnType()) {
elements = ArrayUtil.append(myElements, ((PsiMethod)myCodeFragmentMember).getReturnTypeElement(), PsiElement.class);
}
}
myTypeParameterList = RefactoringUtil.createTypeParameterListWithUsedTypeParameters(((PsiMethod)container).getTypeParameterList(),
elements);
}
List<PsiClassType> exceptions = ExceptionUtil.getThrownCheckedExceptions(myElements);
myThrownExceptions = exceptions.toArray(new PsiClassType[exceptions.size()]);
if (container instanceof PsiMethod) {
checkLocalClasses((PsiMethod) container);
}
return true;
}
private PsiType getExpectedReturnType() {
return myCodeFragmentMember instanceof PsiMethod
? ((PsiMethod)myCodeFragmentMember).getReturnType()
: myCodeFragmentMember instanceof PsiLambdaExpression
? LambdaUtil.getFunctionalInterfaceReturnType((PsiLambdaExpression)myCodeFragmentMember)
: null;
}
@Nullable
protected PsiVariable getArtificialOutputVariable() {
if (myOutputVariables.length == 0 && myExitStatements.isEmpty()) {
if (myCanBeChainedConstructor) {
final Set<PsiField> fields = new HashSet<>();
for (PsiElement element : myElements) {
element.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
super.visitReferenceExpression(expression);
final PsiElement resolve = expression.resolve();
if (resolve instanceof PsiField && ((PsiField)resolve).hasModifierProperty(PsiModifier.FINAL) &&
PsiUtil.isAccessedForWriting(expression)) {
fields.add((PsiField)resolve);
}
}
});
}
if (!fields.isEmpty()) {
return fields.size() == 1 ? fields.iterator().next() : null;
}
}
final VariablesProcessor processor = new VariablesProcessor(true) {
@Override
protected boolean check(PsiVariable var, ResolveState state) {
return isDeclaredInside(var);
}
};
PsiScopesUtil.treeWalkUp(processor, myElements[myElements.length - 1], myCodeFragmentMember);
if (processor.size() == 1) {
return processor.getResult(0);
}
}
return null;
}
private boolean areAllExitPointsNotNull(PsiType returnStatementType) {
if (insertNotNullCheckIfPossible() && myControlFlowWrapper.getOutputVariables(false).length == 0) {
if (returnStatementType != null && !PsiType.VOID.equals(returnStatementType)) {
return getReturnsNullability(false);
}
}
return false;
}
/**
* @param nullsExpected when true check that all returned values are null, when false check that all returned values can't be null
*/
private boolean getReturnsNullability(boolean nullsExpected) {
PsiElement body = null;
if (myCodeFragmentMember instanceof PsiMethod) {
body = ((PsiMethod)myCodeFragmentMember).getBody();
}
else if (myCodeFragmentMember instanceof PsiLambdaExpression) {
body = ((PsiLambdaExpression)myCodeFragmentMember).getBody();
}
if (body == null) return false;
Set<PsiExpression> returnedExpressions = StreamEx.of(myExitStatements)
.select(PsiReturnStatement.class)
.map(PsiReturnStatement::getReturnValue)
.nonNull()
.toSet();
for (Iterator<PsiExpression> it = returnedExpressions.iterator(); it.hasNext(); ) {
PsiType type = it.next().getType();
if (nullsExpected) {
if (type == PsiType.NULL) {
it.remove(); // don't need to check
}
else if (type instanceof PsiPrimitiveType) {
return false;
}
}
else {
if (type == PsiType.NULL) {
return false;
}
else if (type instanceof PsiPrimitiveType) {
it.remove(); // don't need to check
}
}
}
if (returnedExpressions.isEmpty()) return true;
class ReturnChecker extends StandardInstructionVisitor {
boolean myResult = true;
@Override
public DfaInstructionState[] visitCheckReturnValue(CheckReturnValueInstruction instruction,
DataFlowRunner runner,
DfaMemoryState memState) {
PsiElement aReturn = instruction.getReturn();
if (aReturn instanceof PsiExpression && returnedExpressions.contains(aReturn)) {
myResult &= nullsExpected ? memState.isNull(memState.peek()) : memState.isNotNull(memState.peek());
}
return super.visitCheckReturnValue(instruction, runner, memState);
}
}
final StandardDataFlowRunner dfaRunner = new StandardDataFlowRunner();
final ReturnChecker returnChecker = new ReturnChecker();
if (dfaRunner.analyzeMethod(body, returnChecker) == RunnerResult.OK) {
return returnChecker.myResult;
}
return false;
}
protected boolean insertNotNullCheckIfPossible() {
return true;
}
private boolean isNullInferred(String exprText) {
final PsiCodeBlock block = myElementFactory.createCodeBlockFromText("{}", myElements[0]);
for (PsiElement element : myElements) {
block.add(element);
}
final PsiIfStatement statementFromText = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + exprText + " == null);", null);
block.add(statementFromText);
final StandardDataFlowRunner dfaRunner = new StandardDataFlowRunner();
final StandardInstructionVisitor visitor = new StandardInstructionVisitor();
final RunnerResult rc = dfaRunner.analyzeMethod(block, visitor);
if (rc == RunnerResult.OK) {
final Pair<Set<Instruction>, Set<Instruction>> expressions = dfaRunner.getConstConditionalExpressions();
final Set<Instruction> set = expressions.getSecond();
for (Instruction instruction : set) {
if (instruction instanceof BranchingInstruction) {
if (((BranchingInstruction)instruction).getPsiAnchor().getText().equals(statementFromText.getCondition().getText())) {
return true;
}
}
}
}
return false;
}
protected boolean checkOutputVariablesCount() {
int outputCount = (myHasExpressionOutput ? 1 : 0) + (myGenerateConditionalExit ? 1 : 0) + myOutputVariables.length;
return outputCount > 1;
}
private void checkCanBeChainedConstructor() {
if (!(myCodeFragmentMember instanceof PsiMethod)) {
return;
}
final PsiMethod method = (PsiMethod)myCodeFragmentMember;
if (!method.isConstructor() || !PsiType.VOID.equals(myReturnType)) {
return;
}
final PsiCodeBlock body = method.getBody();
if (body == null) return;
final PsiStatement[] psiStatements = body.getStatements();
if (psiStatements.length > 0 && myElements [0] == psiStatements [0]) {
myCanBeChainedConstructor = true;
}
}
private void checkLocalClasses(final PsiMethod container) throws PrepareFailedException {
final List<PsiClass> localClasses = new ArrayList<>();
container.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitClass(final PsiClass aClass) {
localClasses.add(aClass);
}
@Override public void visitAnonymousClass(final PsiAnonymousClass aClass) {
visitElement(aClass);
}
@Override public void visitTypeParameter(final PsiTypeParameter classParameter) {
visitElement(classParameter);
}
});
for(PsiClass localClass: localClasses) {
final boolean classExtracted = isExtractedElement(localClass);
final List<PsiElement> extractedReferences = Collections.synchronizedList(new ArrayList<PsiElement>());
final List<PsiElement> remainingReferences = Collections.synchronizedList(new ArrayList<PsiElement>());
ReferencesSearch.search(localClass).forEach(psiReference -> {
final PsiElement element = psiReference.getElement();
final boolean elementExtracted = isExtractedElement(element);
if (elementExtracted && !classExtracted) {
extractedReferences.add(element);
return false;
}
if (!elementExtracted && classExtracted) {
remainingReferences.add(element);
return false;
}
return true;
});
if (!extractedReferences.isEmpty()) {
throw new PrepareFailedException("Cannot extract method because the selected code fragment uses local classes defined outside of the fragment", extractedReferences.get(0));
}
if (!remainingReferences.isEmpty()) {
throw new PrepareFailedException("Cannot extract method because the selected code fragment defines local classes used outside of the fragment", remainingReferences.get(0));
}
if (classExtracted) {
for (PsiVariable variable : myControlFlowWrapper.getUsedVariables()) {
if (isDeclaredInside(variable) && !variable.equals(myOutputVariable) && PsiUtil.resolveClassInType(variable.getType()) == localClass) {
throw new PrepareFailedException("Cannot extract method because the selected code fragment defines variable of local class type used outside of the fragment", variable);
}
}
}
}
}
private boolean isExtractedElement(final PsiElement element) {
boolean isExtracted = false;
for(PsiElement psiElement: myElements) {
if (PsiTreeUtil.isAncestor(psiElement, element, false)) {
isExtracted = true;
break;
}
}
return isExtracted;
}
private boolean shouldBeStatic() {
for(PsiElement element: myElements) {
final PsiExpressionStatement statement = PsiTreeUtil.getParentOfType(element, PsiExpressionStatement.class);
if (statement != null && JavaHighlightUtil.isSuperOrThisCall(statement, true, true)) {
return true;
}
}
PsiElement codeFragmentMember = myCodeFragmentMember;
while (codeFragmentMember != null && PsiTreeUtil.isAncestor(myTargetClass, codeFragmentMember, true)) {
if (codeFragmentMember instanceof PsiModifierListOwner && ((PsiModifierListOwner)codeFragmentMember).hasModifierProperty(PsiModifier.STATIC)) {
return true;
}
codeFragmentMember = PsiTreeUtil.getParentOfType(codeFragmentMember, PsiModifierListOwner.class, true);
}
return false;
}
public boolean showDialog(final boolean direct) {
AbstractExtractDialog dialog = createExtractMethodDialog(direct);
dialog.show();
if (!dialog.isOK()) return false;
apply(dialog);
return true;
}
protected void apply(final AbstractExtractDialog dialog) {
myMethodName = dialog.getChosenMethodName();
myVariableDatum = dialog.getChosenParameters();
myStatic = isStatic() | dialog.isMakeStatic();
myIsChainedConstructor = dialog.isChainedConstructor();
myMethodVisibility = dialog.getVisibility();
final PsiType returnType = dialog.getReturnType();
if (returnType != null) {
myReturnType = returnType;
}
}
protected AbstractExtractDialog createExtractMethodDialog(final boolean direct) {
setDataFromInputVariables();
myNullness = initNullness();
myArtificialOutputVariable = PsiType.VOID.equals(myReturnType) ? getArtificialOutputVariable() : null;
final PsiType returnType = myArtificialOutputVariable != null ? myArtificialOutputVariable.getType() : myReturnType;
return new ExtractMethodDialog(myProject, myTargetClass, myInputVariables, returnType, getTypeParameterList(),
getThrownExceptions(), isStatic(), isCanBeStatic(), myCanBeChainedConstructor,
myRefactoringName, myHelpId, myNullness, myElements) {
protected boolean areTypesDirected() {
return direct;
}
@Override
protected String[] suggestMethodNames() {
return suggestInitialMethodName();
}
@Override
protected PsiExpression[] findOccurrences() {
return ExtractMethodProcessor.this.findOccurrences();
}
@Override
protected boolean isOutputVariable(PsiVariable var) {
return ExtractMethodProcessor.this.isOutputVariable(var);
}
protected boolean isVoidReturn() {
return myArtificialOutputVariable != null && !(myArtificialOutputVariable instanceof PsiField);
}
@Override
protected void checkMethodConflicts(MultiMap<PsiElement, String> conflicts) {
super.checkMethodConflicts(conflicts);
final VariableData[] parameters = getChosenParameters();
final Map<String, PsiLocalVariable> vars = new HashMap<>();
for (PsiElement element : myElements) {
element.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitLocalVariable(PsiLocalVariable variable) {
super.visitLocalVariable(variable);
vars.put(variable.getName(), variable);
}
@Override
public void visitClass(PsiClass aClass) {}
});
}
for (VariableData parameter : parameters) {
final String paramName = parameter.name;
final PsiLocalVariable variable = vars.get(paramName);
if (variable != null) {
conflicts.putValue(variable, "Variable with name " + paramName + " is already defined in the selected scope");
}
}
}
};
}
public void setDataFromInputVariables() {
final List<VariableData> variables = myInputVariables.getInputVariables();
myVariableDatum = variables.toArray(new VariableData[variables.size()]);
}
public PsiExpression[] findOccurrences() {
if (myExpression != null) {
return new PsiExpression[] {myExpression};
}
if (myOutputVariable != null) {
final PsiElement scope = myOutputVariable instanceof PsiLocalVariable
? RefactoringUtil.getVariableScope((PsiLocalVariable)myOutputVariable)
: PsiTreeUtil.findCommonParent(myElements);
return CodeInsightUtil.findReferenceExpressions(scope, myOutputVariable);
}
final List<PsiStatement> filter = ContainerUtil.filter(myExitStatements, statement -> statement instanceof PsiReturnStatement && ((PsiReturnStatement)statement).getReturnValue() != null);
final List<PsiExpression> map = ContainerUtil.map(filter, statement -> ((PsiReturnStatement)statement).getReturnValue());
return map.toArray(new PsiExpression[map.size()]);
}
private Nullness initNullness() {
if (!PsiUtil.isLanguageLevel5OrHigher(myElements[0]) || PsiUtil.resolveClassInType(myReturnType) == null) return null;
final NullableNotNullManager manager = NullableNotNullManager.getInstance(myProject);
final PsiClass nullableAnnotationClass = JavaPsiFacade.getInstance(myProject)
.findClass(manager.getDefaultNullable(), myElements[0].getResolveScope());
if (nullableAnnotationClass != null) {
final PsiElement elementInCopy = myTargetClass.getContainingFile().copy().findElementAt(myTargetClass.getTextOffset());
final PsiClass classCopy = PsiTreeUtil.getParentOfType(elementInCopy, PsiClass.class);
if (classCopy == null) {
return null;
}
final PsiMethod emptyMethod = (PsiMethod)classCopy.addAfter(generateEmptyMethod("name", null), classCopy.getLBrace());
prepareMethodBody(emptyMethod, false);
if (myNotNullConditionalCheck || myNullConditionalCheck) {
return Nullness.NULLABLE;
}
return DfaUtil.inferMethodNullity(emptyMethod);
}
return null;
}
protected String[] suggestInitialMethodName() {
if (StringUtil.isEmpty(myInitialMethodName)) {
final Set<String> initialMethodNames = new LinkedHashSet<>();
final JavaCodeStyleManagerImpl codeStyleManager = (JavaCodeStyleManagerImpl)JavaCodeStyleManager.getInstance(myProject);
if (myExpression != null || !(myReturnType instanceof PsiPrimitiveType)) {
final String[] names = codeStyleManager.suggestVariableName(VariableKind.FIELD, null, myExpression, myReturnType).names;
for (String name : names) {
initialMethodNames.add(codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD));
}
}
if (myOutputVariable != null) {
final VariableKind outKind = codeStyleManager.getVariableKind(myOutputVariable);
final SuggestedNameInfo nameInfo = codeStyleManager
.suggestVariableName(VariableKind.FIELD, codeStyleManager.variableNameToPropertyName(myOutputVariable.getName(), outKind), null, myOutputVariable.getType());
for (String name : nameInfo.names) {
initialMethodNames.add(codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD));
}
}
final String nameByComment = getNameByComment();
final PsiField field = JavaPsiFacade.getElementFactory(myProject).createField("fieldNameToReplace", myReturnType instanceof PsiEllipsisType ? ((PsiEllipsisType)myReturnType).toArrayType() : myReturnType);
final List<String> getters = new ArrayList<>(ContainerUtil.map(initialMethodNames, propertyName -> {
if (!PsiNameHelper.getInstance(myProject).isIdentifier(propertyName)) {
LOG.info(propertyName + "; " + myExpression);
return null;
}
field.setName(propertyName);
return GenerateMembersUtil.suggestGetterName(field);
}));
ContainerUtil.addIfNotNull(getters, nameByComment);
return ArrayUtil.toStringArray(getters);
}
return new String[] {myInitialMethodName};
}
private String getNameByComment() {
PsiElement prevSibling = PsiTreeUtil.skipWhitespacesBackward(myElements[0]);
if (prevSibling instanceof PsiComment && ((PsiComment)prevSibling).getTokenType() == JavaTokenType.END_OF_LINE_COMMENT) {
final String text = StringUtil.decapitalize(StringUtil.capitalizeWords(prevSibling.getText().trim().substring(2), true)).replaceAll(" ", "");
if (PsiNameHelper.getInstance(myProject).isIdentifier(text) && text.length() < 20) {
return text;
}
}
return null;
}
public boolean isOutputVariable(PsiVariable var) {
return ArrayUtil.find(myOutputVariables, var) != -1;
}
public boolean showDialog() {
return showDialog(true);
}
@TestOnly
public void testRun() throws IncorrectOperationException {
testPrepare();
testNullness();
ExtractMethodHandler.extractMethod(myProject, this);
}
@TestOnly
public void testNullness() {
myNullness = initNullness();
}
@TestOnly
public void testPrepare() {
myInputVariables.setFoldingAvailable(myInputVariables.isFoldingSelectedByDefault());
myMethodName = myInitialMethodName;
myVariableDatum = new VariableData[myInputVariables.getInputVariables().size()];
for (int i = 0; i < myInputVariables.getInputVariables().size(); i++) {
myVariableDatum[i] = myInputVariables.getInputVariables().get(i);
}
}
@TestOnly
public void testTargetClass(PsiClass targetClass) {
if (targetClass != null) {
myTargetClass = targetClass;
myNeedChangeContext = true;
}
}
@TestOnly
public void testPrepare(PsiType returnType, boolean makeStatic) throws PrepareFailedException{
if (makeStatic) {
if (!isCanBeStatic()) {
throw new PrepareFailedException("Failed to make static", myElements[0]);
}
myInputVariables.setPassFields(true);
myStatic = true;
}
if (PsiType.VOID.equals(myReturnType)) {
myArtificialOutputVariable = getArtificialOutputVariable();
}
testPrepare();
if (returnType != null) {
myReturnType = returnType;
}
}
@TestOnly
public void doNotPassParameter(int i) {
myVariableDatum[i].passAsParameter = false;
}
@TestOnly
public void changeParamName(int i, String param) {
myVariableDatum[i].name = param;
}
/**
* Invoked in command and in atomic action
*/
public void doRefactoring() throws IncorrectOperationException {
initDuplicates();
chooseAnchor();
LogicalPosition pos1;
if (myEditor != null) {
int col = myEditor.getCaretModel().getLogicalPosition().column;
int line = myEditor.getCaretModel().getLogicalPosition().line;
pos1 = new LogicalPosition(line, col);
LogicalPosition pos = new LogicalPosition(0, 0);
myEditor.getCaretModel().moveToLogicalPosition(pos);
} else {
pos1 = null;
}
final SearchScope processConflictsScope = myMethodVisibility.equals(PsiModifier.PRIVATE) ?
new LocalSearchScope(myTargetClass) :
GlobalSearchScope.projectScope(myProject);
final Map<PsiMethodCallExpression, PsiMethod> overloadsResolveMap = new HashMap<>();
final Runnable collectOverloads = () -> ApplicationManager.getApplication().runReadAction(() -> {
Map<PsiMethodCallExpression, PsiMethod> overloads =
ExtractMethodUtil.encodeOverloadTargets(myTargetClass, processConflictsScope, myMethodName, myCodeFragmentMember);
overloadsResolveMap.putAll(overloads);
});
final Runnable extract = () -> {
doExtract();
ExtractMethodUtil.decodeOverloadTargets(overloadsResolveMap, myExtractedMethod, myCodeFragmentMember);
};
if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
collectOverloads.run();
extract.run();
} else {
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(collectOverloads, "Collect overloads...", true, myProject)) return;
ApplicationManager.getApplication().runWriteAction(extract);
}
if (myEditor != null) {
myEditor.getCaretModel().moveToLogicalPosition(pos1);
int offset = myMethodCall.getMethodExpression().getTextRange().getStartOffset();
myEditor.getCaretModel().moveToOffset(offset);
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
myEditor.getSelectionModel().removeSelection();
}
}
@Nullable
private DuplicatesFinder initDuplicates() {
List<PsiElement> elements = new ArrayList<>();
for (PsiElement element : myElements) {
if (!(element instanceof PsiWhiteSpace || element instanceof PsiComment)) {
elements.add(element);
}
}
if (myExpression != null) {
DuplicatesFinder finder = new DuplicatesFinder(PsiUtilCore.toPsiElementArray(elements), myInputVariables.copy(),
new ArrayList<>());
myDuplicates = finder.findDuplicates(myTargetClass);
return finder;
}
else if (elements.size() > 0){
DuplicatesFinder myDuplicatesFinder = new DuplicatesFinder(PsiUtilCore.toPsiElementArray(elements), myInputVariables.copy(),
myOutputVariable != null ? new VariableReturnValue(myOutputVariable) : null,
Arrays.asList(myOutputVariables));
myDuplicates = myDuplicatesFinder.findDuplicates(myTargetClass);
return myDuplicatesFinder;
} else {
myDuplicates = new ArrayList<>();
}
return null;
}
public void doExtract() throws IncorrectOperationException {
PsiMethod newMethod = generateEmptyMethod();
myExpression = myInputVariables.replaceWrappedReferences(myElements, myExpression);
renameInputVariables();
LOG.assertTrue(myElements[0].isValid());
PsiCodeBlock body = newMethod.getBody();
myMethodCall = generateMethodCall(null, true);
LOG.assertTrue(myElements[0].isValid());
final PsiStatement exitStatementCopy = prepareMethodBody(newMethod, true);
if (myExpression == null) {
if (myNeedChangeContext && isNeedToChangeCallContext()) {
for (PsiElement element : myElements) {
ChangeContextUtil.encodeContextInfo(element, false);
}
}
if (myNullConditionalCheck) {
final String varName = myOutputVariable.getName();
if (isDeclaredInside(myOutputVariable)) {
declareVariableAtMethodCallLocation(varName);
}
else {
PsiExpressionStatement assignmentExpression =
(PsiExpressionStatement)myElementFactory.createStatementFromText(varName + "=x;", null);
assignmentExpression = (PsiExpressionStatement)addToMethodCallLocation(assignmentExpression);
myMethodCall =
(PsiMethodCallExpression)((PsiAssignmentExpression)assignmentExpression.getExpression()).getRExpression().replace(myMethodCall);
}
declareNecessaryVariablesAfterCall(myOutputVariable);
PsiIfStatement ifStatement;
if (myHasReturnStatementOutput) {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) return null;", null);
}
else if (myGenerateConditionalExit) {
if (myFirstExitStatementCopy instanceof PsiReturnStatement && ((PsiReturnStatement)myFirstExitStatementCopy).getReturnValue() != null) {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) return null;", null);
}
else {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) " + myFirstExitStatementCopy.getText(), null);
}
}
else {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) return;", null);
}
ifStatement = (PsiIfStatement)addToMethodCallLocation(ifStatement);
CodeStyleManager.getInstance(myProject).reformat(ifStatement);
}
else if (myNotNullConditionalCheck) {
String varName = myOutputVariable != null ? myOutputVariable.getName() : "x";
varName = declareVariableAtMethodCallLocation(varName, myReturnType instanceof PsiPrimitiveType ? ((PsiPrimitiveType)myReturnType).getBoxedType(myCodeFragmentMember) : myReturnType);
addToMethodCallLocation(myElementFactory.createStatementFromText("if (" + varName + " != null) return " + varName + ";", null));
declareVariableReusedAfterCall(myOutputVariable);
}
else if (myGenerateConditionalExit) {
PsiIfStatement ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (a) b;", null);
ifStatement = (PsiIfStatement)addToMethodCallLocation(ifStatement);
myMethodCall = (PsiMethodCallExpression)ifStatement.getCondition().replace(myMethodCall);
myFirstExitStatementCopy = (PsiStatement)ifStatement.getThenBranch().replace(myFirstExitStatementCopy);
CodeStyleManager.getInstance(myProject).reformat(ifStatement);
}
else if (myOutputVariable != null || isArtificialOutputUsed()) {
boolean toDeclare = isArtificialOutputUsed() ? !(myArtificialOutputVariable instanceof PsiField) : isDeclaredInside(myOutputVariable);
String name = isArtificialOutputUsed() ? myArtificialOutputVariable.getName() : myOutputVariable.getName();
if (!toDeclare) {
PsiExpressionStatement statement = (PsiExpressionStatement)myElementFactory.createStatementFromText(name + "=x;", null);
statement = (PsiExpressionStatement)myStyleManager.reformat(statement);
statement = (PsiExpressionStatement)addToMethodCallLocation(statement);
PsiAssignmentExpression assignment = (PsiAssignmentExpression)statement.getExpression();
myMethodCall = (PsiMethodCallExpression)assignment.getRExpression().replace(myMethodCall);
}
else {
declareVariableAtMethodCallLocation(name);
}
}
else if (myHasReturnStatementOutput) {
PsiStatement statement = myElementFactory.createStatementFromText("return x;", null);
statement = (PsiStatement)addToMethodCallLocation(statement);
myMethodCall = (PsiMethodCallExpression)((PsiReturnStatement)statement).getReturnValue().replace(myMethodCall);
}
else {
PsiStatement statement = myElementFactory.createStatementFromText("x();", null);
statement = (PsiStatement)addToMethodCallLocation(statement);
myMethodCall = (PsiMethodCallExpression)((PsiExpressionStatement)statement).getExpression().replace(myMethodCall);
}
if (myHasReturnStatement && !myHasReturnStatementOutput && !hasNormalExit()) {
PsiStatement statement = myElementFactory.createStatementFromText("return;", null);
addToMethodCallLocation(statement);
}
else if (!myGenerateConditionalExit && exitStatementCopy != null) {
addToMethodCallLocation(exitStatementCopy);
}
if (!myNullConditionalCheck && !myNotNullConditionalCheck) {
declareNecessaryVariablesAfterCall(myOutputVariable);
}
deleteExtracted();
}
else {
PsiExpression expression2Replace = expressionToReplace(myExpression);
myExpression = (PsiExpression)IntroduceVariableBase.replace(expression2Replace, myMethodCall, myProject);
myMethodCall = PsiTreeUtil.getParentOfType(myExpression.findElementAt(myExpression.getText().indexOf(myMethodCall.getText())), PsiMethodCallExpression.class);
declareNecessaryVariablesAfterCall(myOutputVariable);
}
if (myAnchor instanceof PsiField) {
((PsiField)myAnchor).normalizeDeclaration();
}
adjustFinalParameters(newMethod);
int i = 0;
for (VariableData data : myVariableDatum) {
if (!data.passAsParameter) continue;
final PsiParameter psiParameter = newMethod.getParameterList().getParameters()[i++];
final PsiType paramType = psiParameter.getType();
for (PsiReference reference : ReferencesSearch.search(psiParameter, new LocalSearchScope(body))){
final PsiElement element = reference.getElement();
if (element != null) {
final PsiElement parent = element.getParent();
if (parent instanceof PsiTypeCastExpression) {
final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression)parent;
final PsiTypeElement castType = typeCastExpression.getCastType();
if (castType != null && Comparing.equal(castType.getType(), paramType)) {
RedundantCastUtil.removeCast(typeCastExpression);
}
}
}
}
}
if (myNullness != null &&
PsiUtil.resolveClassInType(newMethod.getReturnType()) != null &&
PropertiesComponent.getInstance(myProject).getBoolean(ExtractMethodDialog.EXTRACT_METHOD_GENERATE_ANNOTATIONS, true)) {
final NullableNotNullManager notNullManager = NullableNotNullManager.getInstance(myProject);
AddNullableNotNullAnnotationFix annotationFix;
switch (myNullness) {
case NOT_NULL:
annotationFix = new AddNullableNotNullAnnotationFix(notNullManager.getDefaultNotNull(), newMethod);
break;
case NULLABLE:
annotationFix = new AddNullableNotNullAnnotationFix(notNullManager.getDefaultNullable(), newMethod);
break;
default:
annotationFix = null;
}
if (annotationFix != null) {
annotationFix.invoke(myProject, myTargetClass.getContainingFile(), newMethod, newMethod);
}
}
myExtractedMethod = addExtractedMethod(newMethod);
if (isNeedToChangeCallContext() && myNeedChangeContext) {
ChangeContextUtil.decodeContextInfo(myExtractedMethod, myTargetClass, RefactoringChangeUtil.createThisExpression(myManager, null));
if (myMethodCall.resolveMethod() != myExtractedMethod) {
final PsiReferenceExpression methodExpression = myMethodCall.getMethodExpression();
RefactoringChangeUtil.qualifyReference(methodExpression, myExtractedMethod, PsiUtil.getEnclosingStaticElement(methodExpression, myTargetClass) != null ? myTargetClass : null);
}
}
}
protected PsiExpression expressionToReplace(PsiExpression expression) {
if (expression instanceof PsiAssignmentExpression) {
return ((PsiAssignmentExpression)expression).getRExpression();
}
return expression;
}
protected PsiMethod addExtractedMethod(PsiMethod newMethod) {
return (PsiMethod)myTargetClass.addAfter(newMethod, myAnchor);
}
@Nullable
private PsiStatement prepareMethodBody(PsiMethod newMethod, boolean doExtract) {
PsiCodeBlock body = newMethod.getBody();
if (myExpression != null) {
declareNecessaryVariablesInsideBody(body);
if (myHasExpressionOutput) {
PsiReturnStatement returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return x;", null);
final PsiExpression returnValue = RefactoringUtil.convertInitializerToNormalExpression(myExpression, myForcedReturnType);
returnStatement.getReturnValue().replace(returnValue);
body.add(returnStatement);
}
else {
PsiExpressionStatement statement = (PsiExpressionStatement)myElementFactory.createStatementFromText("x;", null);
statement.getExpression().replace(myExpression);
body.add(statement);
}
return null;
}
final boolean hasNormalExit = hasNormalExit();
String outVariableName = myOutputVariable != null ? getNewVariableName(myOutputVariable) : null;
PsiReturnStatement returnStatement;
if (myNullConditionalCheck) {
returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return null;", null);
} else if (myOutputVariable != null) {
returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return " + outVariableName + ";", null);
}
else if (myGenerateConditionalExit) {
returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return true;", null);
}
else {
returnStatement = (PsiReturnStatement)myElementFactory.createStatementFromText("return;", null);
}
PsiStatement exitStatementCopy = !doExtract || myNotNullConditionalCheck ? null : myControlFlowWrapper.getExitStatementCopy(returnStatement, myElements);
declareNecessaryVariablesInsideBody(body);
body.addRange(myElements[0], myElements[myElements.length - 1]);
if (myNullConditionalCheck) {
body.add(myElementFactory.createStatementFromText("return " + myOutputVariable.getName() + ";", null));
}
else if (myNotNullConditionalCheck) {
body.add(myElementFactory.createStatementFromText("return null;", null));
}
else if (myGenerateConditionalExit) {
body.add(myElementFactory.createStatementFromText("return false;", null));
}
else if (!myHasReturnStatement && hasNormalExit && myOutputVariable != null) {
final PsiReturnStatement insertedReturnStatement = (PsiReturnStatement)body.add(returnStatement);
if (myOutputVariables.length == 1) {
final PsiExpression returnValue = insertedReturnStatement.getReturnValue();
if (returnValue instanceof PsiReferenceExpression) {
final PsiElement resolved = ((PsiReferenceExpression)returnValue).resolve();
if (resolved instanceof PsiLocalVariable && Comparing.strEqual(((PsiVariable)resolved).getName(), outVariableName)) {
final PsiStatement statement = PsiTreeUtil.getPrevSiblingOfType(insertedReturnStatement, PsiStatement.class);
if (statement instanceof PsiDeclarationStatement) {
final PsiElement[] declaredElements = ((PsiDeclarationStatement)statement).getDeclaredElements();
if (ArrayUtil.find(declaredElements, resolved) != -1) {
InlineUtil.inlineVariable((PsiVariable)resolved, ((PsiVariable)resolved).getInitializer(),
(PsiReferenceExpression)returnValue);
resolved.delete();
}
}
}
}
}
}
else if (isArtificialOutputUsed()) {
body.add(myElementFactory.createStatementFromText("return " + myArtificialOutputVariable.getName() + ";", null));
}
return exitStatementCopy;
}
private boolean isArtificialOutputUsed() {
return myArtificialOutputVariable != null && !PsiType.VOID.equals(myReturnType) && !myIsChainedConstructor;
}
private boolean hasNormalExit() {
try {
PsiCodeBlock block = JavaPsiFacade.getElementFactory(myProject).createCodeBlock();
block.addRange(myElements[0], myElements[myElements.length - 1]);
ControlFlow flow = ControlFlowFactory.getInstance(myProject).getControlFlow(block, new LocalsControlFlowPolicy(block), false, false);
return ControlFlowUtil.canCompleteNormally(flow, 0, flow.getSize());
}
catch (AnalysisCanceledException e) {
//check incomplete code as simple as possible
PsiElement lastElement = myElements[myElements.length - 1];
if (!(lastElement instanceof PsiReturnStatement || lastElement instanceof PsiBreakStatement ||
lastElement instanceof PsiContinueStatement)) {
return true;
}
return false;
}
}
protected boolean isNeedToChangeCallContext() {
return true;
}
private void declareVariableAtMethodCallLocation(String name) {
declareVariableAtMethodCallLocation(name, myReturnType);
}
private String declareVariableAtMethodCallLocation(String name, PsiType type) {
if (myControlFlowWrapper.getOutputVariables(false).length == 0) {
PsiElement lastStatement = PsiTreeUtil.getNextSiblingOfType(myEnclosingBlockStatement != null ? myEnclosingBlockStatement : myElements[myElements.length - 1], PsiStatement.class);
if (lastStatement != null) {
name = JavaCodeStyleManager.getInstance(myProject).suggestUniqueVariableName(name, lastStatement, true);
}
}
PsiDeclarationStatement statement = myElementFactory.createVariableDeclarationStatement(name, type, myMethodCall);
statement =
(PsiDeclarationStatement)JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(addToMethodCallLocation(statement));
PsiVariable var = (PsiVariable)statement.getDeclaredElements()[0];
myMethodCall = (PsiMethodCallExpression)var.getInitializer();
if (myOutputVariable != null) {
var.getModifierList().replace(myOutputVariable.getModifierList());
}
return name;
}
private void adjustFinalParameters(final PsiMethod method) throws IncorrectOperationException {
final IncorrectOperationException[] exc = new IncorrectOperationException[1];
exc[0] = null;
final PsiParameter[] parameters = method.getParameterList().getParameters();
if (parameters.length > 0) {
if (CodeStyleSettingsManager.getSettings(myProject).getCustomSettings(JavaCodeStyleSettings.class).GENERATE_FINAL_PARAMETERS) {
method.accept(new JavaRecursiveElementVisitor() {
@Override public void visitReferenceExpression(PsiReferenceExpression expression) {
final PsiElement resolved = expression.resolve();
if (resolved != null) {
final int index = ArrayUtil.find(parameters, resolved);
if (index >= 0) {
final PsiParameter param = parameters[index];
if (param.hasModifierProperty(PsiModifier.FINAL) && PsiUtil.isAccessedForWriting(expression)) {
try {
PsiUtil.setModifierProperty(param, PsiModifier.FINAL, false);
}
catch (IncorrectOperationException e) {
exc[0] = e;
}
}
}
}
super.visitReferenceExpression(expression);
}
});
}
else if (!PsiUtil.isLanguageLevel8OrHigher(myTargetClass)){
method.accept(new JavaRecursiveElementVisitor() {
@Override public void visitReferenceExpression(PsiReferenceExpression expression) {
final PsiElement resolved = expression.resolve();
final int index = ArrayUtil.find(parameters, resolved);
if (index >= 0) {
final PsiParameter param = parameters[index];
if (!param.hasModifierProperty(PsiModifier.FINAL) && RefactoringUtil.isInsideAnonymousOrLocal(expression, method)) {
try {
PsiUtil.setModifierProperty(param, PsiModifier.FINAL, true);
}
catch (IncorrectOperationException e) {
exc[0] = e;
}
}
}
super.visitReferenceExpression(expression);
}
});
}
if (exc[0] != null) {
throw exc[0];
}
}
}
public List<Match> getDuplicates() {
if (myIsChainedConstructor) {
return filterChainedConstructorDuplicates(myDuplicates);
}
return myDuplicates;
}
private static List<Match> filterChainedConstructorDuplicates(final List<Match> duplicates) {
List<Match> result = new ArrayList<>();
for(Match duplicate: duplicates) {
final PsiElement matchStart = duplicate.getMatchStart();
final PsiMethod method = PsiTreeUtil.getParentOfType(matchStart, PsiMethod.class);
if (method != null && method.isConstructor()) {
final PsiCodeBlock body = method.getBody();
if (body != null) {
final PsiStatement[] psiStatements = body.getStatements();
if (psiStatements.length > 0 && matchStart == psiStatements [0]) {
result.add(duplicate);
}
}
}
}
return result;
}
@Override
public void prepareSignature(Match match) {
MatchUtil.changeSignature(match, myExtractedMethod);
}
public PsiElement processMatch(Match match) throws IncorrectOperationException {
if (PsiTreeUtil.isContextAncestor(myExtractedMethod.getContainingClass(), match.getMatchStart(), false) &&
RefactoringUtil.isInStaticContext(match.getMatchStart(), myExtractedMethod.getContainingClass())) {
PsiUtil.setModifierProperty(myExtractedMethod, PsiModifier.STATIC, true);
}
final PsiMethodCallExpression methodCallExpression = generateMethodCall(match.getInstanceExpression(), false);
ArrayList<VariableData> datas = new ArrayList<>();
for (final VariableData variableData : myVariableDatum) {
if (variableData.passAsParameter) {
datas.add(variableData);
}
}
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);
for (VariableData data : datas) {
final List<PsiElement> parameterValue = match.getParameterValues(data.variable);
if (parameterValue != null) {
for (PsiElement val : parameterValue) {
if (val instanceof PsiExpression) {
final PsiType exprType = ((PsiExpression)val).getType();
if (exprType != null && !TypeConversionUtil.isAssignable(data.type, exprType)) {
final PsiTypeCastExpression cast = (PsiTypeCastExpression)elementFactory.createExpressionFromText("(A)a", val);
cast.getCastType().replace(elementFactory.createTypeElement(data.type));
cast.getOperand().replace(val.copy());
val = cast;
}
}
methodCallExpression.getArgumentList().add(val);
}
} else {
methodCallExpression.getArgumentList().add(myElementFactory.createExpressionFromText(data.variable.getName(), methodCallExpression));
}
}
return match.replace(myExtractedMethod, methodCallExpression, myOutputVariable);
}
@Nullable
protected PsiMethodCallExpression getMatchMethodCallExpression(PsiElement element) {
PsiMethodCallExpression methodCallExpression = null;
if (element instanceof PsiMethodCallExpression) {
methodCallExpression = (PsiMethodCallExpression)element;
}
else if (element instanceof PsiExpressionStatement) {
final PsiExpression expression = ((PsiExpressionStatement)element).getExpression();
if (expression instanceof PsiMethodCallExpression) {
methodCallExpression = (PsiMethodCallExpression)expression;
}
else if (expression instanceof PsiAssignmentExpression) {
final PsiExpression psiExpression = ((PsiAssignmentExpression)expression).getRExpression();
if (psiExpression instanceof PsiMethodCallExpression) {
methodCallExpression = (PsiMethodCallExpression)psiExpression;
}
}
}
else if (element instanceof PsiDeclarationStatement) {
final PsiElement[] declaredElements = ((PsiDeclarationStatement)element).getDeclaredElements();
for (PsiElement declaredElement : declaredElements) {
if (declaredElement instanceof PsiLocalVariable) {
final PsiExpression initializer = ((PsiLocalVariable)declaredElement).getInitializer();
if (initializer instanceof PsiMethodCallExpression) {
methodCallExpression = (PsiMethodCallExpression)initializer;
break;
}
}
}
}
else if (element instanceof PsiIfStatement) {
PsiExpression condition = ((PsiIfStatement)element).getCondition();
if (condition instanceof PsiMethodCallExpression) {
methodCallExpression = (PsiMethodCallExpression)condition;
}
}
return methodCallExpression;
}
protected void deleteExtracted() throws IncorrectOperationException {
if (myEnclosingBlockStatement == null) {
myElements[0].getParent().deleteChildRange(myElements[0], myElements[myElements.length - 1]);
}
else {
myEnclosingBlockStatement.delete();
}
}
protected PsiElement addToMethodCallLocation(PsiStatement statement) throws IncorrectOperationException {
if (myEnclosingBlockStatement == null) {
PsiElement containingStatement = myElements[0] instanceof PsiComment ? myElements[0] : PsiTreeUtil.getParentOfType(myExpression != null ? myExpression : myElements[0], PsiStatement.class, false);
if (containingStatement == null) {
containingStatement = PsiTreeUtil.getParentOfType(myExpression != null ? myExpression : myElements[0], PsiComment.class, false);
}
return containingStatement.getParent().addBefore(statement, containingStatement);
}
else {
return myEnclosingBlockStatement.getParent().addBefore(statement, myEnclosingBlockStatement);
}
}
private void renameInputVariables() throws IncorrectOperationException {
//when multiple input variables should have the same name, unique names are generated
//without reverse, the second rename would rename variable without a prefix into second one though it was already renamed
LocalSearchScope localSearchScope = null;
for (int i = myVariableDatum.length - 1; i >= 0; i--) {
VariableData data = myVariableDatum[i];
PsiVariable variable = data.variable;
if (!data.name.equals(variable.getName()) || variable instanceof PsiField) {
if (localSearchScope == null) {
localSearchScope = new LocalSearchScope(myElements);
}
for (PsiReference reference : ReferencesSearch.search(variable, localSearchScope)) {
reference.handleElementRename(data.name);
final PsiElement element = reference.getElement();
if (element instanceof PsiReferenceExpression) {
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)element;
final PsiExpression qualifierExpression = referenceExpression.getQualifierExpression();
if (qualifierExpression instanceof PsiThisExpression || qualifierExpression instanceof PsiSuperExpression) {
referenceExpression.setQualifierExpression(null);
}
}
}
}
}
}
public PsiClass getTargetClass() {
return myTargetClass;
}
public PsiType getReturnType() {
return myReturnType;
}
private PsiMethod generateEmptyMethod() throws IncorrectOperationException {
return generateEmptyMethod(myMethodName, null);
}
public PsiMethod generateEmptyMethod(String methodName, PsiElement context) throws IncorrectOperationException {
PsiMethod newMethod;
if (myIsChainedConstructor) {
newMethod = myElementFactory.createConstructor();
}
else {
newMethod = context != null ? myElementFactory.createMethod(methodName, myReturnType, context)
: myElementFactory.createMethod(methodName, myReturnType);
PsiUtil.setModifierProperty(newMethod, PsiModifier.STATIC, isStatic());
}
PsiUtil.setModifierProperty(newMethod, myMethodVisibility, true);
if (getTypeParameterList() != null) {
newMethod.getTypeParameterList().replace(getTypeParameterList());
}
PsiCodeBlock body = newMethod.getBody();
LOG.assertTrue(body != null);
boolean isFinal = CodeStyleSettingsManager.getSettings(myProject).getCustomSettings(JavaCodeStyleSettings.class).GENERATE_FINAL_PARAMETERS;
PsiParameterList list = newMethod.getParameterList();
for (VariableData data : myVariableDatum) {
if (data.passAsParameter) {
PsiParameter parm = myElementFactory.createParameter(data.name, data.type);
copyParamAnnotations(parm);
if (isFinal) {
PsiUtil.setModifierProperty(parm, PsiModifier.FINAL, true);
}
list.add(parm);
}
else if (defineVariablesForUnselectedParameters()){
@NonNls StringBuilder buffer = new StringBuilder();
if (isFinal) {
buffer.append("final ");
}
buffer.append("int ");
buffer.append(data.name);
buffer.append("=;");
String text = buffer.toString();
PsiDeclarationStatement declaration = (PsiDeclarationStatement)myElementFactory.createStatementFromText(text, null);
declaration = (PsiDeclarationStatement)myStyleManager.reformat(declaration);
final PsiTypeElement typeElement = myElementFactory.createTypeElement(data.type);
((PsiVariable)declaration.getDeclaredElements()[0]).getTypeElement().replace(typeElement);
body.add(declaration);
}
}
PsiReferenceList throwsList = newMethod.getThrowsList();
for (PsiClassType exception : getThrownExceptions()) {
throwsList.add(JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory().createReferenceElementByType(exception));
}
if (myTargetClass.isInterface() && PsiUtil.isLanguageLevel8OrHigher(myTargetClass)) {
final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(myCodeFragmentMember, PsiMethod.class, false);
if (containingMethod != null && containingMethod.hasModifierProperty(PsiModifier.DEFAULT)) {
PsiUtil.setModifierProperty(newMethod, PsiModifier.DEFAULT, true);
}
}
return (PsiMethod)myStyleManager.reformat(newMethod);
}
protected boolean defineVariablesForUnselectedParameters() {
return true;
}
private void copyParamAnnotations(PsiParameter parm) {
final PsiVariable variable = PsiResolveHelper.SERVICE.getInstance(myProject).resolveReferencedVariable(parm.getName(), myElements[0]);
if (variable instanceof PsiParameter) {
final PsiModifierList modifierList = variable.getModifierList();
if (modifierList != null) {
PsiModifierList parmModifierList = parm.getModifierList();
LOG.assertTrue(parmModifierList != null);
GenerateMembersUtil.copyAnnotations(modifierList, parmModifierList, SuppressWarnings.class.getName());
updateNullabilityAnnotation(parm, variable);
}
}
}
private void updateNullabilityAnnotation(@NotNull PsiParameter parm, @NotNull PsiVariable variable) {
final NullableNotNullManager nullabilityManager = NullableNotNullManager.getInstance(myProject);
final List<String> notNullAnnotations = nullabilityManager.getNotNulls();
final List<String> nullableAnnotations = nullabilityManager.getNullables();
if (AnnotationUtil.isAnnotated(variable, nullableAnnotations) ||
AnnotationUtil.isAnnotated(variable, notNullAnnotations) ||
PropertiesComponent.getInstance(myProject).getBoolean(ExtractMethodDialog.EXTRACT_METHOD_GENERATE_ANNOTATIONS, false)) {
final Boolean isNotNull = isNotNullAt(variable, myElements[0]);
if (isNotNull != null) {
final List<String> toKeep = isNotNull ? notNullAnnotations : nullableAnnotations;
final String[] toRemove = (!isNotNull ? notNullAnnotations : nullableAnnotations).toArray(ArrayUtil.EMPTY_STRING_ARRAY);
AddAnnotationPsiFix.removePhysicalAnnotations(parm, toRemove);
if (!AnnotationUtil.isAnnotated(parm, toKeep)) {
final String toAdd = isNotNull ? nullabilityManager.getDefaultNotNull() : nullabilityManager.getDefaultNullable();
final PsiAnnotation added =
AddAnnotationPsiFix.addPhysicalAnnotation(toAdd, PsiNameValuePair.EMPTY_ARRAY, parm.getModifierList());
JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(added);
}
}
}
}
@Nullable
private static Boolean isNotNullAt(@NotNull PsiVariable variable, PsiElement startElement) {
String variableName = variable.getName();
if (variableName == null) return null;
PsiElement methodOrLambdaBody = null;
if (variable instanceof PsiLocalVariable || variable instanceof PsiParameter) {
final PsiParameterListOwner methodOrLambda = PsiTreeUtil.getParentOfType(variable, PsiMethod.class, PsiLambdaExpression.class);
if (methodOrLambda != null) {
methodOrLambdaBody = methodOrLambda.getBody();
}
}
if (methodOrLambdaBody instanceof PsiCodeBlock) {
PsiElement topmostLambdaOrAnonymousClass = null;
for (PsiElement element = startElement; element != null && element != methodOrLambdaBody; element = element.getParent()) {
if (element instanceof PsiLambdaExpression || element instanceof PsiAnonymousClass) {
topmostLambdaOrAnonymousClass = element;
}
}
if (topmostLambdaOrAnonymousClass != null) {
startElement = topmostLambdaOrAnonymousClass;
}
Project project = methodOrLambdaBody.getProject();
PsiFile file = methodOrLambdaBody.getContainingFile();
final PsiFile copy = PsiFileFactory.getInstance(project)
.createFileFromText(file.getName(), file.getFileType(), file.getText(), file.getModificationStamp(), false);
PsiCodeBlock bodyCopy = findCopy(copy, methodOrLambdaBody, PsiCodeBlock.class);
PsiVariable variableCopy = findCopy(copy, variable, PsiVariable.class);
if (startElement instanceof PsiExpression) {
startElement = PsiTreeUtil.getParentOfType(startElement, PsiStatement.class);
}
if (startElement instanceof PsiStatement) {
PsiStatement startStatementCopy = findCopy(copy, startElement, PsiStatement.class);
try {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
startStatementCopy = wrapWithBlockStatementIfNeeded(startStatementCopy, factory);
String dummyName = JavaCodeStyleManager.getInstance(project).suggestUniqueVariableName("_Dummy_", startElement.getParent(), true);
PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)factory.createStatementFromText(
CommonClassNames.JAVA_LANG_OBJECT + " " + dummyName + " = " + variableName + ";", startStatementCopy);
PsiElement parent = startStatementCopy.getParent();
declarationStatement = (PsiDeclarationStatement)parent.addBefore(declarationStatement, startStatementCopy);
PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
PsiExpression initializer = ((PsiVariable)declaredElements[0]).getInitializer();
Nullness nullness = DfaUtil.checkNullness(variableCopy, initializer, bodyCopy);
return nullness == Nullness.NOT_NULL;
}
catch (IncorrectOperationException ignore) {
return null;
}
}
}
return null;
}
private static <T extends PsiElement> T findCopy(@NotNull PsiFile copy, @NotNull PsiElement element, @NotNull Class<T> clazz) {
TextRange range = element.getTextRange();
return CodeInsightUtil.findElementInRange(copy, range.getStartOffset(), range.getEndOffset(), clazz);
}
private static PsiStatement wrapWithBlockStatementIfNeeded(@NotNull PsiStatement statement, @NotNull PsiElementFactory factory) {
PsiElement parent = statement.getParent();
if (parent instanceof PsiLoopStatement && ((PsiLoopStatement)parent).getBody() == statement ||
parent instanceof PsiIfStatement &&
(((PsiIfStatement)parent).getThenBranch() == statement || ((PsiIfStatement)parent).getElseBranch() == statement)) {
PsiBlockStatement blockStatement = (PsiBlockStatement)factory.createStatementFromText("{}", statement);
blockStatement.getCodeBlock().add(statement);
blockStatement = (PsiBlockStatement)statement.replace(blockStatement);
return blockStatement.getCodeBlock().getStatements()[0];
}
if (parent instanceof PsiForStatement) {
if (((PsiForStatement)parent).getInitialization() == statement || ((PsiForStatement)parent).getUpdate() == statement) {
return wrapWithBlockStatementIfNeeded((PsiForStatement)parent, factory);
}
}
return statement;
}
@NotNull
protected PsiMethodCallExpression generateMethodCall(PsiExpression instanceQualifier, final boolean generateArgs) throws IncorrectOperationException {
@NonNls StringBuilder buffer = new StringBuilder();
final boolean skipInstanceQualifier;
if (myIsChainedConstructor) {
skipInstanceQualifier = true;
buffer.append(PsiKeyword.THIS);
}
else {
skipInstanceQualifier = instanceQualifier == null || instanceQualifier instanceof PsiThisExpression;
if (skipInstanceQualifier) {
if (isNeedToChangeCallContext() && myNeedChangeContext) {
boolean needsThisQualifier = false;
PsiElement parent = myCodeFragmentMember;
while (!myTargetClass.equals(parent)) {
if (parent instanceof PsiMethod) {
String methodName = ((PsiMethod)parent).getName();
if (methodName.equals(myMethodName)) {
needsThisQualifier = true;
break;
}
}
parent = parent.getParent();
}
if (needsThisQualifier) {
buffer.append(myTargetClass.getName());
buffer.append(".this.");
}
}
}
else {
buffer.append("qqq.");
}
buffer.append(myMethodName);
}
buffer.append("(");
if (generateArgs) {
int count = 0;
for (VariableData data : myVariableDatum) {
if (data.passAsParameter) {
if (count > 0) {
buffer.append(",");
}
myInputVariables.appendCallArguments(data, buffer);
count++;
}
}
}
buffer.append(")");
String text = buffer.toString();
PsiMethodCallExpression expr = (PsiMethodCallExpression)myElementFactory.createExpressionFromText(text, null);
expr = (PsiMethodCallExpression)myStyleManager.reformat(expr);
if (!skipInstanceQualifier) {
PsiExpression qualifierExpression = expr.getMethodExpression().getQualifierExpression();
LOG.assertTrue(qualifierExpression != null);
qualifierExpression.replace(instanceQualifier);
}
return (PsiMethodCallExpression)JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(expr);
}
private boolean chooseTargetClass(PsiElement codeFragment, final Pass<ExtractMethodProcessor> extractPass) throws PrepareFailedException {
final List<PsiVariable> inputVariables = myControlFlowWrapper.getInputVariables(codeFragment, myElements, myOutputVariables);
myNeedChangeContext = false;
myTargetClass = myCodeFragmentMember instanceof PsiMember
? ((PsiMember)myCodeFragmentMember).getContainingClass()
: PsiTreeUtil.getParentOfType(myCodeFragmentMember, PsiClass.class);
if (myTargetClass == null) {
LOG.error(myElements[0].getContainingFile());
}
if (!shouldAcceptCurrentTarget(extractPass, myTargetClass)) {
final LinkedHashMap<PsiClass, List<PsiVariable>> classes = new LinkedHashMap<>();
final PsiElementProcessor<PsiClass> processor = new PsiElementProcessor<PsiClass>() {
@Override
public boolean execute(@NotNull PsiClass selectedClass) {
AnonymousTargetClassPreselectionUtil.rememberSelection(selectedClass, myTargetClass);
final List<PsiVariable> array = classes.get(selectedClass);
myNeedChangeContext = myTargetClass != selectedClass;
myTargetClass = selectedClass;
if (array != null) {
for (PsiVariable variable : array) {
if (!inputVariables.contains(variable)) {
inputVariables.addAll(array);
}
}
}
try {
return applyChosenClassAndExtract(inputVariables, extractPass);
}
catch (PrepareFailedException e) {
if (myShowErrorDialogs) {
CommonRefactoringUtil
.showErrorHint(myProject, myEditor, e.getMessage(), ExtractMethodHandler.REFACTORING_NAME, HelpID.EXTRACT_METHOD);
ExtractMethodHandler.highlightPrepareError(e, e.getFile(), myEditor, myProject);
}
return false;
}
}
};
classes.put(myTargetClass, null);
PsiElement target = myTargetClass.getParent();
PsiElement targetMember = myTargetClass;
while (true) {
if (target instanceof PsiFile) break;
if (target instanceof PsiClass) {
boolean success = true;
final List<PsiVariable> array = new ArrayList<>();
for (PsiElement el : myElements) {
if (!ControlFlowUtil.collectOuterLocals(array, el, myCodeFragmentMember, targetMember)) {
success = false;
break;
}
}
if (success) {
classes.put((PsiClass)target, array);
if (shouldAcceptCurrentTarget(extractPass, target)) {
return processor.execute((PsiClass)target);
}
}
}
targetMember = target;
target = target.getParent();
}
if (classes.size() > 1) {
final PsiClass[] psiClasses = classes.keySet().toArray(new PsiClass[classes.size()]);
final PsiClass preselection = AnonymousTargetClassPreselectionUtil.getPreselection(classes.keySet(), psiClasses[0]);
NavigationUtil.getPsiElementPopup(psiClasses, new PsiClassListCellRenderer(), "Choose Destination Class", processor, preselection)
.showInBestPositionFor(myEditor);
return true;
}
}
return applyChosenClassAndExtract(inputVariables, extractPass);
}
private void declareNecessaryVariablesInsideBody(PsiCodeBlock body) throws IncorrectOperationException {
List<PsiVariable> usedVariables = myControlFlowWrapper.getUsedVariablesInBody(ControlFlowUtil.findCodeFragment(myElements[0]), myOutputVariables);
for (PsiVariable variable : usedVariables) {
boolean toDeclare = !isDeclaredInside(variable) && myInputVariables.toDeclareInsideBody(variable);
if (toDeclare) {
String name = variable.getName();
PsiDeclarationStatement statement = myElementFactory.createVariableDeclarationStatement(name, variable.getType(), null);
body.add(statement);
}
}
if (myArtificialOutputVariable instanceof PsiField && !myIsChainedConstructor) {
body.add(myElementFactory.createVariableDeclarationStatement(myArtificialOutputVariable.getName(), myArtificialOutputVariable.getType(), null));
}
}
protected void declareNecessaryVariablesAfterCall(PsiVariable outputVariable) throws IncorrectOperationException {
if (myHasExpressionOutput) return;
List<PsiVariable> usedVariables = myControlFlowWrapper.getUsedVariables();
Collection<ControlFlowUtil.VariableInfo> reassigned = myControlFlowWrapper.getInitializedTwice();
for (PsiVariable variable : usedVariables) {
boolean toDeclare = isDeclaredInside(variable) && !variable.equals(outputVariable);
if (toDeclare) {
String name = variable.getName();
PsiDeclarationStatement statement = myElementFactory.createVariableDeclarationStatement(name, variable.getType(), null);
if (reassigned.contains(new ControlFlowUtil.VariableInfo(variable, null))) {
final PsiElement[] psiElements = statement.getDeclaredElements();
assert psiElements.length > 0;
PsiVariable var = (PsiVariable) psiElements [0];
PsiUtil.setModifierProperty(var, PsiModifier.FINAL, false);
}
addToMethodCallLocation(statement);
}
}
}
public PsiMethodCallExpression getMethodCall() {
return myMethodCall;
}
public void setMethodCall(PsiMethodCallExpression methodCall) {
myMethodCall = methodCall;
}
public boolean isDeclaredInside(PsiVariable variable) {
if (variable instanceof ImplicitVariable) return false;
int startOffset;
int endOffset;
if (myExpression != null) {
final TextRange range = myExpression.getTextRange();
startOffset = range.getStartOffset();
endOffset = range.getEndOffset();
} else {
startOffset = myElements[0].getTextRange().getStartOffset();
endOffset = myElements[myElements.length - 1].getTextRange().getEndOffset();
}
PsiIdentifier nameIdentifier = variable.getNameIdentifier();
if (nameIdentifier == null) return false;
final TextRange range = nameIdentifier.getTextRange();
if (range == null) return false;
int offset = range.getStartOffset();
return startOffset <= offset && offset <= endOffset;
}
private String getNewVariableName(PsiVariable variable) {
for (VariableData data : myVariableDatum) {
if (data.variable.equals(variable)) {
return data.name;
}
}
return variable.getName();
}
private static boolean shouldAcceptCurrentTarget(Pass<ExtractMethodProcessor> extractPass, PsiElement target) {
return extractPass == null && !(target instanceof PsiAnonymousClass);
}
private boolean applyChosenClassAndExtract(List<PsiVariable> inputVariables, @Nullable Pass<ExtractMethodProcessor> extractPass)
throws PrepareFailedException {
myStatic = shouldBeStatic();
final Set<PsiField> fields = new LinkedHashSet<>();
myCanBeStatic = canBeStatic(myTargetClass, myCodeFragmentMember, myElements, fields);
myInputVariables = new InputVariables(inputVariables, myProject, new LocalSearchScope(myElements), isFoldingApplicable());
myInputVariables.setUsedInstanceFields(fields);
if (!checkExitPoints()){
return false;
}
checkCanBeChainedConstructor();
if (extractPass != null) {
extractPass.pass(this);
}
return true;
}
public static boolean canBeStatic(final PsiClass targetClass, final PsiElement place, final PsiElement[] elements, Set<PsiField> usedFields) {
if (!PsiUtil.isLocalOrAnonymousClass(targetClass) && (targetClass.getContainingClass() == null || targetClass.hasModifierProperty(PsiModifier.STATIC))) {
boolean canBeStatic = true;
if (targetClass.isInterface()) {
final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(place, PsiMethod.class, false);
canBeStatic = containingMethod == null || containingMethod.hasModifierProperty(PsiModifier.STATIC);
}
if (canBeStatic) {
ElementNeedsThis needsThis = new ElementNeedsThis(targetClass) {
@Override
protected void visitClassMemberReferenceElement(PsiMember classMember, PsiJavaCodeReferenceElement classMemberReference) {
if (classMember instanceof PsiField && !classMember.hasModifierProperty(PsiModifier.STATIC)) {
final PsiExpression expression = PsiTreeUtil.getParentOfType(classMemberReference, PsiExpression.class, false);
if (expression == null || !PsiUtil.isAccessedForWriting(expression)) {
usedFields.add((PsiField)classMember);
return;
}
}
super.visitClassMemberReferenceElement(classMember, classMemberReference);
}
};
for (int i = 0; i < elements.length && !needsThis.usesMembers(); i++) {
PsiElement element = elements[i];
element.accept(needsThis);
}
return !needsThis.usesMembers();
}
}
return false;
}
protected boolean isFoldingApplicable() {
return true;
}
protected void chooseAnchor() {
myAnchor = myCodeFragmentMember;
while (!myAnchor.getParent().equals(myTargetClass)) {
myAnchor = myAnchor.getParent();
}
}
private void declareVariableReusedAfterCall(PsiVariable variable) {
if (variable != null &&
variable.getName() != null &&
isDeclaredInside(variable) &&
myControlFlowWrapper.getUsedVariables().contains(variable) &&
!myControlFlowWrapper.needVariableValueAfterEnd(variable)) {
PsiDeclarationStatement declaration =
myElementFactory.createVariableDeclarationStatement(variable.getName(), variable.getType(), null);
addToMethodCallLocation(declaration);
}
}
private void showMultipleExitPointsMessage() {
if (myShowErrorDialogs) {
HighlightManager highlightManager = HighlightManager.getInstance(myProject);
PsiStatement[] exitStatementsArray = myExitStatements.toArray(new PsiStatement[myExitStatements.size()]);
EditorColorsManager manager = EditorColorsManager.getInstance();
TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
highlightManager.addOccurrenceHighlights(myEditor, exitStatementsArray, attributes, true, null);
String message = RefactoringBundle
.getCannotRefactorMessage(RefactoringBundle.message("there.are.multiple.exit.points.in.the.selected.code.fragment"));
CommonRefactoringUtil.showErrorHint(myProject, myEditor, message, myRefactoringName, myHelpId);
WindowManager.getInstance().getStatusBar(myProject).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
}
}
protected void showMultipleOutputMessage(PsiType expressionType) throws PrepareFailedException {
if (myShowErrorDialogs) {
String message = buildMultipleOutputMessageError(expressionType) + "\nWould you like to Extract Method Object?";
if (ApplicationManager.getApplication().isUnitTestMode()) throw new RuntimeException(message);
RefactoringMessageDialog dialog = new RefactoringMessageDialog(myRefactoringName, message, myHelpId, "OptionPane.errorIcon", true,
myProject);
if (dialog.showAndGet()) {
new ExtractMethodObjectHandler()
.invoke(myProject, myEditor, myTargetClass.getContainingFile(), DataManager.getInstance().getDataContext());
}
}
}
protected String buildMultipleOutputMessageError(PsiType expressionType) {
StringBuilder buffer = new StringBuilder();
buffer.append(RefactoringBundle.getCannotRefactorMessage(
RefactoringBundle.message("there.are.multiple.output.values.for.the.selected.code.fragment")));
buffer.append("\n");
if (myHasExpressionOutput) {
buffer.append(" ").append(RefactoringBundle.message("expression.result")).append(": ");
buffer.append(PsiFormatUtil.formatType(expressionType, 0, PsiSubstitutor.EMPTY));
buffer.append(",\n");
}
if (myGenerateConditionalExit) {
buffer.append(" ").append(RefactoringBundle.message("boolean.method.result"));
buffer.append(",\n");
}
for (int i = 0; i < myOutputVariables.length; i++) {
PsiVariable var = myOutputVariables[i];
buffer.append(" ");
buffer.append(var.getName());
buffer.append(" : ");
buffer.append(PsiFormatUtil.formatType(var.getType(), 0, PsiSubstitutor.EMPTY));
if (i < myOutputVariables.length - 1) {
buffer.append(",\n");
}
else {
buffer.append(".");
}
}
return buffer.toString();
}
public PsiMethod getExtractedMethod() {
return myExtractedMethod;
}
public void setMethodName(String methodName) {
myMethodName = methodName;
}
public Boolean hasDuplicates() {
List<Match> duplicates = getDuplicates();
if (duplicates != null && !duplicates.isEmpty()) {
return true;
}
if (myExtractedMethod != null) {
final ExtractMethodSignatureSuggester suggester = new ExtractMethodSignatureSuggester(myProject, myExtractedMethod, myMethodCall, myVariableDatum);
duplicates = suggester.getDuplicates(myExtractedMethod, myMethodCall, myInputVariables.getFolding());
if (duplicates != null && !duplicates.isEmpty()) {
myDuplicates = duplicates;
myExtractedMethod = suggester.getExtractedMethod();
myMethodCall = suggester.getMethodCall();
myVariableDatum = suggester.getVariableData();
final List<PsiVariable> outputVariables = new ArrayList<>();
for (PsiReturnStatement statement : PsiUtil.findReturnStatements(myExtractedMethod)) {
final PsiExpression returnValue = statement.getReturnValue();
if (returnValue instanceof PsiReferenceExpression) {
final PsiElement resolve = ((PsiReferenceExpression)returnValue).resolve();
if (resolve instanceof PsiLocalVariable) {
outputVariables.add((PsiVariable)resolve);
}
}
}
if (outputVariables.size() == 1) {
myOutputVariable = outputVariables.get(0);
}
return null;
}
}
return false;
}
public boolean hasDuplicates(Set<VirtualFile> files) {
final DuplicatesFinder finder = initDuplicates();
final Boolean hasDuplicates = hasDuplicates();
if (hasDuplicates == null || hasDuplicates) return true;
if (finder != null) {
final PsiManager psiManager = PsiManager.getInstance(myProject);
for (VirtualFile file : files) {
if (!finder.findDuplicates(psiManager.findFile(file)).isEmpty()) return true;
}
}
return false;
}
@Nullable
public String getConfirmDuplicatePrompt(Match match) {
final boolean needToBeStatic = RefactoringUtil.isInStaticContext(match.getMatchStart(), myExtractedMethod.getContainingClass());
final String changedSignature = MatchUtil
.getChangedSignature(match, myExtractedMethod, needToBeStatic, VisibilityUtil.getVisibilityStringToDisplay(myExtractedMethod));
if (changedSignature != null) {
return RefactoringBundle.message("replace.this.code.fragment.and.change.signature", changedSignature);
}
if (needToBeStatic && !myExtractedMethod.hasModifierProperty(PsiModifier.STATIC)) {
return RefactoringBundle.message("replace.this.code.fragment.and.make.method.static");
}
return null;
}
@Override
public String getReplaceDuplicatesTitle(int idx, int size) {
return RefactoringBundle.message("process.duplicates.title", idx, size);
}
public InputVariables getInputVariables() {
return myInputVariables;
}
public PsiTypeParameterList getTypeParameterList() {
return myTypeParameterList;
}
public PsiClassType[] getThrownExceptions() {
return myThrownExceptions;
}
public boolean isStatic() {
return myStatic;
}
public boolean isCanBeStatic() {
return myCanBeStatic;
}
public PsiElement[] getElements() {
return myElements;
}
public PsiVariable[] getOutputVariables() {
return myOutputVariables;
}
public void setMethodVisibility(String methodVisibility) {
myMethodVisibility = methodVisibility;
}
}
|
apixandru/intellij-community
|
java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodProcessor.java
|
Java
|
apache-2.0
| 90,417 |
#
# 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.
from collections import Counter
import airflow
from airflow.ti_deps.deps.base_ti_dep import BaseTIDep
from airflow.utils.session import provide_session
from airflow.utils.state import State
class TriggerRuleDep(BaseTIDep):
"""
Determines if a task's upstream tasks are in a state that allows a given task instance
to run.
"""
NAME = "Trigger Rule"
IGNOREABLE = True
IS_TASK_DEP = True
@staticmethod
def _get_states_count_upstream_ti(ti, finished_tasks):
"""
This function returns the states of the upstream tis for a specific ti in order to determine
whether this ti can run in this iteration
:param ti: the ti that we want to calculate deps for
:type ti: airflow.models.TaskInstance
:param finished_tasks: all the finished tasks of the dag_run
:type finished_tasks: list[airflow.models.TaskInstance]
"""
counter = Counter(task.state for task in finished_tasks if task.task_id in ti.task.upstream_task_ids)
return counter.get(State.SUCCESS, 0), counter.get(State.SKIPPED, 0), counter.get(State.FAILED, 0), \
counter.get(State.UPSTREAM_FAILED, 0), sum(counter.values())
@provide_session
def _get_dep_statuses(self, ti, session, dep_context):
TR = airflow.utils.trigger_rule.TriggerRule
# Checking that all upstream dependencies have succeeded
if not ti.task.upstream_list:
yield self._passing_status(
reason="The task instance did not have any upstream tasks.")
return
if ti.task.trigger_rule == TR.DUMMY:
yield self._passing_status(reason="The task had a dummy trigger rule set.")
return
# see if the task name is in the task upstream for our task
successes, skipped, failed, upstream_failed, done = self._get_states_count_upstream_ti(
ti=ti,
finished_tasks=dep_context.ensure_finished_tasks(ti.task.dag, ti.execution_date, session))
yield from self._evaluate_trigger_rule(
ti=ti,
successes=successes,
skipped=skipped,
failed=failed,
upstream_failed=upstream_failed,
done=done,
flag_upstream_failed=dep_context.flag_upstream_failed,
session=session)
@provide_session
def _evaluate_trigger_rule( # pylint: disable=too-many-branches
self,
ti,
successes,
skipped,
failed,
upstream_failed,
done,
flag_upstream_failed,
session):
"""
Yields a dependency status that indicate whether the given task instance's trigger
rule was met.
:param ti: the task instance to evaluate the trigger rule of
:type ti: airflow.models.TaskInstance
:param successes: Number of successful upstream tasks
:type successes: int
:param skipped: Number of skipped upstream tasks
:type skipped: int
:param failed: Number of failed upstream tasks
:type failed: int
:param upstream_failed: Number of upstream_failed upstream tasks
:type upstream_failed: int
:param done: Number of completed upstream tasks
:type done: int
:param flag_upstream_failed: This is a hack to generate
the upstream_failed state creation while checking to see
whether the task instance is runnable. It was the shortest
path to add the feature
:type flag_upstream_failed: bool
:param session: database session
:type session: sqlalchemy.orm.session.Session
"""
TR = airflow.utils.trigger_rule.TriggerRule
task = ti.task
upstream = len(task.upstream_task_ids)
trigger_rule = task.trigger_rule
upstream_done = done >= upstream
upstream_tasks_state = {
"total": upstream, "successes": successes, "skipped": skipped,
"failed": failed, "upstream_failed": upstream_failed, "done": done
}
# TODO(aoen): Ideally each individual trigger rules would be its own class, but
# this isn't very feasible at the moment since the database queries need to be
# bundled together for efficiency.
# handling instant state assignment based on trigger rules
if flag_upstream_failed:
if trigger_rule == TR.ALL_SUCCESS:
if upstream_failed or failed:
ti.set_state(State.UPSTREAM_FAILED, session)
elif skipped:
ti.set_state(State.SKIPPED, session)
elif trigger_rule == TR.ALL_FAILED:
if successes or skipped:
ti.set_state(State.SKIPPED, session)
elif trigger_rule == TR.ONE_SUCCESS:
if upstream_done and not successes:
ti.set_state(State.SKIPPED, session)
elif trigger_rule == TR.ONE_FAILED:
if upstream_done and not (failed or upstream_failed):
ti.set_state(State.SKIPPED, session)
elif trigger_rule == TR.NONE_FAILED:
if upstream_failed or failed:
ti.set_state(State.UPSTREAM_FAILED, session)
elif trigger_rule == TR.NONE_FAILED_OR_SKIPPED:
if upstream_failed or failed:
ti.set_state(State.UPSTREAM_FAILED, session)
elif skipped == upstream:
ti.set_state(State.SKIPPED, session)
elif trigger_rule == TR.NONE_SKIPPED:
if skipped:
ti.set_state(State.SKIPPED, session)
if trigger_rule == TR.ONE_SUCCESS:
if successes <= 0:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires one upstream "
"task success, but none were found. "
"upstream_tasks_state={1}, upstream_task_ids={2}"
.format(trigger_rule, upstream_tasks_state, task.upstream_task_ids))
elif trigger_rule == TR.ONE_FAILED:
if not failed and not upstream_failed:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires one upstream "
"task failure, but none were found. "
"upstream_tasks_state={1}, upstream_task_ids={2}"
.format(trigger_rule, upstream_tasks_state, task.upstream_task_ids))
elif trigger_rule == TR.ALL_SUCCESS:
num_failures = upstream - successes
if num_failures > 0:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to have succeeded, but found {1} non-success(es). "
"upstream_tasks_state={2}, upstream_task_ids={3}"
.format(trigger_rule, num_failures, upstream_tasks_state,
task.upstream_task_ids))
elif trigger_rule == TR.ALL_FAILED:
num_successes = upstream - failed - upstream_failed
if num_successes > 0:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to have failed, but found {1} non-failure(s). "
"upstream_tasks_state={2}, upstream_task_ids={3}"
.format(trigger_rule, num_successes, upstream_tasks_state,
task.upstream_task_ids))
elif trigger_rule == TR.ALL_DONE:
if not upstream_done:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to have completed, but found {1} task(s) that "
"weren't done. upstream_tasks_state={2}, "
"upstream_task_ids={3}"
.format(trigger_rule, upstream_done, upstream_tasks_state,
task.upstream_task_ids))
elif trigger_rule == TR.NONE_FAILED:
num_failures = upstream - successes - skipped
if num_failures > 0:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to have succeeded or been skipped, but found {1} non-success(es). "
"upstream_tasks_state={2}, upstream_task_ids={3}"
.format(trigger_rule, num_failures, upstream_tasks_state,
task.upstream_task_ids))
elif trigger_rule == TR.NONE_FAILED_OR_SKIPPED:
num_failures = upstream - successes - skipped
if num_failures > 0:
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to have succeeded or been skipped, but found {1} non-success(es). "
"upstream_tasks_state={2}, upstream_task_ids={3}"
.format(trigger_rule, num_failures, upstream_tasks_state,
task.upstream_task_ids))
elif trigger_rule == TR.NONE_SKIPPED:
if not upstream_done or (skipped > 0):
yield self._failing_status(
reason="Task's trigger rule '{0}' requires all upstream "
"tasks to not have been skipped, but found {1} task(s) skipped. "
"upstream_tasks_state={2}, upstream_task_ids={3}"
.format(trigger_rule, skipped, upstream_tasks_state,
task.upstream_task_ids))
else:
yield self._failing_status(
reason="No strategy to evaluate trigger rule '{0}'.".format(trigger_rule))
|
wooga/airflow
|
airflow/ti_deps/deps/trigger_rule_dep.py
|
Python
|
apache-2.0
| 10,691 |
/*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes an association between a route table and a subnet.
/// </summary>
public partial class RouteTableAssociation
{
private bool? _main;
private string _routeTableAssociationId;
private string _routeTableId;
private string _subnetId;
/// <summary>
/// Gets and sets the property Main.
/// <para>
/// Indicates whether this is the main route table.
/// </para>
/// </summary>
public bool Main
{
get { return this._main.GetValueOrDefault(); }
set { this._main = value; }
}
// Check to see if Main property is set
internal bool IsSetMain()
{
return this._main.HasValue;
}
/// <summary>
/// Gets and sets the property RouteTableAssociationId.
/// <para>
/// The ID of the association between a route table and a subnet.
/// </para>
/// </summary>
public string RouteTableAssociationId
{
get { return this._routeTableAssociationId; }
set { this._routeTableAssociationId = value; }
}
// Check to see if RouteTableAssociationId property is set
internal bool IsSetRouteTableAssociationId()
{
return this._routeTableAssociationId != null;
}
/// <summary>
/// Gets and sets the property RouteTableId.
/// <para>
/// The ID of the route table.
/// </para>
/// </summary>
public string RouteTableId
{
get { return this._routeTableId; }
set { this._routeTableId = value; }
}
// Check to see if RouteTableId property is set
internal bool IsSetRouteTableId()
{
return this._routeTableId != null;
}
/// <summary>
/// Gets and sets the property SubnetId.
/// <para>
/// The ID of the subnet. A subnet ID is not returned for an implicit association.
/// </para>
/// </summary>
public string SubnetId
{
get { return this._subnetId; }
set { this._subnetId = value; }
}
// Check to see if SubnetId property is set
internal bool IsSetSubnetId()
{
return this._subnetId != null;
}
}
}
|
rafd123/aws-sdk-net
|
sdk/src/Services/EC2/Generated/Model/RouteTableAssociation.cs
|
C#
|
apache-2.0
| 3,312 |
package io.codearcs.candlestack.aws.rds;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import io.codearcs.candlestack.CandlestackPropertiesException;
import io.codearcs.candlestack.MetricsReaderWriter;
import io.codearcs.candlestack.aws.CloudWatchStatistic;
import io.codearcs.candlestack.aws.GlobalAWSProperties;
import io.codearcs.candlestack.aws.cloudwatch.CloudWatchMetric;
import io.codearcs.candlestack.nagios.object.commands.Command;
import io.codearcs.candlestack.nagios.object.services.Service;
public enum RDSCloudWatchMetric implements CloudWatchMetric {
CPUUtilization( CloudWatchStatistic.Average,
"check-cpu",
"check-aws-rds-cpu",
"check-aws-rds-cpu-via-es.sh",
"Checks to see if the RDS instance is experiencing heavy CPU load. In the event an alert is triggered check the RDS instance for potential query issues causing the heavy CPU load.",
new HashSet<>( Arrays.asList( RDSType.AURORA, RDSType.AURORA_MYSQL, RDSType.MARIADB ) ),
false,
false ),
DatabaseConnections( CloudWatchStatistic.Maximum,
"check-db-connections",
"check-aws-rds-db-connections",
"check-aws-rds-db-connections-via-es.sh",
"Checks to see if the RDS instance is experiencing high number of database connections. In the event an alert is triggered check the users of the RDS instance for potential connection leaks.",
new HashSet<>( Arrays.asList( RDSType.AURORA, RDSType.AURORA_MYSQL, RDSType.MARIADB ) ),
false,
false ),
FreeStorageSpace( CloudWatchStatistic.Minimum,
"check-free-storage",
"check-aws-rds-free-storage",
"check-aws-rds-free-storage-via-es.sh",
"Checks to see if the RDS instance is running low on available storage space. In the event an alert is triggered check the RDS instance for potential issues causing a spike in data usage.",
new HashSet<>( Arrays.asList( RDSType.MARIADB ) ),
false,
false ),
VolumeBytesUsed( CloudWatchStatistic.Average,
"check-storage-used",
"check-aws-rds-storage-used",
"check-aws-rds-storage-used-via-es.sh",
"Checks to see if the RDS instance has used more storage space than has been specified. In the event an alert is triggered check the RDS instance for potential issues causing a spike in data usage.",
new HashSet<>( Arrays.asList( RDSType.AURORA, RDSType.AURORA_MYSQL ) ),
false,
true ),
AuroraReplicaLag( CloudWatchStatistic.Maximum,
"check-replica-lag",
"check-aws-rds-replica-lag",
"check-aws-rds-replica-lag-via-es.sh",
"Checks to see if the Aurora read replica is experiencing a high replication lag. In the event an alert is triggered check the Aurora cluster for potential issues causing the lag.",
new HashSet<>( Arrays.asList( RDSType.AURORA, RDSType.AURORA_MYSQL ) ),
true,
false ),
ActiveTransactions( CloudWatchStatistic.Maximum,
"check-active-transactions",
"check-aws-rds-active-transactions",
"check-aws-rds-active-transactions-via-es.sh",
"Checks to see if the RDS instance is experiencing a large number of active transactions. In the event an alert is triggered check the RDS instance for potential query issues causing the transaction build up.",
new HashSet<>( Arrays.asList( RDSType.AURORA, RDSType.AURORA_MYSQL ) ),
false,
false );
private static final String NAMESPACE = "AWS/RDS";
private String serviceName, commandName, scriptFileName, notes, logsHost, logsAuthToken;
private CloudWatchStatistic statistic;
private Set<RDSType> supportedRDSTypes;
private boolean replicaOnly, clusterOnly;
private RDSCloudWatchMetric( CloudWatchStatistic statistic, String serviceName, String commandName, String scriptFileName, String notes, Set<RDSType> supportedRDSTypes, boolean replicaOnly, boolean clusterOnly ) {
this.statistic = statistic;
this.serviceName = serviceName;
this.commandName = commandName;
this.scriptFileName = scriptFileName;
this.notes = notes;
this.supportedRDSTypes = supportedRDSTypes;
this.replicaOnly = replicaOnly;
this.clusterOnly = clusterOnly;
try {
logsHost = GlobalAWSProperties.getLogsHost();
logsAuthToken = GlobalAWSProperties.getLogsAuthToken();
} catch ( CandlestackPropertiesException ignore ) {
// We will see this error else where if this is the case
}
}
@Override
public CloudWatchStatistic getStatistic() {
return statistic;
}
@Override
public String getServiceName() {
return serviceName;
}
@Override
public String getCommandName() {
return commandName;
}
@Override
public String getScriptFileName() {
return scriptFileName;
}
public boolean isRDSTypeSupported( RDSType rdsType ) {
return supportedRDSTypes.contains( rdsType );
}
public boolean isReplicaOnlyMetric() {
return replicaOnly;
}
public boolean isClusterOnlyMetric() {
return clusterOnly;
}
@Override
public Service getService( String dbInstanceId, Set<String> contactGroups ) throws CandlestackPropertiesException {
long warning = GlobalAWSProperties.getRDSCloudWatchMetricWarningLevel( dbInstanceId, this );
long critical = GlobalAWSProperties.getRDSCloudWatchMetricCriticalLevel( dbInstanceId, this );
String command = commandName + "!" + MetricsReaderWriter.sanitizeString( dbInstanceId ) + "!" + warning + "!" + critical;
String notificationPeriod = GlobalAWSProperties.getRDSServiceNotificationPeriod( dbInstanceId );
return new Service( serviceName, dbInstanceId, command, notes, notificationPeriod, contactGroups );
}
@Override
public Command getMonitorCommand( String relativePathToMonitorResource ) {
return new Command( commandName, relativePathToMonitorResource + scriptFileName + " " + logsHost + " " + logsAuthToken + " $ARG1$ $ARG2$ $ARG3$" );
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
public String getName() {
return name();
}
}
|
CodeArcsInc/candlestack
|
src/main/java/io/codearcs/candlestack/aws/rds/RDSCloudWatchMetric.java
|
Java
|
apache-2.0
| 5,836 |
# 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.
from openstack import _log
from openstack.baremetal.v1 import node as _node
from openstack.baremetal_introspection.v1 import introspection as _introspect
from openstack import exceptions
from openstack import proxy
_logger = _log.setup_logging('openstack')
class Proxy(proxy.Proxy):
def introspections(self, **query):
"""Retrieve a generator of introspection records.
:param dict query: Optional query parameters to be sent to restrict
the records to be returned. Available parameters include:
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``limit``: Requests at most the specified number of items be
returned from the query.
* ``marker``: Specifies the ID of the last-seen introspection. Use
the ``limit`` parameter to make an initial limited request and
use the ID of the last-seen introspection from the response as
the ``marker`` value in a subsequent limited request.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of :class:`~.introspection.Introspection`
objects
"""
return _introspect.Introspection.list(self, **query)
def start_introspection(self, node, manage_boot=None):
"""Create a new introspection from attributes.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param bool manage_boot: Whether to manage boot parameters for the
node. Defaults to the server default (which is `True`).
:returns: :class:`~.introspection.Introspection` instance.
"""
node = self._get_resource(_node.Node, node)
res = _introspect.Introspection.new(connection=self._get_connection(),
id=node.id)
kwargs = {}
if manage_boot is not None:
kwargs['manage_boot'] = manage_boot
return res.create(self, **kwargs)
def get_introspection(self, introspection):
"""Get a specific introspection.
:param introspection: The value can be the name or ID of an
introspection (matching bare metal node name or ID) or
an :class:`~.introspection.Introspection` instance.
:returns: :class:`~.introspection.Introspection` instance.
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
introspection matching the name or ID could be found.
"""
return self._get(_introspect.Introspection, introspection)
def get_introspection_data(self, introspection, processed=True):
"""Get introspection data.
:param introspection: The value can be the name or ID of an
introspection (matching bare metal node name or ID) or
an :class:`~.introspection.Introspection` instance.
:param processed: Whether to fetch the final processed data (the
default) or the raw unprocessed data as received from the ramdisk.
:returns: introspection data from the most recent successful run.
:rtype: dict
"""
res = self._get_resource(_introspect.Introspection, introspection)
return res.get_data(self, processed=processed)
def abort_introspection(self, introspection, ignore_missing=True):
"""Abort an introspection.
Note that the introspection is not aborted immediately, you may use
`wait_for_introspection` with `ignore_error=True`.
:param introspection: The value can be the name or ID of an
introspection (matching bare metal node name or ID) or
an :class:`~.introspection.Introspection` instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the introspection could not be found. When set to ``True``, no
exception will be raised when attempting to abort a non-existent
introspection.
:returns: nothing
"""
res = self._get_resource(_introspect.Introspection, introspection)
try:
res.abort(self)
except exceptions.ResourceNotFound:
if not ignore_missing:
raise
def wait_for_introspection(self, introspection, timeout=None,
ignore_error=False):
"""Wait for the introspection to finish.
:param introspection: The value can be the name or ID of an
introspection (matching bare metal node name or ID) or
an :class:`~.introspection.Introspection` instance.
:param timeout: How much (in seconds) to wait for the introspection.
The value of ``None`` (the default) means no client-side timeout.
:param ignore_error: If ``True``, this call will raise an exception
if the introspection reaches the ``error`` state. Otherwise the
error state is considered successful and the call returns.
:returns: :class:`~.introspection.Introspection` instance.
:raises: :class:`~openstack.exceptions.ResourceFailure` if
introspection fails and ``ignore_error`` is ``False``.
:raises: :class:`~openstack.exceptions.ResourceTimeout` on timeout.
"""
res = self._get_resource(_introspect.Introspection, introspection)
return res.wait(self, timeout=timeout, ignore_error=ignore_error)
|
stackforge/python-openstacksdk
|
openstack/baremetal_introspection/v1/_proxy.py
|
Python
|
apache-2.0
| 7,038 |
/*
** Copyright 2011, 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.
*/
package com.android.server.accessibility;
import android.content.Context;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GesturePoint;
import android.gesture.GestureStore;
import android.gesture.GestureStroke;
import android.gesture.Prediction;
import android.graphics.Rect;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Slog;
import android.view.MotionEvent;
import android.view.MotionEvent.PointerCoords;
import android.view.MotionEvent.PointerProperties;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
import android.view.WindowManagerPolicy;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import com.android.internal.R;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* This class is a strategy for performing touch exploration. It
* transforms the motion event stream by modifying, adding, replacing,
* and consuming certain events. The interaction model is:
*
* <ol>
* <li>1. One finger moving slow around performs touch exploration.</li>
* <li>2. One finger moving fast around performs gestures.</li>
* <li>3. Two close fingers moving in the same direction perform a drag.</li>
* <li>4. Multi-finger gestures are delivered to view hierarchy.</li>
* <li>5. Two fingers moving in different directions are considered a multi-finger gesture.</li>
* <li>7. Double tapping clicks on the on the last touch explored location if it was in
* a window that does not take focus, otherwise the click is within the accessibility
* focused rectangle.</li>
* <li>7. Tapping and holding for a while performs a long press in a similar fashion
* as the click above.</li>
* <ol>
*
* @hide
*/
class TouchExplorer implements EventStreamTransformation {
private static final boolean DEBUG = false;
// Tag for logging received events.
private static final String LOG_TAG = "TouchExplorer";
// States this explorer can be in.
private static final int STATE_TOUCH_EXPLORING = 0x00000001;
private static final int STATE_DRAGGING = 0x00000002;
private static final int STATE_DELEGATING = 0x00000004;
private static final int STATE_GESTURE_DETECTING = 0x00000005;
// The minimum of the cosine between the vectors of two moving
// pointers so they can be considered moving in the same direction.
private static final float MAX_DRAGGING_ANGLE_COS = 0.525321989f; // cos(pi/4)
// Constant referring to the ids bits of all pointers.
private static final int ALL_POINTER_ID_BITS = 0xFFFFFFFF;
// This constant captures the current implementation detail that
// pointer IDs are between 0 and 31 inclusive (subject to change).
// (See MAX_POINTER_ID in frameworks/base/include/ui/Input.h)
private static final int MAX_POINTER_COUNT = 32;
// Invalid pointer ID.
private static final int INVALID_POINTER_ID = -1;
// The velocity above which we detect gestures.
private static final int GESTURE_DETECTION_VELOCITY_DIP = 1000;
// The minimal distance before we take the middle of the distance between
// the two dragging pointers as opposed to use the location of the primary one.
private static final int MIN_POINTER_DISTANCE_TO_USE_MIDDLE_LOCATION_DIP = 200;
// The timeout after which we are no longer trying to detect a gesture.
private static final int EXIT_GESTURE_DETECTION_TIMEOUT = 2000;
// Timeout before trying to decide what the user is trying to do.
private final int mDetermineUserIntentTimeout;
// Timeout within which we try to detect a tap.
private final int mTapTimeout;
// Timeout within which we try to detect a double tap.
private final int mDoubleTapTimeout;
// Slop between the down and up tap to be a tap.
private final int mTouchSlop;
// Slop between the first and second tap to be a double tap.
private final int mDoubleTapSlop;
// The current state of the touch explorer.
private int mCurrentState = STATE_TOUCH_EXPLORING;
// The ID of the pointer used for dragging.
private int mDraggingPointerId;
// Handler for performing asynchronous operations.
private final Handler mHandler;
// Command for delayed sending of a hover enter and move event.
private final SendHoverEnterAndMoveDelayed mSendHoverEnterAndMoveDelayed;
// Command for delayed sending of a hover exit event.
private final SendHoverExitDelayed mSendHoverExitDelayed;
// Command for delayed sending of touch exploration end events.
private final SendAccessibilityEventDelayed mSendTouchExplorationEndDelayed;
// Command for delayed sending of touch interaction end events.
private final SendAccessibilityEventDelayed mSendTouchInteractionEndDelayed;
// Command for delayed sending of a long press.
private final PerformLongPressDelayed mPerformLongPressDelayed;
// Command for exiting gesture detection mode after a timeout.
private final ExitGestureDetectionModeDelayed mExitGestureDetectionModeDelayed;
// Helper to detect and react to double tap in touch explore mode.
private final DoubleTapDetector mDoubleTapDetector;
// The scaled minimal distance before we take the middle of the distance between
// the two dragging pointers as opposed to use the location of the primary one.
private final int mScaledMinPointerDistanceToUseMiddleLocation;
// The scaled velocity above which we detect gestures.
private final int mScaledGestureDetectionVelocity;
// The handler to which to delegate events.
private EventStreamTransformation mNext;
// Helper to track gesture velocity.
private final VelocityTracker mVelocityTracker = VelocityTracker.obtain();
// Helper class to track received pointers.
private final ReceivedPointerTracker mReceivedPointerTracker;
// Helper class to track injected pointers.
private final InjectedPointerTracker mInjectedPointerTracker;
// Handle to the accessibility manager service.
private final AccessibilityManagerService mAms;
// Temporary rectangle to avoid instantiation.
private final Rect mTempRect = new Rect();
// Context in which this explorer operates.
private final Context mContext;
// The X of the previous event.
private float mPreviousX;
// The Y of the previous event.
private float mPreviousY;
// Buffer for storing points for gesture detection.
private final ArrayList<GesturePoint> mStrokeBuffer = new ArrayList<GesturePoint>(100);
// The minimal delta between moves to add a gesture point.
private static final int TOUCH_TOLERANCE = 3;
// The minimal score for accepting a predicted gesture.
private static final float MIN_PREDICTION_SCORE = 2.0f;
// The library for gesture detection.
private GestureLibrary mGestureLibrary;
// The long pressing pointer id if coordinate remapping is needed.
private int mLongPressingPointerId = -1;
// The long pressing pointer X if coordinate remapping is needed.
private int mLongPressingPointerDeltaX;
// The long pressing pointer Y if coordinate remapping is needed.
private int mLongPressingPointerDeltaY;
// The id of the last touch explored window.
private int mLastTouchedWindowId;
// Whether touch exploration is in progress.
private boolean mTouchExplorationInProgress;
/**
* Creates a new instance.
*
* @param inputFilter The input filter associated with this explorer.
* @param context A context handle for accessing resources.
*/
public TouchExplorer(Context context, AccessibilityManagerService service) {
mContext = context;
mAms = service;
mReceivedPointerTracker = new ReceivedPointerTracker();
mInjectedPointerTracker = new InjectedPointerTracker();
mTapTimeout = ViewConfiguration.getTapTimeout();
mDetermineUserIntentTimeout = ViewConfiguration.getDoubleTapTimeout();
mDoubleTapTimeout = ViewConfiguration.getDoubleTapTimeout();
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mDoubleTapSlop = ViewConfiguration.get(context).getScaledDoubleTapSlop();
mHandler = new Handler(context.getMainLooper());
mPerformLongPressDelayed = new PerformLongPressDelayed();
mExitGestureDetectionModeDelayed = new ExitGestureDetectionModeDelayed();
mGestureLibrary = GestureLibraries.fromRawResource(context, R.raw.accessibility_gestures);
mGestureLibrary.setOrientationStyle(8);
mGestureLibrary.setSequenceType(GestureStore.SEQUENCE_SENSITIVE);
mGestureLibrary.load();
mSendHoverEnterAndMoveDelayed = new SendHoverEnterAndMoveDelayed();
mSendHoverExitDelayed = new SendHoverExitDelayed();
mSendTouchExplorationEndDelayed = new SendAccessibilityEventDelayed(
AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END,
mDetermineUserIntentTimeout);
mSendTouchInteractionEndDelayed = new SendAccessibilityEventDelayed(
AccessibilityEvent.TYPE_TOUCH_INTERACTION_END,
mDetermineUserIntentTimeout);
mDoubleTapDetector = new DoubleTapDetector();
final float density = context.getResources().getDisplayMetrics().density;
mScaledMinPointerDistanceToUseMiddleLocation =
(int) (MIN_POINTER_DISTANCE_TO_USE_MIDDLE_LOCATION_DIP * density);
mScaledGestureDetectionVelocity = (int) (GESTURE_DETECTION_VELOCITY_DIP * density);
}
public void clear() {
// If we have not received an event then we are in initial
// state. Therefore, there is not need to clean anything.
MotionEvent event = mReceivedPointerTracker.getLastReceivedEvent();
if (event != null) {
clear(mReceivedPointerTracker.getLastReceivedEvent(), WindowManagerPolicy.FLAG_TRUSTED);
}
}
public void onDestroy() {
// TODO: Implement
}
private void clear(MotionEvent event, int policyFlags) {
switch (mCurrentState) {
case STATE_TOUCH_EXPLORING: {
// If a touch exploration gesture is in progress send events for its end.
sendHoverExitAndTouchExplorationGestureEndIfNeeded(policyFlags);
} break;
case STATE_DRAGGING: {
mDraggingPointerId = INVALID_POINTER_ID;
// Send exit to all pointers that we have delivered.
sendUpForInjectedDownPointers(event, policyFlags);
} break;
case STATE_DELEGATING: {
// Send exit to all pointers that we have delivered.
sendUpForInjectedDownPointers(event, policyFlags);
} break;
case STATE_GESTURE_DETECTING: {
// Clear the current stroke.
mStrokeBuffer.clear();
} break;
}
// Remove all pending callbacks.
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
mExitGestureDetectionModeDelayed.cancel();
mSendTouchExplorationEndDelayed.cancel();
mSendTouchInteractionEndDelayed.cancel();
// Reset the pointer trackers.
mReceivedPointerTracker.clear();
mInjectedPointerTracker.clear();
// Clear the double tap detector
mDoubleTapDetector.clear();
// Go to initial state.
// Clear the long pressing pointer remap data.
mLongPressingPointerId = -1;
mLongPressingPointerDeltaX = 0;
mLongPressingPointerDeltaY = 0;
mCurrentState = STATE_TOUCH_EXPLORING;
if (mNext != null) {
mNext.clear();
}
mTouchExplorationInProgress = false;
mAms.onTouchInteractionEnd();
}
@Override
public void setNext(EventStreamTransformation next) {
mNext = next;
}
@Override
public void onMotionEvent(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
if (DEBUG) {
Slog.d(LOG_TAG, "Received event: " + event + ", policyFlags=0x"
+ Integer.toHexString(policyFlags));
Slog.d(LOG_TAG, getStateSymbolicName(mCurrentState));
}
mReceivedPointerTracker.onMotionEvent(rawEvent);
switch(mCurrentState) {
case STATE_TOUCH_EXPLORING: {
handleMotionEventStateTouchExploring(event, rawEvent, policyFlags);
} break;
case STATE_DRAGGING: {
handleMotionEventStateDragging(event, policyFlags);
} break;
case STATE_DELEGATING: {
handleMotionEventStateDelegating(event, policyFlags);
} break;
case STATE_GESTURE_DETECTING: {
handleMotionEventGestureDetecting(rawEvent, policyFlags);
} break;
default:
throw new IllegalStateException("Illegal state: " + mCurrentState);
}
}
public void onAccessibilityEvent(AccessibilityEvent event) {
final int eventType = event.getEventType();
// The event for gesture end should be strictly after the
// last hover exit event.
if (mSendTouchExplorationEndDelayed.isPending()
&& eventType == AccessibilityEvent.TYPE_VIEW_HOVER_EXIT) {
mSendTouchExplorationEndDelayed.cancel();
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END);
}
// The event for touch interaction end should be strictly after the
// last hover exit and the touch exploration gesture end events.
if (mSendTouchInteractionEndDelayed.isPending()
&& eventType == AccessibilityEvent.TYPE_VIEW_HOVER_EXIT) {
mSendTouchInteractionEndDelayed.cancel();
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_END);
}
// If a new window opens or the accessibility focus moves we no longer
// want to click/long press on the last touch explored location.
switch (eventType) {
case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
if (mInjectedPointerTracker.mLastInjectedHoverEventForClick != null) {
mInjectedPointerTracker.mLastInjectedHoverEventForClick.recycle();
mInjectedPointerTracker.mLastInjectedHoverEventForClick = null;
}
mLastTouchedWindowId = -1;
} break;
case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER:
case AccessibilityEvent.TYPE_VIEW_HOVER_EXIT: {
mLastTouchedWindowId = event.getWindowId();
} break;
}
if (mNext != null) {
mNext.onAccessibilityEvent(event);
}
}
/**
* Handles a motion event in touch exploring state.
*
* @param event The event to be handled.
* @param rawEvent The raw (unmodified) motion event.
* @param policyFlags The policy flags associated with the event.
*/
private void handleMotionEventStateTouchExploring(MotionEvent event, MotionEvent rawEvent,
int policyFlags) {
ReceivedPointerTracker receivedTracker = mReceivedPointerTracker;
mVelocityTracker.addMovement(rawEvent);
mDoubleTapDetector.onMotionEvent(event, policyFlags);
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
mAms.onTouchInteractionStart();
// Pre-feed the motion events to the gesture detector since we
// have a distance slop before getting into gesture detection
// mode and not using the points within this slop significantly
// decreases the quality of gesture recognition.
handleMotionEventGestureDetecting(rawEvent, policyFlags);
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_START);
// If we still have not notified the user for the last
// touch, we figure out what to do. If were waiting
// we resent the delayed callback and wait again.
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
if (mSendTouchExplorationEndDelayed.isPending()) {
mSendTouchExplorationEndDelayed.forceSendAndRemove();
}
if (mSendTouchInteractionEndDelayed.isPending()) {
mSendTouchInteractionEndDelayed.forceSendAndRemove();
}
// If we have the first tap, schedule a long press and break
// since we do not want to schedule hover enter because
// the delayed callback will kick in before the long click.
// This would lead to a state transition resulting in long
// pressing the item below the double taped area which is
// not necessary where accessibility focus is.
if (mDoubleTapDetector.firstTapDetected()) {
// We got a tap now post a long press action.
mPerformLongPressDelayed.post(event, policyFlags);
break;
}
if (!mTouchExplorationInProgress) {
if (!mSendHoverEnterAndMoveDelayed.isPending()) {
// Deliver hover enter with a delay to have a chance
// to detect what the user is trying to do.
final int pointerId = receivedTracker.getPrimaryPointerId();
final int pointerIdBits = (1 << pointerId);
mSendHoverEnterAndMoveDelayed.post(event, true, pointerIdBits,
policyFlags);
}
// Cache the event until we discern exploration from gesturing.
mSendHoverEnterAndMoveDelayed.addEvent(event);
}
} break;
case MotionEvent.ACTION_POINTER_DOWN: {
/* do nothing - let the code for ACTION_MOVE decide what to do */
} break;
case MotionEvent.ACTION_MOVE: {
final int pointerId = receivedTracker.getPrimaryPointerId();
final int pointerIndex = event.findPointerIndex(pointerId);
final int pointerIdBits = (1 << pointerId);
switch (event.getPointerCount()) {
case 1: {
// We have not started sending events since we try to
// figure out what the user is doing.
if (mSendHoverEnterAndMoveDelayed.isPending()) {
// Pre-feed the motion events to the gesture detector since we
// have a distance slop before getting into gesture detection
// mode and not using the points within this slop significantly
// decreases the quality of gesture recognition.
handleMotionEventGestureDetecting(rawEvent, policyFlags);
// Cache the event until we discern exploration from gesturing.
mSendHoverEnterAndMoveDelayed.addEvent(event);
// It is *important* to use the distance traveled by the pointers
// on the screen which may or may not be magnified.
final float deltaX = receivedTracker.getReceivedPointerDownX(pointerId)
- rawEvent.getX(pointerIndex);
final float deltaY = receivedTracker.getReceivedPointerDownY(pointerId)
- rawEvent.getY(pointerIndex);
final double moveDelta = Math.hypot(deltaX, deltaY);
// The user has moved enough for us to decide.
if (moveDelta > mDoubleTapSlop) {
// Check whether the user is performing a gesture. We
// detect gestures if the pointer is moving above a
// given velocity.
mVelocityTracker.computeCurrentVelocity(1000);
final float maxAbsVelocity = Math.max(
Math.abs(mVelocityTracker.getXVelocity(pointerId)),
Math.abs(mVelocityTracker.getYVelocity(pointerId)));
if (maxAbsVelocity > mScaledGestureDetectionVelocity) {
// We have to perform gesture detection, so
// clear the current state and try to detect.
mCurrentState = STATE_GESTURE_DETECTING;
mVelocityTracker.clear();
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
mExitGestureDetectionModeDelayed.post();
// Send accessibility event to announce the start
// of gesture recognition.
sendAccessibilityEvent(
AccessibilityEvent.TYPE_GESTURE_DETECTION_START);
} else {
// We have just decided that the user is touch,
// exploring so start sending events.
mSendHoverEnterAndMoveDelayed.forceSendAndRemove();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
sendMotionEvent(event, MotionEvent.ACTION_HOVER_MOVE,
pointerIdBits, policyFlags);
}
break;
}
} else {
// Cancel the long press if pending and the user
// moved more than the slop.
if (mPerformLongPressDelayed.isPending()) {
final float deltaX =
receivedTracker.getReceivedPointerDownX(pointerId)
- rawEvent.getX(pointerIndex);
final float deltaY =
receivedTracker.getReceivedPointerDownY(pointerId)
- rawEvent.getY(pointerIndex);
final double moveDelta = Math.hypot(deltaX, deltaY);
// The user has moved enough for us to decide.
if (moveDelta > mTouchSlop) {
mPerformLongPressDelayed.cancel();
}
}
// The user is either double tapping or performing a long
// press, so do not send move events yet.
if (mDoubleTapDetector.firstTapDetected()) {
break;
}
sendTouchExplorationGestureStartAndHoverEnterIfNeeded(policyFlags);
sendMotionEvent(event, MotionEvent.ACTION_HOVER_MOVE, pointerIdBits,
policyFlags);
}
} break;
case 2: {
// More than one pointer so the user is not touch exploring
// and now we have to decide whether to delegate or drag.
if (mSendHoverEnterAndMoveDelayed.isPending()) {
// We have not started sending events so cancel
// scheduled sending events.
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
} else {
mPerformLongPressDelayed.cancel();
// If the user is touch exploring the second pointer may be
// performing a double tap to activate an item without need
// for the user to lift his exploring finger.
// It is *important* to use the distance traveled by the pointers
// on the screen which may or may not be magnified.
final float deltaX = receivedTracker.getReceivedPointerDownX(pointerId)
- rawEvent.getX(pointerIndex);
final float deltaY = receivedTracker.getReceivedPointerDownY(pointerId)
- rawEvent.getY(pointerIndex);
final double moveDelta = Math.hypot(deltaX, deltaY);
if (moveDelta < mDoubleTapSlop) {
break;
}
// We are sending events so send exit and gesture
// end since we transition to another state.
sendHoverExitAndTouchExplorationGestureEndIfNeeded(policyFlags);
}
// We know that a new state transition is to happen and the
// new state will not be gesture recognition, so clear the
// stashed gesture strokes.
mStrokeBuffer.clear();
if (isDraggingGesture(event)) {
// Two pointers moving in the same direction within
// a given distance perform a drag.
mCurrentState = STATE_DRAGGING;
mDraggingPointerId = pointerId;
event.setEdgeFlags(receivedTracker.getLastReceivedDownEdgeFlags());
sendMotionEvent(event, MotionEvent.ACTION_DOWN, pointerIdBits,
policyFlags);
} else {
// Two pointers moving arbitrary are delegated to the view hierarchy.
mCurrentState = STATE_DELEGATING;
sendDownForAllNotInjectedPointers(event, policyFlags);
}
mVelocityTracker.clear();
} break;
default: {
// More than one pointer so the user is not touch exploring
// and now we have to decide whether to delegate or drag.
if (mSendHoverEnterAndMoveDelayed.isPending()) {
// We have not started sending events so cancel
// scheduled sending events.
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
} else {
mPerformLongPressDelayed.cancel();
// We are sending events so send exit and gesture
// end since we transition to another state.
sendHoverExitAndTouchExplorationGestureEndIfNeeded(policyFlags);
}
// More than two pointers are delegated to the view hierarchy.
mCurrentState = STATE_DELEGATING;
sendDownForAllNotInjectedPointers(event, policyFlags);
mVelocityTracker.clear();
}
}
} break;
case MotionEvent.ACTION_UP: {
mAms.onTouchInteractionEnd();
// We know that we do not need the pre-fed gesture points are not
// needed anymore since the last pointer just went up.
mStrokeBuffer.clear();
final int pointerId = event.getPointerId(event.getActionIndex());
final int pointerIdBits = (1 << pointerId);
mPerformLongPressDelayed.cancel();
mVelocityTracker.clear();
if (mSendHoverEnterAndMoveDelayed.isPending()) {
// If we have not delivered the enter schedule an exit.
mSendHoverExitDelayed.post(event, pointerIdBits, policyFlags);
} else {
// The user is touch exploring so we send events for end.
sendHoverExitAndTouchExplorationGestureEndIfNeeded(policyFlags);
}
if (!mSendTouchInteractionEndDelayed.isPending()) {
mSendTouchInteractionEndDelayed.post();
}
} break;
case MotionEvent.ACTION_CANCEL: {
clear(event, policyFlags);
} break;
}
}
/**
* Handles a motion event in dragging state.
*
* @param event The event to be handled.
* @param policyFlags The policy flags associated with the event.
*/
private void handleMotionEventStateDragging(MotionEvent event, int policyFlags) {
final int pointerIdBits = (1 << mDraggingPointerId);
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
throw new IllegalStateException("Dragging state can be reached only if two "
+ "pointers are already down");
}
case MotionEvent.ACTION_POINTER_DOWN: {
// We are in dragging state so we have two pointers and another one
// goes down => delegate the three pointers to the view hierarchy
mCurrentState = STATE_DELEGATING;
if (mDraggingPointerId != INVALID_POINTER_ID) {
sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
}
sendDownForAllNotInjectedPointers(event, policyFlags);
} break;
case MotionEvent.ACTION_MOVE: {
switch (event.getPointerCount()) {
case 1: {
// do nothing
} break;
case 2: {
if (isDraggingGesture(event)) {
final float firstPtrX = event.getX(0);
final float firstPtrY = event.getY(0);
final float secondPtrX = event.getX(1);
final float secondPtrY = event.getY(1);
final float deltaX = firstPtrX - secondPtrX;
final float deltaY = firstPtrY - secondPtrY;
final double distance = Math.hypot(deltaX, deltaY);
if (distance > mScaledMinPointerDistanceToUseMiddleLocation) {
event.setLocation(deltaX / 2, deltaY / 2);
}
// If still dragging send a drag event.
sendMotionEvent(event, MotionEvent.ACTION_MOVE, pointerIdBits,
policyFlags);
} else {
// The two pointers are moving either in different directions or
// no close enough => delegate the gesture to the view hierarchy.
mCurrentState = STATE_DELEGATING;
// Send an event to the end of the drag gesture.
sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits,
policyFlags);
// Deliver all pointers to the view hierarchy.
sendDownForAllNotInjectedPointers(event, policyFlags);
}
} break;
default: {
mCurrentState = STATE_DELEGATING;
// Send an event to the end of the drag gesture.
sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits,
policyFlags);
// Deliver all pointers to the view hierarchy.
sendDownForAllNotInjectedPointers(event, policyFlags);
}
}
} break;
case MotionEvent.ACTION_POINTER_UP: {
final int pointerId = event.getPointerId(event.getActionIndex());
if (pointerId == mDraggingPointerId) {
mDraggingPointerId = INVALID_POINTER_ID;
// Send an event to the end of the drag gesture.
sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
}
} break;
case MotionEvent.ACTION_UP: {
mAms.onTouchInteractionEnd();
// Announce the end of a new touch interaction.
sendAccessibilityEvent(
AccessibilityEvent.TYPE_TOUCH_INTERACTION_END);
final int pointerId = event.getPointerId(event.getActionIndex());
if (pointerId == mDraggingPointerId) {
mDraggingPointerId = INVALID_POINTER_ID;
// Send an event to the end of the drag gesture.
sendMotionEvent(event, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
}
mCurrentState = STATE_TOUCH_EXPLORING;
} break;
case MotionEvent.ACTION_CANCEL: {
clear(event, policyFlags);
} break;
}
}
/**
* Handles a motion event in delegating state.
*
* @param event The event to be handled.
* @param policyFlags The policy flags associated with the event.
*/
private void handleMotionEventStateDelegating(MotionEvent event, int policyFlags) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
throw new IllegalStateException("Delegating state can only be reached if "
+ "there is at least one pointer down!");
}
case MotionEvent.ACTION_UP: {
mAms.onTouchInteractionEnd();
// Announce the end of a the touch interaction.
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_END);
mLongPressingPointerId = -1;
mLongPressingPointerDeltaX = 0;
mLongPressingPointerDeltaY = 0;
mCurrentState = STATE_TOUCH_EXPLORING;
} break;
case MotionEvent.ACTION_CANCEL: {
clear(event, policyFlags);
} break;
}
// Deliver the event.
sendMotionEvent(event, event.getAction(), ALL_POINTER_ID_BITS, policyFlags);
}
private void handleMotionEventGestureDetecting(MotionEvent event, int policyFlags) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
final float x = event.getX();
final float y = event.getY();
mPreviousX = x;
mPreviousY = y;
mStrokeBuffer.add(new GesturePoint(x, y, event.getEventTime()));
} break;
case MotionEvent.ACTION_MOVE: {
final float x = event.getX();
final float y = event.getY();
final float dX = Math.abs(x - mPreviousX);
final float dY = Math.abs(y - mPreviousY);
if (dX >= TOUCH_TOLERANCE || dY >= TOUCH_TOLERANCE) {
mPreviousX = x;
mPreviousY = y;
mStrokeBuffer.add(new GesturePoint(x, y, event.getEventTime()));
}
} break;
case MotionEvent.ACTION_UP: {
mAms.onTouchInteractionEnd();
// Announce the end of the gesture recognition.
sendAccessibilityEvent(AccessibilityEvent.TYPE_GESTURE_DETECTION_END);
// Announce the end of a the touch interaction.
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_INTERACTION_END);
float x = event.getX();
float y = event.getY();
mStrokeBuffer.add(new GesturePoint(x, y, event.getEventTime()));
Gesture gesture = new Gesture();
gesture.addStroke(new GestureStroke(mStrokeBuffer));
ArrayList<Prediction> predictions = mGestureLibrary.recognize(gesture);
if (!predictions.isEmpty()) {
Prediction bestPrediction = predictions.get(0);
if (bestPrediction.score >= MIN_PREDICTION_SCORE) {
if (DEBUG) {
Slog.i(LOG_TAG, "gesture: " + bestPrediction.name + " score: "
+ bestPrediction.score);
}
try {
final int gestureId = Integer.parseInt(bestPrediction.name);
mAms.onGesture(gestureId);
} catch (NumberFormatException nfe) {
Slog.w(LOG_TAG, "Non numeric gesture id:" + bestPrediction.name);
}
}
}
mStrokeBuffer.clear();
mExitGestureDetectionModeDelayed.cancel();
mCurrentState = STATE_TOUCH_EXPLORING;
} break;
case MotionEvent.ACTION_CANCEL: {
clear(event, policyFlags);
} break;
}
}
/**
* Sends an accessibility event of the given type.
*
* @param type The event type.
*/
private void sendAccessibilityEvent(int type) {
AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext);
if (accessibilityManager.isEnabled()) {
AccessibilityEvent event = AccessibilityEvent.obtain(type);
event.setWindowId(mAms.getActiveWindowId());
accessibilityManager.sendAccessibilityEvent(event);
switch (type) {
case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START: {
mTouchExplorationInProgress = true;
} break;
case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END: {
mTouchExplorationInProgress = false;
} break;
}
}
}
/**
* Sends down events to the view hierarchy for all pointers which are
* not already being delivered i.e. pointers that are not yet injected.
*
* @param prototype The prototype from which to create the injected events.
* @param policyFlags The policy flags associated with the event.
*/
private void sendDownForAllNotInjectedPointers(MotionEvent prototype, int policyFlags) {
InjectedPointerTracker injectedPointers = mInjectedPointerTracker;
// Inject the injected pointers.
int pointerIdBits = 0;
final int pointerCount = prototype.getPointerCount();
for (int i = 0; i < pointerCount; i++) {
final int pointerId = prototype.getPointerId(i);
// Do not send event for already delivered pointers.
if (!injectedPointers.isInjectedPointerDown(pointerId)) {
pointerIdBits |= (1 << pointerId);
final int action = computeInjectionAction(MotionEvent.ACTION_DOWN, i);
sendMotionEvent(prototype, action, pointerIdBits, policyFlags);
}
}
}
/**
* Sends the exit events if needed. Such events are hover exit and touch explore
* gesture end.
*
* @param policyFlags The policy flags associated with the event.
*/
private void sendHoverExitAndTouchExplorationGestureEndIfNeeded(int policyFlags) {
MotionEvent event = mInjectedPointerTracker.getLastInjectedHoverEvent();
if (event != null && event.getActionMasked() != MotionEvent.ACTION_HOVER_EXIT) {
final int pointerIdBits = event.getPointerIdBits();
if (!mSendTouchExplorationEndDelayed.isPending()) {
mSendTouchExplorationEndDelayed.post();
}
sendMotionEvent(event, MotionEvent.ACTION_HOVER_EXIT, pointerIdBits, policyFlags);
}
}
/**
* Sends the enter events if needed. Such events are hover enter and touch explore
* gesture start.
*
* @param policyFlags The policy flags associated with the event.
*/
private void sendTouchExplorationGestureStartAndHoverEnterIfNeeded(int policyFlags) {
MotionEvent event = mInjectedPointerTracker.getLastInjectedHoverEvent();
if (event != null && event.getActionMasked() == MotionEvent.ACTION_HOVER_EXIT) {
final int pointerIdBits = event.getPointerIdBits();
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START);
sendMotionEvent(event, MotionEvent.ACTION_HOVER_ENTER, pointerIdBits, policyFlags);
}
}
/**
* Sends up events to the view hierarchy for all pointers which are
* already being delivered i.e. pointers that are injected.
*
* @param prototype The prototype from which to create the injected events.
* @param policyFlags The policy flags associated with the event.
*/
private void sendUpForInjectedDownPointers(MotionEvent prototype, int policyFlags) {
final InjectedPointerTracker injectedTracked = mInjectedPointerTracker;
int pointerIdBits = 0;
final int pointerCount = prototype.getPointerCount();
for (int i = 0; i < pointerCount; i++) {
final int pointerId = prototype.getPointerId(i);
// Skip non injected down pointers.
if (!injectedTracked.isInjectedPointerDown(pointerId)) {
continue;
}
pointerIdBits |= (1 << pointerId);
final int action = computeInjectionAction(MotionEvent.ACTION_UP, i);
sendMotionEvent(prototype, action, pointerIdBits, policyFlags);
}
}
/**
* Sends an up and down events.
*
* @param prototype The prototype from which to create the injected events.
* @param policyFlags The policy flags associated with the event.
*/
private void sendActionDownAndUp(MotionEvent prototype, int policyFlags) {
// Tap with the pointer that last explored.
final int pointerId = prototype.getPointerId(prototype.getActionIndex());
final int pointerIdBits = (1 << pointerId);
sendMotionEvent(prototype, MotionEvent.ACTION_DOWN, pointerIdBits, policyFlags);
sendMotionEvent(prototype, MotionEvent.ACTION_UP, pointerIdBits, policyFlags);
}
/**
* Sends an event.
*
* @param prototype The prototype from which to create the injected events.
* @param action The action of the event.
* @param pointerIdBits The bits of the pointers to send.
* @param policyFlags The policy flags associated with the event.
*/
private void sendMotionEvent(MotionEvent prototype, int action, int pointerIdBits,
int policyFlags) {
prototype.setAction(action);
MotionEvent event = null;
if (pointerIdBits == ALL_POINTER_ID_BITS) {
event = prototype;
} else {
event = prototype.split(pointerIdBits);
}
if (action == MotionEvent.ACTION_DOWN) {
event.setDownTime(event.getEventTime());
} else {
event.setDownTime(mInjectedPointerTracker.getLastInjectedDownEventTime());
}
// If the user is long pressing but the long pressing pointer
// was not exactly over the accessibility focused item we need
// to remap the location of that pointer so the user does not
// have to explicitly touch explore something to be able to
// long press it, or even worse to avoid the user long pressing
// on the wrong item since click and long press behave differently.
if (mLongPressingPointerId >= 0) {
final int remappedIndex = event.findPointerIndex(mLongPressingPointerId);
final int pointerCount = event.getPointerCount();
PointerProperties[] props = PointerProperties.createArray(pointerCount);
PointerCoords[] coords = PointerCoords.createArray(pointerCount);
for (int i = 0; i < pointerCount; i++) {
event.getPointerProperties(i, props[i]);
event.getPointerCoords(i, coords[i]);
if (i == remappedIndex) {
coords[i].x -= mLongPressingPointerDeltaX;
coords[i].y -= mLongPressingPointerDeltaY;
}
}
MotionEvent remapped = MotionEvent.obtain(event.getDownTime(),
event.getEventTime(), event.getAction(), event.getPointerCount(),
props, coords, event.getMetaState(), event.getButtonState(),
1.0f, 1.0f, event.getDeviceId(), event.getEdgeFlags(),
event.getSource(), event.getFlags());
if (event != prototype) {
event.recycle();
}
event = remapped;
}
if (DEBUG) {
Slog.d(LOG_TAG, "Injecting event: " + event + ", policyFlags=0x"
+ Integer.toHexString(policyFlags));
}
// Make sure that the user will see the event.
policyFlags |= WindowManagerPolicy.FLAG_PASS_TO_USER;
if (mNext != null) {
// TODO: For now pass null for the raw event since the touch
// explorer is the last event transformation and it does
// not care about the raw event.
mNext.onMotionEvent(event, null, policyFlags);
}
mInjectedPointerTracker.onMotionEvent(event);
if (event != prototype) {
event.recycle();
}
}
/**
* Computes the action for an injected event based on a masked action
* and a pointer index.
*
* @param actionMasked The masked action.
* @param pointerIndex The index of the pointer which has changed.
* @return The action to be used for injection.
*/
private int computeInjectionAction(int actionMasked, int pointerIndex) {
switch (actionMasked) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
InjectedPointerTracker injectedTracker = mInjectedPointerTracker;
// Compute the action based on how many down pointers are injected.
if (injectedTracker.getInjectedPointerDownCount() == 0) {
return MotionEvent.ACTION_DOWN;
} else {
return (pointerIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT)
| MotionEvent.ACTION_POINTER_DOWN;
}
}
case MotionEvent.ACTION_POINTER_UP: {
InjectedPointerTracker injectedTracker = mInjectedPointerTracker;
// Compute the action based on how many down pointers are injected.
if (injectedTracker.getInjectedPointerDownCount() == 1) {
return MotionEvent.ACTION_UP;
} else {
return (pointerIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT)
| MotionEvent.ACTION_POINTER_UP;
}
}
default:
return actionMasked;
}
}
private class DoubleTapDetector {
private MotionEvent mDownEvent;
private MotionEvent mFirstTapEvent;
public void onMotionEvent(MotionEvent event, int policyFlags) {
final int actionIndex = event.getActionIndex();
final int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
if (mFirstTapEvent != null
&& !GestureUtils.isSamePointerContext(mFirstTapEvent, event)) {
clear();
}
mDownEvent = MotionEvent.obtain(event);
} break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP: {
if (mDownEvent == null) {
return;
}
if (!GestureUtils.isSamePointerContext(mDownEvent, event)) {
clear();
return;
}
if (GestureUtils.isTap(mDownEvent, event, mTapTimeout, mTouchSlop,
actionIndex)) {
if (mFirstTapEvent == null || GestureUtils.isTimedOut(mFirstTapEvent,
event, mDoubleTapTimeout)) {
mFirstTapEvent = MotionEvent.obtain(event);
mDownEvent.recycle();
mDownEvent = null;
return;
}
if (GestureUtils.isMultiTap(mFirstTapEvent, event, mDoubleTapTimeout,
mDoubleTapSlop, actionIndex)) {
onDoubleTap(event, policyFlags);
mFirstTapEvent.recycle();
mFirstTapEvent = null;
mDownEvent.recycle();
mDownEvent = null;
return;
}
mFirstTapEvent.recycle();
mFirstTapEvent = null;
} else {
if (mFirstTapEvent != null) {
mFirstTapEvent.recycle();
mFirstTapEvent = null;
}
}
mDownEvent.recycle();
mDownEvent = null;
} break;
}
}
public void onDoubleTap(MotionEvent secondTapUp, int policyFlags) {
// This should never be called when more than two pointers are down.
if (secondTapUp.getPointerCount() > 2) {
return;
}
// Remove pending event deliveries.
mSendHoverEnterAndMoveDelayed.cancel();
mSendHoverExitDelayed.cancel();
mPerformLongPressDelayed.cancel();
if (mSendTouchExplorationEndDelayed.isPending()) {
mSendTouchExplorationEndDelayed.forceSendAndRemove();
}
if (mSendTouchInteractionEndDelayed.isPending()) {
mSendTouchInteractionEndDelayed.forceSendAndRemove();
}
int clickLocationX;
int clickLocationY;
final int pointerId = secondTapUp.getPointerId(secondTapUp.getActionIndex());
final int pointerIndex = secondTapUp.findPointerIndex(pointerId);
MotionEvent lastExploreEvent =
mInjectedPointerTracker.getLastInjectedHoverEventForClick();
if (lastExploreEvent == null) {
// No last touch explored event but there is accessibility focus in
// the active window. We click in the middle of the focus bounds.
Rect focusBounds = mTempRect;
if (mAms.getAccessibilityFocusBoundsInActiveWindow(focusBounds)) {
clickLocationX = focusBounds.centerX();
clickLocationY = focusBounds.centerY();
} else {
// Out of luck - do nothing.
return;
}
} else {
// If the click is within the active window but not within the
// accessibility focus bounds we click in the focus center.
final int lastExplorePointerIndex = lastExploreEvent.getActionIndex();
clickLocationX = (int) lastExploreEvent.getX(lastExplorePointerIndex);
clickLocationY = (int) lastExploreEvent.getY(lastExplorePointerIndex);
Rect activeWindowBounds = mTempRect;
if (mLastTouchedWindowId == mAms.getActiveWindowId()) {
mAms.getActiveWindowBounds(activeWindowBounds);
if (activeWindowBounds.contains(clickLocationX, clickLocationY)) {
Rect focusBounds = mTempRect;
if (mAms.getAccessibilityFocusBoundsInActiveWindow(focusBounds)) {
if (!focusBounds.contains(clickLocationX, clickLocationY)) {
clickLocationX = focusBounds.centerX();
clickLocationY = focusBounds.centerY();
}
}
}
}
}
// Do the click.
PointerProperties[] properties = new PointerProperties[1];
properties[0] = new PointerProperties();
secondTapUp.getPointerProperties(pointerIndex, properties[0]);
PointerCoords[] coords = new PointerCoords[1];
coords[0] = new PointerCoords();
coords[0].x = clickLocationX;
coords[0].y = clickLocationY;
MotionEvent event = MotionEvent.obtain(secondTapUp.getDownTime(),
secondTapUp.getEventTime(), MotionEvent.ACTION_DOWN, 1, properties,
coords, 0, 0, 1.0f, 1.0f, secondTapUp.getDeviceId(), 0,
secondTapUp.getSource(), secondTapUp.getFlags());
sendActionDownAndUp(event, policyFlags);
event.recycle();
}
public void clear() {
if (mDownEvent != null) {
mDownEvent.recycle();
mDownEvent = null;
}
if (mFirstTapEvent != null) {
mFirstTapEvent.recycle();
mFirstTapEvent = null;
}
}
public boolean firstTapDetected() {
return mFirstTapEvent != null
&& SystemClock.uptimeMillis() - mFirstTapEvent.getEventTime() < mDoubleTapTimeout;
}
}
/**
* Determines whether a two pointer gesture is a dragging one.
*
* @param event The event with the pointer data.
* @return True if the gesture is a dragging one.
*/
private boolean isDraggingGesture(MotionEvent event) {
ReceivedPointerTracker receivedTracker = mReceivedPointerTracker;
final float firstPtrX = event.getX(0);
final float firstPtrY = event.getY(0);
final float secondPtrX = event.getX(1);
final float secondPtrY = event.getY(1);
final float firstPtrDownX = receivedTracker.getReceivedPointerDownX(0);
final float firstPtrDownY = receivedTracker.getReceivedPointerDownY(0);
final float secondPtrDownX = receivedTracker.getReceivedPointerDownX(1);
final float secondPtrDownY = receivedTracker.getReceivedPointerDownY(1);
return GestureUtils.isDraggingGesture(firstPtrDownX, firstPtrDownY, secondPtrDownX,
secondPtrDownY, firstPtrX, firstPtrY, secondPtrX, secondPtrY,
MAX_DRAGGING_ANGLE_COS);
}
/**
* Gets the symbolic name of a state.
*
* @param state A state.
* @return The state symbolic name.
*/
private static String getStateSymbolicName(int state) {
switch (state) {
case STATE_TOUCH_EXPLORING:
return "STATE_TOUCH_EXPLORING";
case STATE_DRAGGING:
return "STATE_DRAGGING";
case STATE_DELEGATING:
return "STATE_DELEGATING";
case STATE_GESTURE_DETECTING:
return "STATE_GESTURE_DETECTING";
default:
throw new IllegalArgumentException("Unknown state: " + state);
}
}
/**
* Class for delayed exiting from gesture detecting mode.
*/
private final class ExitGestureDetectionModeDelayed implements Runnable {
public void post() {
mHandler.postDelayed(this, EXIT_GESTURE_DETECTION_TIMEOUT);
}
public void cancel() {
mHandler.removeCallbacks(this);
}
@Override
public void run() {
// Announce the end of gesture recognition.
sendAccessibilityEvent(AccessibilityEvent.TYPE_GESTURE_DETECTION_END);
// Clearing puts is in touch exploration state with a finger already
// down, so announce the transition to exploration state.
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START);
clear();
}
}
/**
* Class for delayed sending of long press.
*/
private final class PerformLongPressDelayed implements Runnable {
private MotionEvent mEvent;
private int mPolicyFlags;
public void post(MotionEvent prototype, int policyFlags) {
mEvent = MotionEvent.obtain(prototype);
mPolicyFlags = policyFlags;
mHandler.postDelayed(this, ViewConfiguration.getLongPressTimeout());
}
public void cancel() {
if (mEvent != null) {
mHandler.removeCallbacks(this);
clear();
}
}
private boolean isPending() {
return mHandler.hasCallbacks(this);
}
@Override
public void run() {
// Pointers should not be zero when running this command.
if (mReceivedPointerTracker.getLastReceivedEvent().getPointerCount() == 0) {
return;
}
int clickLocationX;
int clickLocationY;
final int pointerId = mEvent.getPointerId(mEvent.getActionIndex());
final int pointerIndex = mEvent.findPointerIndex(pointerId);
MotionEvent lastExploreEvent =
mInjectedPointerTracker.getLastInjectedHoverEventForClick();
if (lastExploreEvent == null) {
// No last touch explored event but there is accessibility focus in
// the active window. We click in the middle of the focus bounds.
Rect focusBounds = mTempRect;
if (mAms.getAccessibilityFocusBoundsInActiveWindow(focusBounds)) {
clickLocationX = focusBounds.centerX();
clickLocationY = focusBounds.centerY();
} else {
// Out of luck - do nothing.
return;
}
} else {
// If the click is within the active window but not within the
// accessibility focus bounds we click in the focus center.
final int lastExplorePointerIndex = lastExploreEvent.getActionIndex();
clickLocationX = (int) lastExploreEvent.getX(lastExplorePointerIndex);
clickLocationY = (int) lastExploreEvent.getY(lastExplorePointerIndex);
Rect activeWindowBounds = mTempRect;
if (mLastTouchedWindowId == mAms.getActiveWindowId()) {
mAms.getActiveWindowBounds(activeWindowBounds);
if (activeWindowBounds.contains(clickLocationX, clickLocationY)) {
Rect focusBounds = mTempRect;
if (mAms.getAccessibilityFocusBoundsInActiveWindow(focusBounds)) {
if (!focusBounds.contains(clickLocationX, clickLocationY)) {
clickLocationX = focusBounds.centerX();
clickLocationY = focusBounds.centerY();
}
}
}
}
}
mLongPressingPointerId = pointerId;
mLongPressingPointerDeltaX = (int) mEvent.getX(pointerIndex) - clickLocationX;
mLongPressingPointerDeltaY = (int) mEvent.getY(pointerIndex) - clickLocationY;
sendHoverExitAndTouchExplorationGestureEndIfNeeded(mPolicyFlags);
mCurrentState = STATE_DELEGATING;
sendDownForAllNotInjectedPointers(mEvent, mPolicyFlags);
clear();
}
private void clear() {
mEvent.recycle();
mEvent = null;
mPolicyFlags = 0;
}
}
/**
* Class for delayed sending of hover enter and move events.
*/
class SendHoverEnterAndMoveDelayed implements Runnable {
private final String LOG_TAG_SEND_HOVER_DELAYED = "SendHoverEnterAndMoveDelayed";
private final List<MotionEvent> mEvents = new ArrayList<MotionEvent>();
private int mPointerIdBits;
private int mPolicyFlags;
public void post(MotionEvent event, boolean touchExplorationInProgress,
int pointerIdBits, int policyFlags) {
cancel();
addEvent(event);
mPointerIdBits = pointerIdBits;
mPolicyFlags = policyFlags;
mHandler.postDelayed(this, mDetermineUserIntentTimeout);
}
public void addEvent(MotionEvent event) {
mEvents.add(MotionEvent.obtain(event));
}
public void cancel() {
if (isPending()) {
mHandler.removeCallbacks(this);
clear();
}
}
private boolean isPending() {
return mHandler.hasCallbacks(this);
}
private void clear() {
mPointerIdBits = -1;
mPolicyFlags = 0;
final int eventCount = mEvents.size();
for (int i = eventCount - 1; i >= 0; i--) {
mEvents.remove(i).recycle();
}
}
public void forceSendAndRemove() {
if (isPending()) {
run();
cancel();
}
}
public void run() {
// Send an accessibility event to announce the touch exploration start.
sendAccessibilityEvent(AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START);
if (!mEvents.isEmpty()) {
// Deliver a down event.
sendMotionEvent(mEvents.get(0), MotionEvent.ACTION_HOVER_ENTER,
mPointerIdBits, mPolicyFlags);
if (DEBUG) {
Slog.d(LOG_TAG_SEND_HOVER_DELAYED,
"Injecting motion event: ACTION_HOVER_ENTER");
}
// Deliver move events.
final int eventCount = mEvents.size();
for (int i = 1; i < eventCount; i++) {
sendMotionEvent(mEvents.get(i), MotionEvent.ACTION_HOVER_MOVE,
mPointerIdBits, mPolicyFlags);
if (DEBUG) {
Slog.d(LOG_TAG_SEND_HOVER_DELAYED,
"Injecting motion event: ACTION_HOVER_MOVE");
}
}
}
clear();
}
}
/**
* Class for delayed sending of hover exit events.
*/
class SendHoverExitDelayed implements Runnable {
private final String LOG_TAG_SEND_HOVER_DELAYED = "SendHoverExitDelayed";
private MotionEvent mPrototype;
private int mPointerIdBits;
private int mPolicyFlags;
public void post(MotionEvent prototype, int pointerIdBits, int policyFlags) {
cancel();
mPrototype = MotionEvent.obtain(prototype);
mPointerIdBits = pointerIdBits;
mPolicyFlags = policyFlags;
mHandler.postDelayed(this, mDetermineUserIntentTimeout);
}
public void cancel() {
if (isPending()) {
mHandler.removeCallbacks(this);
clear();
}
}
private boolean isPending() {
return mHandler.hasCallbacks(this);
}
private void clear() {
mPrototype.recycle();
mPrototype = null;
mPointerIdBits = -1;
mPolicyFlags = 0;
}
public void forceSendAndRemove() {
if (isPending()) {
run();
cancel();
}
}
public void run() {
if (DEBUG) {
Slog.d(LOG_TAG_SEND_HOVER_DELAYED, "Injecting motion event:"
+ " ACTION_HOVER_EXIT");
}
sendMotionEvent(mPrototype, MotionEvent.ACTION_HOVER_EXIT,
mPointerIdBits, mPolicyFlags);
if (!mSendTouchExplorationEndDelayed.isPending()) {
mSendTouchExplorationEndDelayed.cancel();
mSendTouchExplorationEndDelayed.post();
}
if (mSendTouchInteractionEndDelayed.isPending()) {
mSendTouchInteractionEndDelayed.cancel();
mSendTouchInteractionEndDelayed.post();
}
clear();
}
}
private class SendAccessibilityEventDelayed implements Runnable {
private final int mEventType;
private final int mDelay;
public SendAccessibilityEventDelayed(int eventType, int delay) {
mEventType = eventType;
mDelay = delay;
}
public void cancel() {
mHandler.removeCallbacks(this);
}
public void post() {
mHandler.postDelayed(this, mDelay);
}
public boolean isPending() {
return mHandler.hasCallbacks(this);
}
public void forceSendAndRemove() {
if (isPending()) {
run();
cancel();
}
}
@Override
public void run() {
sendAccessibilityEvent(mEventType);
}
}
@Override
public String toString() {
return LOG_TAG;
}
class InjectedPointerTracker {
private static final String LOG_TAG_INJECTED_POINTER_TRACKER = "InjectedPointerTracker";
// Keep track of which pointers sent to the system are down.
private int mInjectedPointersDown;
// The time of the last injected down.
private long mLastInjectedDownEventTime;
// The last injected hover event.
private MotionEvent mLastInjectedHoverEvent;
// The last injected hover event used for performing clicks.
private MotionEvent mLastInjectedHoverEventForClick;
/**
* Processes an injected {@link MotionEvent} event.
*
* @param event The event to process.
*/
public void onMotionEvent(MotionEvent event) {
final int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
final int pointerId = event.getPointerId(event.getActionIndex());
final int pointerFlag = (1 << pointerId);
mInjectedPointersDown |= pointerFlag;
mLastInjectedDownEventTime = event.getDownTime();
} break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP: {
final int pointerId = event.getPointerId(event.getActionIndex());
final int pointerFlag = (1 << pointerId);
mInjectedPointersDown &= ~pointerFlag;
if (mInjectedPointersDown == 0) {
mLastInjectedDownEventTime = 0;
}
} break;
case MotionEvent.ACTION_HOVER_ENTER:
case MotionEvent.ACTION_HOVER_MOVE:
case MotionEvent.ACTION_HOVER_EXIT: {
if (mLastInjectedHoverEvent != null) {
mLastInjectedHoverEvent.recycle();
}
mLastInjectedHoverEvent = MotionEvent.obtain(event);
if (mLastInjectedHoverEventForClick != null) {
mLastInjectedHoverEventForClick.recycle();
}
mLastInjectedHoverEventForClick = MotionEvent.obtain(event);
} break;
}
if (DEBUG) {
Slog.i(LOG_TAG_INJECTED_POINTER_TRACKER, "Injected pointer:\n" + toString());
}
}
/**
* Clears the internals state.
*/
public void clear() {
mInjectedPointersDown = 0;
}
/**
* @return The time of the last injected down event.
*/
public long getLastInjectedDownEventTime() {
return mLastInjectedDownEventTime;
}
/**
* @return The number of down pointers injected to the view hierarchy.
*/
public int getInjectedPointerDownCount() {
return Integer.bitCount(mInjectedPointersDown);
}
/**
* @return The bits of the injected pointers that are down.
*/
public int getInjectedPointersDown() {
return mInjectedPointersDown;
}
/**
* Whether an injected pointer is down.
*
* @param pointerId The unique pointer id.
* @return True if the pointer is down.
*/
public boolean isInjectedPointerDown(int pointerId) {
final int pointerFlag = (1 << pointerId);
return (mInjectedPointersDown & pointerFlag) != 0;
}
/**
* @return The the last injected hover event.
*/
public MotionEvent getLastInjectedHoverEvent() {
return mLastInjectedHoverEvent;
}
/**
* @return The the last injected hover event.
*/
public MotionEvent getLastInjectedHoverEventForClick() {
return mLastInjectedHoverEventForClick;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("=========================");
builder.append("\nDown pointers #");
builder.append(Integer.bitCount(mInjectedPointersDown));
builder.append(" [ ");
for (int i = 0; i < MAX_POINTER_COUNT; i++) {
if ((mInjectedPointersDown & i) != 0) {
builder.append(i);
builder.append(" ");
}
}
builder.append("]");
builder.append("\n=========================");
return builder.toString();
}
}
class ReceivedPointerTracker {
private static final String LOG_TAG_RECEIVED_POINTER_TRACKER = "ReceivedPointerTracker";
// Keep track of where and when a pointer went down.
private final float[] mReceivedPointerDownX = new float[MAX_POINTER_COUNT];
private final float[] mReceivedPointerDownY = new float[MAX_POINTER_COUNT];
private final long[] mReceivedPointerDownTime = new long[MAX_POINTER_COUNT];
// Which pointers are down.
private int mReceivedPointersDown;
// The edge flags of the last received down event.
private int mLastReceivedDownEdgeFlags;
// Primary pointer which is either the first that went down
// or if it goes up the next one that most recently went down.
private int mPrimaryPointerId;
// Keep track of the last up pointer data.
private long mLastReceivedUpPointerDownTime;
private int mLastReceivedUpPointerId;
private float mLastReceivedUpPointerDownX;
private float mLastReceivedUpPointerDownY;
private MotionEvent mLastReceivedEvent;
/**
* Clears the internals state.
*/
public void clear() {
Arrays.fill(mReceivedPointerDownX, 0);
Arrays.fill(mReceivedPointerDownY, 0);
Arrays.fill(mReceivedPointerDownTime, 0);
mReceivedPointersDown = 0;
mPrimaryPointerId = 0;
mLastReceivedUpPointerDownTime = 0;
mLastReceivedUpPointerId = 0;
mLastReceivedUpPointerDownX = 0;
mLastReceivedUpPointerDownY = 0;
}
/**
* Processes a received {@link MotionEvent} event.
*
* @param event The event to process.
*/
public void onMotionEvent(MotionEvent event) {
if (mLastReceivedEvent != null) {
mLastReceivedEvent.recycle();
}
mLastReceivedEvent = MotionEvent.obtain(event);
final int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN: {
handleReceivedPointerDown(event.getActionIndex(), event);
} break;
case MotionEvent.ACTION_POINTER_DOWN: {
handleReceivedPointerDown(event.getActionIndex(), event);
} break;
case MotionEvent.ACTION_UP: {
handleReceivedPointerUp(event.getActionIndex(), event);
} break;
case MotionEvent.ACTION_POINTER_UP: {
handleReceivedPointerUp(event.getActionIndex(), event);
} break;
}
if (DEBUG) {
Slog.i(LOG_TAG_RECEIVED_POINTER_TRACKER, "Received pointer:\n" + toString());
}
}
/**
* @return The last received event.
*/
public MotionEvent getLastReceivedEvent() {
return mLastReceivedEvent;
}
/**
* @return The number of received pointers that are down.
*/
public int getReceivedPointerDownCount() {
return Integer.bitCount(mReceivedPointersDown);
}
/**
* Whether an received pointer is down.
*
* @param pointerId The unique pointer id.
* @return True if the pointer is down.
*/
public boolean isReceivedPointerDown(int pointerId) {
final int pointerFlag = (1 << pointerId);
return (mReceivedPointersDown & pointerFlag) != 0;
}
/**
* @param pointerId The unique pointer id.
* @return The X coordinate where the pointer went down.
*/
public float getReceivedPointerDownX(int pointerId) {
return mReceivedPointerDownX[pointerId];
}
/**
* @param pointerId The unique pointer id.
* @return The Y coordinate where the pointer went down.
*/
public float getReceivedPointerDownY(int pointerId) {
return mReceivedPointerDownY[pointerId];
}
/**
* @param pointerId The unique pointer id.
* @return The time when the pointer went down.
*/
public long getReceivedPointerDownTime(int pointerId) {
return mReceivedPointerDownTime[pointerId];
}
/**
* @return The id of the primary pointer.
*/
public int getPrimaryPointerId() {
if (mPrimaryPointerId == INVALID_POINTER_ID) {
mPrimaryPointerId = findPrimaryPointerId();
}
return mPrimaryPointerId;
}
/**
* @return The time when the last up received pointer went down.
*/
public long getLastReceivedUpPointerDownTime() {
return mLastReceivedUpPointerDownTime;
}
/**
* @return The down X of the last received pointer that went up.
*/
public float getLastReceivedUpPointerDownX() {
return mLastReceivedUpPointerDownX;
}
/**
* @return The down Y of the last received pointer that went up.
*/
public float getLastReceivedUpPointerDownY() {
return mLastReceivedUpPointerDownY;
}
/**
* @return The edge flags of the last received down event.
*/
public int getLastReceivedDownEdgeFlags() {
return mLastReceivedDownEdgeFlags;
}
/**
* Handles a received pointer down event.
*
* @param pointerIndex The index of the pointer that has changed.
* @param event The event to be handled.
*/
private void handleReceivedPointerDown(int pointerIndex, MotionEvent event) {
final int pointerId = event.getPointerId(pointerIndex);
final int pointerFlag = (1 << pointerId);
mLastReceivedUpPointerId = 0;
mLastReceivedUpPointerDownTime = 0;
mLastReceivedUpPointerDownX = 0;
mLastReceivedUpPointerDownX = 0;
mLastReceivedDownEdgeFlags = event.getEdgeFlags();
mReceivedPointersDown |= pointerFlag;
mReceivedPointerDownX[pointerId] = event.getX(pointerIndex);
mReceivedPointerDownY[pointerId] = event.getY(pointerIndex);
mReceivedPointerDownTime[pointerId] = event.getEventTime();
mPrimaryPointerId = pointerId;
}
/**
* Handles a received pointer up event.
*
* @param pointerIndex The index of the pointer that has changed.
* @param event The event to be handled.
*/
private void handleReceivedPointerUp(int pointerIndex, MotionEvent event) {
final int pointerId = event.getPointerId(pointerIndex);
final int pointerFlag = (1 << pointerId);
mLastReceivedUpPointerId = pointerId;
mLastReceivedUpPointerDownTime = getReceivedPointerDownTime(pointerId);
mLastReceivedUpPointerDownX = mReceivedPointerDownX[pointerId];
mLastReceivedUpPointerDownY = mReceivedPointerDownY[pointerId];
mReceivedPointersDown &= ~pointerFlag;
mReceivedPointerDownX[pointerId] = 0;
mReceivedPointerDownY[pointerId] = 0;
mReceivedPointerDownTime[pointerId] = 0;
if (mPrimaryPointerId == pointerId) {
mPrimaryPointerId = INVALID_POINTER_ID;
}
}
/**
* @return The primary pointer id.
*/
private int findPrimaryPointerId() {
int primaryPointerId = INVALID_POINTER_ID;
long minDownTime = Long.MAX_VALUE;
// Find the pointer that went down first.
int pointerIdBits = mReceivedPointersDown;
while (pointerIdBits > 0) {
final int pointerId = Integer.numberOfTrailingZeros(pointerIdBits);
pointerIdBits &= ~(1 << pointerId);
final long downPointerTime = mReceivedPointerDownTime[pointerId];
if (downPointerTime < minDownTime) {
minDownTime = downPointerTime;
primaryPointerId = pointerId;
}
}
return primaryPointerId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("=========================");
builder.append("\nDown pointers #");
builder.append(getReceivedPointerDownCount());
builder.append(" [ ");
for (int i = 0; i < MAX_POINTER_COUNT; i++) {
if (isReceivedPointerDown(i)) {
builder.append(i);
builder.append(" ");
}
}
builder.append("]");
builder.append("\nPrimary pointer id [ ");
builder.append(getPrimaryPointerId());
builder.append(" ]");
builder.append("\n=========================");
return builder.toString();
}
}
}
|
indashnet/InDashNet.Open.UN2000
|
android/frameworks/base/services/java/com/android/server/accessibility/TouchExplorer.java
|
Java
|
apache-2.0
| 81,944 |
/*
* Copyright 2014-2019 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.redshift.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Describes the members of a VPC security group.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/VpcSecurityGroupMembership"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class VpcSecurityGroupMembership implements Serializable, Cloneable {
/**
* <p>
* The identifier of the VPC security group.
* </p>
*/
private String vpcSecurityGroupId;
/**
* <p>
* The status of the VPC security group.
* </p>
*/
private String status;
/**
* <p>
* The identifier of the VPC security group.
* </p>
*
* @param vpcSecurityGroupId
* The identifier of the VPC security group.
*/
public void setVpcSecurityGroupId(String vpcSecurityGroupId) {
this.vpcSecurityGroupId = vpcSecurityGroupId;
}
/**
* <p>
* The identifier of the VPC security group.
* </p>
*
* @return The identifier of the VPC security group.
*/
public String getVpcSecurityGroupId() {
return this.vpcSecurityGroupId;
}
/**
* <p>
* The identifier of the VPC security group.
* </p>
*
* @param vpcSecurityGroupId
* The identifier of the VPC security group.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VpcSecurityGroupMembership withVpcSecurityGroupId(String vpcSecurityGroupId) {
setVpcSecurityGroupId(vpcSecurityGroupId);
return this;
}
/**
* <p>
* The status of the VPC security group.
* </p>
*
* @param status
* The status of the VPC security group.
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* The status of the VPC security group.
* </p>
*
* @return The status of the VPC security group.
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* The status of the VPC security group.
* </p>
*
* @param status
* The status of the VPC security group.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VpcSecurityGroupMembership withStatus(String status) {
setStatus(status);
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 (getVpcSecurityGroupId() != null)
sb.append("VpcSecurityGroupId: ").append(getVpcSecurityGroupId()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof VpcSecurityGroupMembership == false)
return false;
VpcSecurityGroupMembership other = (VpcSecurityGroupMembership) obj;
if (other.getVpcSecurityGroupId() == null ^ this.getVpcSecurityGroupId() == null)
return false;
if (other.getVpcSecurityGroupId() != null && other.getVpcSecurityGroupId().equals(this.getVpcSecurityGroupId()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getVpcSecurityGroupId() == null) ? 0 : getVpcSecurityGroupId().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
return hashCode;
}
@Override
public VpcSecurityGroupMembership clone() {
try {
return (VpcSecurityGroupMembership) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
jentfoo/aws-sdk-java
|
aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/VpcSecurityGroupMembership.java
|
Java
|
apache-2.0
| 5,374 |
<?php namespace DMA\Friends\API\Resources;
use Response;
use Request;
use Validator;
use DMA\Friends\Models\Rating;
use DMA\Friends\Models\Activity;
use DMA\Friends\Classes\API\BaseResource;
use DMA\Friends\API\Transformers\UserProfileTransformer;
use RainLab\User\Models\User;
class RatingResource extends BaseResource {
protected $model = '\DMA\Friends\Models\Rating';
protected $transformer = '\DMA\Friends\API\Transformers\RatingTransformer';
public function __construct()
{
// Add additional routes to Activity resource
$this->addAdditionalRoute('ratingsByObject', '{object}/{objectId}', ['GET']);
$this->addAdditionalRoute('addObjectRateJson', 'rate/{object}/', ['POST']);
$this->addAdditionalRoute('addObjectRating', 'rate/{object}/{objectId}/user/{user}/{rate}', ['GET']);
}
/**
* Get instance of the object
* @param string $objectType
* @param string $objectId
* @return mixed
*/
protected function getObject($objectType, $objectId)
{
$registry = [
'activity' => '\DMA\Friends\Models\Activity',
'badge' => '\DMA\Friends\Models\Badge',
];
$model = array_get($registry, $objectType);
if ($model){
return call_user_func_array("{$model}::find", [$objectId]);
}else{
$options = implode(', ', array_keys($registry));
throw new \Exception("$objectType is not register as rateable. Options are $options");
}
}
/**
* @SWG\GET(
* path="ratings/{object}/{objectId}",
* description="Get all object ratings",
* tags={ "ratings"},
*
* @SWG\Parameter(
* description="Object",
* in="path",
* name="object",
* required=true,
* type="string",
* enum={"activity", "badge"}
* ),
* @SWG\Parameter(
* description="ID of object to fetch",
* format="int64",
* in="path",
* name="objectId",
* required=true,
* type="integer"
* ),
* @SWG\Response(
* response=200,
* description="Successful response",
* @SWG\Schema(ref="#/definitions/rate")
* ),
* @SWG\Response(
* response=500,
* description="Unexpected error",
* @SWG\Schema(ref="#/definitions/error500")
* ),
* @SWG\Response(
* response=404,
* description="User not found",
* @SWG\Schema(ref="#/definitions/UserError404")
* )
* )
*/
/**
* Get ratings by object
* @param string $objectType
* @param int $objectId
*/
public function ratingsByObject($objectType, $objectId)
{
if($instance = $this->getObject($objectType, $objectId)){
$pageSize = $this->getPageSize();
$paginator = $instance->getRates()->paginate($pageSize);
$meta = [
'rating' => array_merge(
$instance->getRatingStats(),
[
'object_type' => $objectType,
'object_id' => intval($objectId)
]
)
];
$transformer = new \DMA\Friends\API\Transformers\RateTransformer;
return Response::api()->withPaginator($paginator, $transformer, null, $meta);
} else {
return Response::api()->errorNotFound("$objectType not found");
}
}
/**
* @SWG\Definition(
* definition="response.rate",
* required={"data"},
* @SWG\Property(
* property="data",
* type="object",
* ref="#/definitions/rate.payload"
* )
* )
*
* @SWG\Definition(
* definition="rate.payload",
* required={"success", "message", "user", "rating"},
* @SWG\Property(
* property="success",
* type="boolean"
* ),
* @SWG\Property(
* property="message",
* type="string"
* ),
* @SWG\Property(
* property="user",
* type="object",
* ref="#/definitions/user.info.points"
* ),
* @SWG\Property(
* property="rating",
* type="object",
* ref="#/definitions/rating.stats"
* )
* )
*
* @SWG\Definition(
* definition="rating.stats",
* required={"total", "average", "object_type", "object_id"},
* @SWG\Property(
* property="total",
* type="number",
* format="float"
* ),
* @SWG\Property(
* property="average",
* type="number",
* format="float"
* ),
* @SWG\Property(
* property="object_type",
* type="string"
* ),
* @SWG\Property(
* property="object_id",
* type="integer",
* format="int32"
* )
* )
*
*
* @SWG\GET(
* path="ratings/rate/{object}/{objectId}/user/{user}/{rate}",
* description="Get all object ratings",
* tags={ "ratings"},
*
* @SWG\Parameter(
* description="Object to rate",
* in="path",
* name="object",
* required=true,
* type="string",
* enum={"activity", "badge"}
* ),
* @SWG\Parameter(
* description="ID of object to rate",
* format="int64",
* in="path",
* name="objectId",
* required=true,
* type="integer"
* ),
* @SWG\Parameter(
* description="ID of user",
* format="int64",
* in="path",
* name="user",
* required=true,
* type="integer"
* ),
* @SWG\Parameter(
* description="Rate value",
* format="float",
* in="path",
* name="rate",
* required=true,
* type="number",
* minimum=1,
* maximum=5
* ),
* @SWG\Response(
* response=200,
* description="Successful response",
* @SWG\Schema(ref="#/definitions/response.rate")
* ),
* @SWG\Response(
* response=500,
* description="Unexpected error",
* @SWG\Schema(ref="#/definitions/error500")
* ),
* @SWG\Response(
* response=404,
* description="User not found",
* @SWG\Schema(ref="#/definitions/UserError404")
* )
* )
*/
public function addObjectRating($objectType, $objectId, $user, $rateValue, $comment = null)
{
if($user = User::find($user)){
if($instance = $this->getObject($objectType, $objectId)){
list($success, $rating) = $instance->addRating($user, $rateValue, $comment);
// Get common user points format via UserProfileTransformer
$userTransformer = new UserProfileTransformer();
$points = $userTransformer->getUserPoints($user);
$payload = [
'data' => [
'success' => $success,
'message' => "$objectType has been rate succesfully.",
'user' => [
'id' => $user->getKey(),
'points' => $points
],
'rating' => array_merge(
$instance->getRatingStats(),
[
'object_type' => $objectType,
'object_id' => intVal($objectId)
]
)
]
];
$httpCode = 201;
if( !$success ) {
$httpCode = 200;
$payload['data']['message'] = "User has already rate this $objectType";
}
return Response::api()->setStatusCode($httpCode)->withArray($payload);
} else {
return Response::api()->errorNotFound("$object not found");
}
}else{
return Response::api()->errorNotFound('User not found');
}
}
/**
* @SWG\Definition(
* definition="request.rate",
* required={"id", "rate", "user_id"},
* @SWG\Property(
* property="id",
* type="integer",
* format="int32"
* ),
* @SWG\Property(
* property="rate",
* type="number",
* format="float"
* ),
* @SWG\Property(
* property="user_id",
* type="integer",
* format="int32"
* )
* )
*
*
* @SWG\Post(
* path="ratings/rate/{object}/",
* description="Get all object ratings",
* tags={ "ratings"},
*
* @SWG\Parameter(
* description="Object to rate",
* in="path",
* name="object",
* required=true,
* type="string",
* enum={"activity", "badge"}
* ),
* @SWG\Parameter(
* in="body",
* name="body",
* required=true,
* type="object",
* schema=@SWG\Schema(ref="#/definitions/request.rate")
* ),
* @SWG\Response(
* response=200,
* description="Successful response",
* @SWG\Schema(ref="#/definitions/response.rate")
* ),
* @SWG\Response(
* response=500,
* description="Unexpected error",
* @SWG\Schema(ref="#/definitions/error500")
* ),
* @SWG\Response(
* response=404,
* description="User not found",
* @SWG\Schema(ref="#/definitions/UserError404")
* )
* )
*/
public function addObjectRateJson($objectType){
$data = Request::all();
$rules = [
'id' => "required",
'rate' => "required",
'user_id' => "required"
];
$validation = Validator::make($data, $rules);
if ($validation->fails()){
return $this->errorDataValidation('rate data fails to validated', $validation->errors());
}
$comment = array_get($data, 'comment', '');
return $this->addObjectRating($objectType, $data['id'], $data['user_id'], $data['rate'], $comment);
}
public function index()
{
# TODO : stop default behaviour of the base resource and
# return and error
return Response::api()->errorForbidden();
#return parent::index();
}
/**
* @SWG\Get(
* path="ratings/{id}",
* description="Returns an rating by id",
* tags={ "ratings"},
*
* @SWG\Parameter(
* description="ID of rating to fetch",
* format="int64",
* in="path",
* name="id",
* required=true,
* type="integer"
* ),
*
* @SWG\Response(
* response=200,
* description="Successful response",
* @SWG\Schema(ref="#/definitions/rate")
* ),
* @SWG\Response(
* response=500,
* description="Unexpected error",
* @SWG\Schema(ref="#/definitions/error500")
* ),
* @SWG\Response(
* response=404,
* description="Not Found",
* @SWG\Schema(ref="#/definitions/error404")
* )
* )
*/
public function show($id)
{
return parent::show($id);
}
}
|
DenverArtMuseum/OctoberFriends
|
api/resources/RatingResource.php
|
PHP
|
apache-2.0
| 12,864 |
/*
* Copyright (c) 2013 Mike Heath. 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 nats.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import nats.NatsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
/**
* Encodes {@link ServerFrame} objects to binary to be sent over the network.
*
* @author Mike Heath
*/
public class ServerFrameEncoder extends MessageToByteEncoder<ServerFrame> {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerFrameEncoder.class);
private static final Charset UTF8 = Charset.forName("utf-8");
public static final byte[] CMD_PUB = "MSG".getBytes(UTF8);
public static final byte[] CMD_ERR = "-ERR".getBytes(UTF8);
public static final byte[] CMD_INFO = "INFO".getBytes(UTF8);
public static final byte[] OK = "+OK\r\n".getBytes(UTF8);
public static final byte[] PING = "PING\r\n".getBytes(UTF8);
public static final byte[] PONG = "PONG\r\n".getBytes(UTF8);
@Override
public void encode(ChannelHandlerContext ctx, ServerFrame frame, ByteBuf out) throws Exception {
LOGGER.trace("Encoding {}", frame);
if (frame instanceof ServerPublishFrame) {
final ServerPublishFrame publishFrame = (ServerPublishFrame) frame;
out.writeBytes(CMD_PUB);
out.writeByte(' ');
out.writeBytes(publishFrame.getSubject().getBytes(UTF8));
out.writeByte(' ');
out.writeBytes(publishFrame.getId().getBytes(UTF8));
out.writeByte(' ');
final String replyTo = publishFrame.getReplyTo();
if (replyTo != null) {
out.writeBytes(replyTo.getBytes(UTF8));
out.writeByte(' ');
}
final byte[] bodyBytes = publishFrame.getBody().getBytes(UTF8);
ByteBufUtil.writeIntegerAsString(out, bodyBytes.length);
out.writeBytes(ByteBufUtil.CRLF);
out.writeBytes(bodyBytes);
out.writeBytes(ByteBufUtil.CRLF);
} else if (frame instanceof ServerErrorFrame) {
final ServerErrorFrame message = (ServerErrorFrame) frame;
final String errorMessage = message.getErrorMessage();
out.writeBytes(CMD_ERR);
if (errorMessage != null) {
out.writeByte(' ');
out.writeBytes(errorMessage.getBytes(UTF8));
}
out.writeBytes(ByteBufUtil.CRLF);
} else if (frame instanceof ServerInfoFrame) {
final ServerInfoFrame infoFrame = (ServerInfoFrame) frame;
out.writeBytes(CMD_INFO);
out.writeByte(' ');
out.writeBytes(infoFrame.getInfo().getBytes(UTF8));
out.writeBytes(ByteBufUtil.CRLF);
} else if (frame instanceof ServerOkFrame) {
out.writeBytes(OK);
} else if (frame instanceof ServerPingFrame) {
out.writeBytes(PING);
} else if (frame instanceof ServerPongFrame) {
out.writeBytes(PONG);
} else {
throw new NatsException("Unable to encode server of type " + frame.getClass().getName());
}
}
}
|
cloudfoundry-community/java-nats
|
client/src/main/java/nats/codec/ServerFrameEncoder.java
|
Java
|
apache-2.0
| 3,415 |