text
stringlengths 7
1.01M
|
|---|
/*
* Copyright 2020, EnMasse authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.enmasse.systemtest.sharedinfra;
import io.enmasse.api.model.MessagingAddress;
import io.enmasse.api.model.MessagingAddressBuilder;
import io.enmasse.api.model.MessagingEndpoint;
import io.enmasse.api.model.MessagingEndpointBuilder;
import io.enmasse.api.model.MessagingInfrastructure;
import io.enmasse.api.model.MessagingInfrastructureBuilder;
import io.enmasse.api.model.MessagingInfrastructureCondition;
import io.enmasse.api.model.MessagingTenant;
import io.enmasse.systemtest.TestTag;
import io.enmasse.systemtest.annotations.DefaultMessagingInfrastructure;
import io.enmasse.systemtest.annotations.DefaultMessagingTenant;
import io.enmasse.systemtest.annotations.ExternalClients;
import io.enmasse.systemtest.bases.TestBase;
import io.enmasse.systemtest.bases.isolated.ITestIsolatedSharedInfra;
import io.enmasse.systemtest.messaginginfra.resources.MessagingInfrastructureResourceType;
import io.enmasse.systemtest.time.TimeoutBudget;
import io.enmasse.systemtest.utils.TestUtils;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Tag(TestTag.ISOLATED_SHARED_INFRA)
public class MessagingInfrastructureTest extends TestBase implements ITestIsolatedSharedInfra {
/**
* Test that infrastructure static scaling strategy can be changed and that change is reflected
* in the underlying pods.
*/
@Test
public void testInfraStaticScalingStrategy() throws Exception {
MessagingInfrastructure infra = new MessagingInfrastructureBuilder()
.withNewMetadata()
.withName("default-infra")
.withNamespace(environment.namespace())
.endMetadata()
.withNewSpec()
.endSpec()
.build();
infraResourceManager.createResource(infra);
waitForConditionsTrue(infra);
assertEquals(1, kubernetes.listPods(infra.getMetadata().getNamespace(), Map.of("component", "router")).size());
assertEquals(1, kubernetes.listPods(infra.getMetadata().getNamespace(), Map.of("component", "broker")).size());
// Scale up
infra = new MessagingInfrastructureBuilder(infra)
.editOrNewSpec()
.editOrNewRouter()
.editOrNewScalingStrategy()
.editOrNewStatic()
.withReplicas(3)
.endStatic()
.endScalingStrategy()
.endRouter()
.editOrNewBroker()
.editOrNewScalingStrategy()
.editOrNewStatic()
.withPoolSize(2)
.endStatic()
.endScalingStrategy()
.endBroker()
.endSpec()
.build();
infraResourceManager.createResource(infra);
assertTrue(infraResourceManager.waitResourceCondition(infra, i -> i.getStatus() != null && i.getStatus().getBrokers() != null && i.getStatus().getBrokers().size() == 2));
assertTrue(infraResourceManager.waitResourceCondition(infra, i -> i.getStatus() != null && i.getStatus().getRouters() != null && i.getStatus().getRouters().size() == 3));
waitForConditionsTrue(infra);
// Ensure that we can find the pods as the above conditions are true
assertEquals(3, kubernetes.listPods(infra.getMetadata().getNamespace(), Map.of("component", "router")).size());
assertEquals(2, kubernetes.listPods(infra.getMetadata().getNamespace(), Map.of("component", "broker")).size());
// Scale down
infra = new MessagingInfrastructureBuilder(infra)
.editOrNewSpec()
.editOrNewRouter()
.editOrNewScalingStrategy()
.editOrNewStatic()
.withReplicas(2)
.endStatic()
.endScalingStrategy()
.endRouter()
.editOrNewBroker()
.editOrNewScalingStrategy()
.editOrNewStatic()
.withPoolSize(1)
.endStatic()
.endScalingStrategy()
.endBroker()
.endSpec()
.build();
infraResourceManager.createResource(infra);
assertTrue(infraResourceManager.waitResourceCondition(infra, i -> i.getStatus() != null && i.getStatus().getBrokers() != null && i.getStatus().getBrokers().size() == 1));
assertTrue(infraResourceManager.waitResourceCondition(infra, i -> i.getStatus() != null && i.getStatus().getRouters() != null && i.getStatus().getRouters().size() == 2));
waitForConditionsTrue(infra);
// Conditions are not set to false when scaling down, so we must wait for replicas
TestUtils.waitForNReplicas(2, infra.getMetadata().getNamespace(), Map.of("component", "router"), Collections.emptyMap(), TimeoutBudget.ofDuration(Duration.ofMinutes(5)));
TestUtils.waitForNReplicas(1, infra.getMetadata().getNamespace(), Map.of("component", "broker"), Collections.emptyMap(), TimeoutBudget.ofDuration(Duration.ofMinutes(5)));
}
/**
* Test that the pods in the messaging infrastructure can be restarted, and that they are reconfigured to support
* existing addresses and endpoints.
*/
@Test
@ExternalClients
@DefaultMessagingInfrastructure
@DefaultMessagingTenant
public void testInfraRestart() throws Exception {
MessagingTenant tenant = infraResourceManager.getDefaultMessagingTenant();
MessagingAddress queue = new MessagingAddressBuilder()
.editOrNewMetadata()
.withNamespace(tenant.getMetadata().getNamespace())
.withName("queue1")
.endMetadata()
.editOrNewSpec()
.editOrNewQueue()
.endQueue()
.endSpec()
.build();
MessagingAddress anycast = new MessagingAddressBuilder()
.editOrNewMetadata()
.withNamespace(tenant.getMetadata().getNamespace())
.withName("anycast1")
.endMetadata()
.editOrNewSpec()
.editOrNewAnycast()
.endAnycast()
.endSpec()
.build();
MessagingEndpoint endpoint = new MessagingEndpointBuilder()
.editOrNewMetadata()
.withNamespace(tenant.getMetadata().getNamespace())
.withName("app")
.endMetadata()
.editOrNewSpec()
.addToProtocols("AMQP")
.editOrNewCluster()
.endCluster()
.endSpec()
.build();
infraResourceManager.createResource(endpoint, anycast, queue);
// Make sure endpoints work first
LOGGER.info("Running initial client check");
MessagingEndpointTest.doTestSendReceiveOnCluster(endpoint.getStatus().getHost(), endpoint.getStatus().getPorts().get(0).getPort(), anycast.getMetadata().getName(), false, false);
MessagingEndpointTest.doTestSendReceiveOnCluster(endpoint.getStatus().getHost(), endpoint.getStatus().getPorts().get(0).getPort(), queue.getMetadata().getName(), false, false);
// Restart router and broker pods
MessagingInfrastructure defaultInfra = infraResourceManager.getDefaultInfra();
kubernetes.deletePod(defaultInfra.getMetadata().getNamespace(), Collections.singletonMap("infra", defaultInfra.getMetadata().getName()));
Thread.sleep(60_000);
// Wait for the operator state to be green again.
assertTrue(infraResourceManager.waitResourceCondition(defaultInfra, i -> i.getStatus() != null && i.getStatus().getBrokers() != null && i.getStatus().getBrokers().size() == 1));
assertTrue(infraResourceManager.waitResourceCondition(defaultInfra, i -> i.getStatus() != null && i.getStatus().getRouters() != null && i.getStatus().getRouters().size() == 1));
waitForConditionsTrue(defaultInfra);
MessagingEndpointTest.doTestSendReceiveOnCluster(endpoint.getStatus().getHost(), endpoint.getStatus().getPorts().get(0).getPort(), anycast.getMetadata().getName(), false, false);
MessagingEndpointTest.doTestSendReceiveOnCluster(endpoint.getStatus().getHost(), endpoint.getStatus().getPorts().get(0).getPort(), queue.getMetadata().getName(), false, false);
}
private void waitForConditionsTrue(MessagingInfrastructure infra) {
for (String condition : List.of("CaCreated", "RoutersCreated", "BrokersCreated", "BrokersConnected", "Ready")) {
waitForCondition(infra, condition, "True");
}
}
private void waitForCondition(MessagingInfrastructure infra, String conditionName, String expectedValue) {
assertTrue(infraResourceManager.waitResourceCondition(infra, messagingInfra -> {
MessagingInfrastructureCondition condition = MessagingInfrastructureResourceType.getCondition(messagingInfra.getStatus().getConditions(), conditionName);
return condition != null && expectedValue.equals(condition.getStatus());
}));
}
}
|
/**
* Autogenerated by Thrift Compiler (0.9.2)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.p.s.pinpoint.thrift.dto;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import javax.annotation.Generated;
import java.nio.ByteBuffer;
import java.util.*;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2016-12-9")
public class TSpan implements org.apache.thrift.TBase<TSpan, TSpan._Fields>, java.io.Serializable, Cloneable, Comparable<TSpan> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TSpan");
private static final org.apache.thrift.protocol.TField AGENT_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("agentId", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField APPLICATION_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("applicationName", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField AGENT_START_TIME_FIELD_DESC = new org.apache.thrift.protocol.TField("agentStartTime", org.apache.thrift.protocol.TType.I64, (short)3);
private static final org.apache.thrift.protocol.TField TRANSACTION_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("transactionId", org.apache.thrift.protocol.TType.STRING, (short)4);
private static final org.apache.thrift.protocol.TField SPAN_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("spanId", org.apache.thrift.protocol.TType.I64, (short)7);
private static final org.apache.thrift.protocol.TField PARENT_SPAN_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("parentSpanId", org.apache.thrift.protocol.TType.I64, (short)8);
private static final org.apache.thrift.protocol.TField START_TIME_FIELD_DESC = new org.apache.thrift.protocol.TField("startTime", org.apache.thrift.protocol.TType.I64, (short)9);
private static final org.apache.thrift.protocol.TField ELAPSED_FIELD_DESC = new org.apache.thrift.protocol.TField("elapsed", org.apache.thrift.protocol.TType.I32, (short)10);
private static final org.apache.thrift.protocol.TField RPC_FIELD_DESC = new org.apache.thrift.protocol.TField("rpc", org.apache.thrift.protocol.TType.STRING, (short)11);
private static final org.apache.thrift.protocol.TField SERVICE_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("serviceType", org.apache.thrift.protocol.TType.I16, (short)12);
private static final org.apache.thrift.protocol.TField END_POINT_FIELD_DESC = new org.apache.thrift.protocol.TField("endPoint", org.apache.thrift.protocol.TType.STRING, (short)13);
private static final org.apache.thrift.protocol.TField REMOTE_ADDR_FIELD_DESC = new org.apache.thrift.protocol.TField("remoteAddr", org.apache.thrift.protocol.TType.STRING, (short)14);
private static final org.apache.thrift.protocol.TField ANNOTATIONS_FIELD_DESC = new org.apache.thrift.protocol.TField("annotations", org.apache.thrift.protocol.TType.LIST, (short)15);
private static final org.apache.thrift.protocol.TField FLAG_FIELD_DESC = new org.apache.thrift.protocol.TField("flag", org.apache.thrift.protocol.TType.I16, (short)16);
private static final org.apache.thrift.protocol.TField ERR_FIELD_DESC = new org.apache.thrift.protocol.TField("err", org.apache.thrift.protocol.TType.I32, (short)17);
private static final org.apache.thrift.protocol.TField SPAN_EVENT_LIST_FIELD_DESC = new org.apache.thrift.protocol.TField("spanEventList", org.apache.thrift.protocol.TType.LIST, (short)18);
private static final org.apache.thrift.protocol.TField PARENT_APPLICATION_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("parentApplicationName", org.apache.thrift.protocol.TType.STRING, (short)19);
private static final org.apache.thrift.protocol.TField PARENT_APPLICATION_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("parentApplicationType", org.apache.thrift.protocol.TType.I16, (short)20);
private static final org.apache.thrift.protocol.TField ACCEPTOR_HOST_FIELD_DESC = new org.apache.thrift.protocol.TField("acceptorHost", org.apache.thrift.protocol.TType.STRING, (short)21);
private static final org.apache.thrift.protocol.TField API_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("apiId", org.apache.thrift.protocol.TType.I32, (short)25);
private static final org.apache.thrift.protocol.TField EXCEPTION_INFO_FIELD_DESC = new org.apache.thrift.protocol.TField("exceptionInfo", org.apache.thrift.protocol.TType.STRUCT, (short)26);
private static final org.apache.thrift.protocol.TField APPLICATION_SERVICE_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("applicationServiceType", org.apache.thrift.protocol.TType.I16, (short)30);
private static final org.apache.thrift.protocol.TField LOGGING_TRANSACTION_INFO_FIELD_DESC = new org.apache.thrift.protocol.TField("loggingTransactionInfo", org.apache.thrift.protocol.TType.BYTE, (short)31);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new TSpanStandardSchemeFactory());
schemes.put(TupleScheme.class, new TSpanTupleSchemeFactory());
}
private String agentId; // required
private String applicationName; // required
private long agentStartTime; // required
private ByteBuffer transactionId; // required
private long spanId; // required
private long parentSpanId; // optional
private long startTime; // required
private int elapsed; // optional
private String rpc; // optional
private short serviceType; // required
private String endPoint; // optional
private String remoteAddr; // optional
private List<TAnnotation> annotations; // optional
private short flag; // optional
private int err; // optional
private List<TSpanEvent> spanEventList; // optional
private String parentApplicationName; // optional
private short parentApplicationType; // optional
private String acceptorHost; // optional
private int apiId; // optional
private TIntStringValue exceptionInfo; // optional
private short applicationServiceType; // optional
private byte loggingTransactionInfo; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
AGENT_ID((short)1, "agentId"),
APPLICATION_NAME((short)2, "applicationName"),
AGENT_START_TIME((short)3, "agentStartTime"),
TRANSACTION_ID((short)4, "transactionId"),
SPAN_ID((short)7, "spanId"),
PARENT_SPAN_ID((short)8, "parentSpanId"),
START_TIME((short)9, "startTime"),
ELAPSED((short)10, "elapsed"),
RPC((short)11, "rpc"),
SERVICE_TYPE((short)12, "serviceType"),
END_POINT((short)13, "endPoint"),
REMOTE_ADDR((short)14, "remoteAddr"),
ANNOTATIONS((short)15, "annotations"),
FLAG((short)16, "flag"),
ERR((short)17, "err"),
SPAN_EVENT_LIST((short)18, "spanEventList"),
PARENT_APPLICATION_NAME((short)19, "parentApplicationName"),
PARENT_APPLICATION_TYPE((short)20, "parentApplicationType"),
ACCEPTOR_HOST((short)21, "acceptorHost"),
API_ID((short)25, "apiId"),
EXCEPTION_INFO((short)26, "exceptionInfo"),
APPLICATION_SERVICE_TYPE((short)30, "applicationServiceType"),
LOGGING_TRANSACTION_INFO((short)31, "loggingTransactionInfo");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // AGENT_ID
return AGENT_ID;
case 2: // APPLICATION_NAME
return APPLICATION_NAME;
case 3: // AGENT_START_TIME
return AGENT_START_TIME;
case 4: // TRANSACTION_ID
return TRANSACTION_ID;
case 7: // SPAN_ID
return SPAN_ID;
case 8: // PARENT_SPAN_ID
return PARENT_SPAN_ID;
case 9: // START_TIME
return START_TIME;
case 10: // ELAPSED
return ELAPSED;
case 11: // RPC
return RPC;
case 12: // SERVICE_TYPE
return SERVICE_TYPE;
case 13: // END_POINT
return END_POINT;
case 14: // REMOTE_ADDR
return REMOTE_ADDR;
case 15: // ANNOTATIONS
return ANNOTATIONS;
case 16: // FLAG
return FLAG;
case 17: // ERR
return ERR;
case 18: // SPAN_EVENT_LIST
return SPAN_EVENT_LIST;
case 19: // PARENT_APPLICATION_NAME
return PARENT_APPLICATION_NAME;
case 20: // PARENT_APPLICATION_TYPE
return PARENT_APPLICATION_TYPE;
case 21: // ACCEPTOR_HOST
return ACCEPTOR_HOST;
case 25: // API_ID
return API_ID;
case 26: // EXCEPTION_INFO
return EXCEPTION_INFO;
case 30: // APPLICATION_SERVICE_TYPE
return APPLICATION_SERVICE_TYPE;
case 31: // LOGGING_TRANSACTION_INFO
return LOGGING_TRANSACTION_INFO;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __AGENTSTARTTIME_ISSET_ID = 0;
private static final int __SPANID_ISSET_ID = 1;
private static final int __PARENTSPANID_ISSET_ID = 2;
private static final int __STARTTIME_ISSET_ID = 3;
private static final int __ELAPSED_ISSET_ID = 4;
private static final int __SERVICETYPE_ISSET_ID = 5;
private static final int __FLAG_ISSET_ID = 6;
private static final int __ERR_ISSET_ID = 7;
private static final int __PARENTAPPLICATIONTYPE_ISSET_ID = 8;
private static final int __APIID_ISSET_ID = 9;
private static final int __APPLICATIONSERVICETYPE_ISSET_ID = 10;
private static final int __LOGGINGTRANSACTIONINFO_ISSET_ID = 11;
private short __isset_bitfield = 0;
private static final _Fields optionals[] = {_Fields.PARENT_SPAN_ID, _Fields.ELAPSED, _Fields.RPC, _Fields.END_POINT, _Fields.REMOTE_ADDR, _Fields.ANNOTATIONS, _Fields.FLAG, _Fields.ERR, _Fields.SPAN_EVENT_LIST, _Fields.PARENT_APPLICATION_NAME, _Fields.PARENT_APPLICATION_TYPE, _Fields.ACCEPTOR_HOST, _Fields.API_ID, _Fields.EXCEPTION_INFO, _Fields.APPLICATION_SERVICE_TYPE, _Fields.LOGGING_TRANSACTION_INFO};
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.AGENT_ID, new org.apache.thrift.meta_data.FieldMetaData("agentId", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.APPLICATION_NAME, new org.apache.thrift.meta_data.FieldMetaData("applicationName", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.AGENT_START_TIME, new org.apache.thrift.meta_data.FieldMetaData("agentStartTime", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.TRANSACTION_ID, new org.apache.thrift.meta_data.FieldMetaData("transactionId", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));
tmpMap.put(_Fields.SPAN_ID, new org.apache.thrift.meta_data.FieldMetaData("spanId", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.PARENT_SPAN_ID, new org.apache.thrift.meta_data.FieldMetaData("parentSpanId", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.START_TIME, new org.apache.thrift.meta_data.FieldMetaData("startTime", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.ELAPSED, new org.apache.thrift.meta_data.FieldMetaData("elapsed", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.RPC, new org.apache.thrift.meta_data.FieldMetaData("rpc", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.SERVICE_TYPE, new org.apache.thrift.meta_data.FieldMetaData("serviceType", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16)));
tmpMap.put(_Fields.END_POINT, new org.apache.thrift.meta_data.FieldMetaData("endPoint", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.REMOTE_ADDR, new org.apache.thrift.meta_data.FieldMetaData("remoteAddr", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.ANNOTATIONS, new org.apache.thrift.meta_data.FieldMetaData("annotations", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TAnnotation.class))));
tmpMap.put(_Fields.FLAG, new org.apache.thrift.meta_data.FieldMetaData("flag", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16)));
tmpMap.put(_Fields.ERR, new org.apache.thrift.meta_data.FieldMetaData("err", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.SPAN_EVENT_LIST, new org.apache.thrift.meta_data.FieldMetaData("spanEventList", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TSpanEvent.class))));
tmpMap.put(_Fields.PARENT_APPLICATION_NAME, new org.apache.thrift.meta_data.FieldMetaData("parentApplicationName", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.PARENT_APPLICATION_TYPE, new org.apache.thrift.meta_data.FieldMetaData("parentApplicationType", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16)));
tmpMap.put(_Fields.ACCEPTOR_HOST, new org.apache.thrift.meta_data.FieldMetaData("acceptorHost", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.API_ID, new org.apache.thrift.meta_data.FieldMetaData("apiId", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.EXCEPTION_INFO, new org.apache.thrift.meta_data.FieldMetaData("exceptionInfo", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TIntStringValue.class)));
tmpMap.put(_Fields.APPLICATION_SERVICE_TYPE, new org.apache.thrift.meta_data.FieldMetaData("applicationServiceType", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16)));
tmpMap.put(_Fields.LOGGING_TRANSACTION_INFO, new org.apache.thrift.meta_data.FieldMetaData("loggingTransactionInfo", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TSpan.class, metaDataMap);
}
public TSpan() {
this.parentSpanId = -1L;
this.elapsed = 0;
this.flag = (short)0;
}
public TSpan(
String agentId,
String applicationName,
long agentStartTime,
ByteBuffer transactionId,
long spanId,
long startTime,
short serviceType)
{
this();
this.agentId = agentId;
this.applicationName = applicationName;
this.agentStartTime = agentStartTime;
setAgentStartTimeIsSet(true);
this.transactionId = org.apache.thrift.TBaseHelper.copyBinary(transactionId);
this.spanId = spanId;
setSpanIdIsSet(true);
this.startTime = startTime;
setStartTimeIsSet(true);
this.serviceType = serviceType;
setServiceTypeIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public TSpan(TSpan other) {
__isset_bitfield = other.__isset_bitfield;
if (other.isSetAgentId()) {
this.agentId = other.agentId;
}
if (other.isSetApplicationName()) {
this.applicationName = other.applicationName;
}
this.agentStartTime = other.agentStartTime;
if (other.isSetTransactionId()) {
this.transactionId = org.apache.thrift.TBaseHelper.copyBinary(other.transactionId);
}
this.spanId = other.spanId;
this.parentSpanId = other.parentSpanId;
this.startTime = other.startTime;
this.elapsed = other.elapsed;
if (other.isSetRpc()) {
this.rpc = other.rpc;
}
this.serviceType = other.serviceType;
if (other.isSetEndPoint()) {
this.endPoint = other.endPoint;
}
if (other.isSetRemoteAddr()) {
this.remoteAddr = other.remoteAddr;
}
if (other.isSetAnnotations()) {
List<TAnnotation> __this__annotations = new ArrayList<TAnnotation>(other.annotations.size());
for (TAnnotation other_element : other.annotations) {
__this__annotations.add(new TAnnotation(other_element));
}
this.annotations = __this__annotations;
}
this.flag = other.flag;
this.err = other.err;
if (other.isSetSpanEventList()) {
List<TSpanEvent> __this__spanEventList = new ArrayList<TSpanEvent>(other.spanEventList.size());
for (TSpanEvent other_element : other.spanEventList) {
__this__spanEventList.add(new TSpanEvent(other_element));
}
this.spanEventList = __this__spanEventList;
}
if (other.isSetParentApplicationName()) {
this.parentApplicationName = other.parentApplicationName;
}
this.parentApplicationType = other.parentApplicationType;
if (other.isSetAcceptorHost()) {
this.acceptorHost = other.acceptorHost;
}
this.apiId = other.apiId;
if (other.isSetExceptionInfo()) {
this.exceptionInfo = new TIntStringValue(other.exceptionInfo);
}
this.applicationServiceType = other.applicationServiceType;
this.loggingTransactionInfo = other.loggingTransactionInfo;
}
public TSpan deepCopy() {
return new TSpan(this);
}
@Override
public void clear() {
this.agentId = null;
this.applicationName = null;
setAgentStartTimeIsSet(false);
this.agentStartTime = 0;
this.transactionId = null;
setSpanIdIsSet(false);
this.spanId = 0;
this.parentSpanId = -1L;
setStartTimeIsSet(false);
this.startTime = 0;
this.elapsed = 0;
this.rpc = null;
setServiceTypeIsSet(false);
this.serviceType = 0;
this.endPoint = null;
this.remoteAddr = null;
this.annotations = null;
this.flag = (short)0;
setErrIsSet(false);
this.err = 0;
this.spanEventList = null;
this.parentApplicationName = null;
setParentApplicationTypeIsSet(false);
this.parentApplicationType = 0;
this.acceptorHost = null;
setApiIdIsSet(false);
this.apiId = 0;
this.exceptionInfo = null;
setApplicationServiceTypeIsSet(false);
this.applicationServiceType = 0;
setLoggingTransactionInfoIsSet(false);
this.loggingTransactionInfo = 0;
}
public String getAgentId() {
return this.agentId;
}
public void setAgentId(String agentId) {
this.agentId = agentId;
}
public void unsetAgentId() {
this.agentId = null;
}
/** Returns true if field agentId is set (has been assigned a value) and false otherwise */
public boolean isSetAgentId() {
return this.agentId != null;
}
public void setAgentIdIsSet(boolean value) {
if (!value) {
this.agentId = null;
}
}
public String getApplicationName() {
return this.applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public void unsetApplicationName() {
this.applicationName = null;
}
/** Returns true if field applicationName is set (has been assigned a value) and false otherwise */
public boolean isSetApplicationName() {
return this.applicationName != null;
}
public void setApplicationNameIsSet(boolean value) {
if (!value) {
this.applicationName = null;
}
}
public long getAgentStartTime() {
return this.agentStartTime;
}
public void setAgentStartTime(long agentStartTime) {
this.agentStartTime = agentStartTime;
setAgentStartTimeIsSet(true);
}
public void unsetAgentStartTime() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __AGENTSTARTTIME_ISSET_ID);
}
/** Returns true if field agentStartTime is set (has been assigned a value) and false otherwise */
public boolean isSetAgentStartTime() {
return EncodingUtils.testBit(__isset_bitfield, __AGENTSTARTTIME_ISSET_ID);
}
public void setAgentStartTimeIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __AGENTSTARTTIME_ISSET_ID, value);
}
public byte[] getTransactionId() {
setTransactionId(org.apache.thrift.TBaseHelper.rightSize(transactionId));
return transactionId == null ? null : transactionId.array();
}
public ByteBuffer bufferForTransactionId() {
return org.apache.thrift.TBaseHelper.copyBinary(transactionId);
}
public void setTransactionId(byte[] transactionId) {
this.transactionId = transactionId == null ? (ByteBuffer)null : ByteBuffer.wrap(Arrays.copyOf(transactionId, transactionId.length));
}
public void setTransactionId(ByteBuffer transactionId) {
this.transactionId = org.apache.thrift.TBaseHelper.copyBinary(transactionId);
}
public void unsetTransactionId() {
this.transactionId = null;
}
/** Returns true if field transactionId is set (has been assigned a value) and false otherwise */
public boolean isSetTransactionId() {
return this.transactionId != null;
}
public void setTransactionIdIsSet(boolean value) {
if (!value) {
this.transactionId = null;
}
}
public long getSpanId() {
return this.spanId;
}
public void setSpanId(long spanId) {
this.spanId = spanId;
setSpanIdIsSet(true);
}
public void unsetSpanId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SPANID_ISSET_ID);
}
/** Returns true if field spanId is set (has been assigned a value) and false otherwise */
public boolean isSetSpanId() {
return EncodingUtils.testBit(__isset_bitfield, __SPANID_ISSET_ID);
}
public void setSpanIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SPANID_ISSET_ID, value);
}
public long getParentSpanId() {
return this.parentSpanId;
}
public void setParentSpanId(long parentSpanId) {
this.parentSpanId = parentSpanId;
setParentSpanIdIsSet(true);
}
public void unsetParentSpanId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PARENTSPANID_ISSET_ID);
}
/** Returns true if field parentSpanId is set (has been assigned a value) and false otherwise */
public boolean isSetParentSpanId() {
return EncodingUtils.testBit(__isset_bitfield, __PARENTSPANID_ISSET_ID);
}
public void setParentSpanIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PARENTSPANID_ISSET_ID, value);
}
public long getStartTime() {
return this.startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
setStartTimeIsSet(true);
}
public void unsetStartTime() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __STARTTIME_ISSET_ID);
}
/** Returns true if field startTime is set (has been assigned a value) and false otherwise */
public boolean isSetStartTime() {
return EncodingUtils.testBit(__isset_bitfield, __STARTTIME_ISSET_ID);
}
public void setStartTimeIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __STARTTIME_ISSET_ID, value);
}
public int getElapsed() {
return this.elapsed;
}
public void setElapsed(int elapsed) {
this.elapsed = elapsed;
setElapsedIsSet(true);
}
public void unsetElapsed() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ELAPSED_ISSET_ID);
}
/** Returns true if field elapsed is set (has been assigned a value) and false otherwise */
public boolean isSetElapsed() {
return EncodingUtils.testBit(__isset_bitfield, __ELAPSED_ISSET_ID);
}
public void setElapsedIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ELAPSED_ISSET_ID, value);
}
public String getRpc() {
return this.rpc;
}
public void setRpc(String rpc) {
this.rpc = rpc;
}
public void unsetRpc() {
this.rpc = null;
}
/** Returns true if field rpc is set (has been assigned a value) and false otherwise */
public boolean isSetRpc() {
return this.rpc != null;
}
public void setRpcIsSet(boolean value) {
if (!value) {
this.rpc = null;
}
}
public short getServiceType() {
return this.serviceType;
}
public void setServiceType(short serviceType) {
this.serviceType = serviceType;
setServiceTypeIsSet(true);
}
public void unsetServiceType() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SERVICETYPE_ISSET_ID);
}
/** Returns true if field serviceType is set (has been assigned a value) and false otherwise */
public boolean isSetServiceType() {
return EncodingUtils.testBit(__isset_bitfield, __SERVICETYPE_ISSET_ID);
}
public void setServiceTypeIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SERVICETYPE_ISSET_ID, value);
}
public String getEndPoint() {
return this.endPoint;
}
public void setEndPoint(String endPoint) {
this.endPoint = endPoint;
}
public void unsetEndPoint() {
this.endPoint = null;
}
/** Returns true if field endPoint is set (has been assigned a value) and false otherwise */
public boolean isSetEndPoint() {
return this.endPoint != null;
}
public void setEndPointIsSet(boolean value) {
if (!value) {
this.endPoint = null;
}
}
public String getRemoteAddr() {
return this.remoteAddr;
}
public void setRemoteAddr(String remoteAddr) {
this.remoteAddr = remoteAddr;
}
public void unsetRemoteAddr() {
this.remoteAddr = null;
}
/** Returns true if field remoteAddr is set (has been assigned a value) and false otherwise */
public boolean isSetRemoteAddr() {
return this.remoteAddr != null;
}
public void setRemoteAddrIsSet(boolean value) {
if (!value) {
this.remoteAddr = null;
}
}
public int getAnnotationsSize() {
return (this.annotations == null) ? 0 : this.annotations.size();
}
public java.util.Iterator<TAnnotation> getAnnotationsIterator() {
return (this.annotations == null) ? null : this.annotations.iterator();
}
public void addToAnnotations(TAnnotation elem) {
if (this.annotations == null) {
this.annotations = new ArrayList<TAnnotation>();
}
this.annotations.add(elem);
}
public List<TAnnotation> getAnnotations() {
return this.annotations;
}
public void setAnnotations(List<TAnnotation> annotations) {
this.annotations = annotations;
}
public void unsetAnnotations() {
this.annotations = null;
}
/** Returns true if field annotations is set (has been assigned a value) and false otherwise */
public boolean isSetAnnotations() {
return this.annotations != null;
}
public void setAnnotationsIsSet(boolean value) {
if (!value) {
this.annotations = null;
}
}
public short getFlag() {
return this.flag;
}
public void setFlag(short flag) {
this.flag = flag;
setFlagIsSet(true);
}
public void unsetFlag() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __FLAG_ISSET_ID);
}
/** Returns true if field flag is set (has been assigned a value) and false otherwise */
public boolean isSetFlag() {
return EncodingUtils.testBit(__isset_bitfield, __FLAG_ISSET_ID);
}
public void setFlagIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __FLAG_ISSET_ID, value);
}
public int getErr() {
return this.err;
}
public void setErr(int err) {
this.err = err;
setErrIsSet(true);
}
public void unsetErr() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ERR_ISSET_ID);
}
/** Returns true if field err is set (has been assigned a value) and false otherwise */
public boolean isSetErr() {
return EncodingUtils.testBit(__isset_bitfield, __ERR_ISSET_ID);
}
public void setErrIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ERR_ISSET_ID, value);
}
public int getSpanEventListSize() {
return (this.spanEventList == null) ? 0 : this.spanEventList.size();
}
public java.util.Iterator<TSpanEvent> getSpanEventListIterator() {
return (this.spanEventList == null) ? null : this.spanEventList.iterator();
}
public void addToSpanEventList(TSpanEvent elem) {
if (this.spanEventList == null) {
this.spanEventList = new ArrayList<TSpanEvent>();
}
this.spanEventList.add(elem);
}
public List<TSpanEvent> getSpanEventList() {
return this.spanEventList;
}
public void setSpanEventList(List<TSpanEvent> spanEventList) {
this.spanEventList = spanEventList;
}
public void unsetSpanEventList() {
this.spanEventList = null;
}
/** Returns true if field spanEventList is set (has been assigned a value) and false otherwise */
public boolean isSetSpanEventList() {
return this.spanEventList != null;
}
public void setSpanEventListIsSet(boolean value) {
if (!value) {
this.spanEventList = null;
}
}
public String getParentApplicationName() {
return this.parentApplicationName;
}
public void setParentApplicationName(String parentApplicationName) {
this.parentApplicationName = parentApplicationName;
}
public void unsetParentApplicationName() {
this.parentApplicationName = null;
}
/** Returns true if field parentApplicationName is set (has been assigned a value) and false otherwise */
public boolean isSetParentApplicationName() {
return this.parentApplicationName != null;
}
public void setParentApplicationNameIsSet(boolean value) {
if (!value) {
this.parentApplicationName = null;
}
}
public short getParentApplicationType() {
return this.parentApplicationType;
}
public void setParentApplicationType(short parentApplicationType) {
this.parentApplicationType = parentApplicationType;
setParentApplicationTypeIsSet(true);
}
public void unsetParentApplicationType() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PARENTAPPLICATIONTYPE_ISSET_ID);
}
/** Returns true if field parentApplicationType is set (has been assigned a value) and false otherwise */
public boolean isSetParentApplicationType() {
return EncodingUtils.testBit(__isset_bitfield, __PARENTAPPLICATIONTYPE_ISSET_ID);
}
public void setParentApplicationTypeIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PARENTAPPLICATIONTYPE_ISSET_ID, value);
}
public String getAcceptorHost() {
return this.acceptorHost;
}
public void setAcceptorHost(String acceptorHost) {
this.acceptorHost = acceptorHost;
}
public void unsetAcceptorHost() {
this.acceptorHost = null;
}
/** Returns true if field acceptorHost is set (has been assigned a value) and false otherwise */
public boolean isSetAcceptorHost() {
return this.acceptorHost != null;
}
public void setAcceptorHostIsSet(boolean value) {
if (!value) {
this.acceptorHost = null;
}
}
public int getApiId() {
return this.apiId;
}
public void setApiId(int apiId) {
this.apiId = apiId;
setApiIdIsSet(true);
}
public void unsetApiId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __APIID_ISSET_ID);
}
/** Returns true if field apiId is set (has been assigned a value) and false otherwise */
public boolean isSetApiId() {
return EncodingUtils.testBit(__isset_bitfield, __APIID_ISSET_ID);
}
public void setApiIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __APIID_ISSET_ID, value);
}
public TIntStringValue getExceptionInfo() {
return this.exceptionInfo;
}
public void setExceptionInfo(TIntStringValue exceptionInfo) {
this.exceptionInfo = exceptionInfo;
}
public void unsetExceptionInfo() {
this.exceptionInfo = null;
}
/** Returns true if field exceptionInfo is set (has been assigned a value) and false otherwise */
public boolean isSetExceptionInfo() {
return this.exceptionInfo != null;
}
public void setExceptionInfoIsSet(boolean value) {
if (!value) {
this.exceptionInfo = null;
}
}
public short getApplicationServiceType() {
return this.applicationServiceType;
}
public void setApplicationServiceType(short applicationServiceType) {
this.applicationServiceType = applicationServiceType;
setApplicationServiceTypeIsSet(true);
}
public void unsetApplicationServiceType() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __APPLICATIONSERVICETYPE_ISSET_ID);
}
/** Returns true if field applicationServiceType is set (has been assigned a value) and false otherwise */
public boolean isSetApplicationServiceType() {
return EncodingUtils.testBit(__isset_bitfield, __APPLICATIONSERVICETYPE_ISSET_ID);
}
public void setApplicationServiceTypeIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __APPLICATIONSERVICETYPE_ISSET_ID, value);
}
public byte getLoggingTransactionInfo() {
return this.loggingTransactionInfo;
}
public void setLoggingTransactionInfo(byte loggingTransactionInfo) {
this.loggingTransactionInfo = loggingTransactionInfo;
setLoggingTransactionInfoIsSet(true);
}
public void unsetLoggingTransactionInfo() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __LOGGINGTRANSACTIONINFO_ISSET_ID);
}
/** Returns true if field loggingTransactionInfo is set (has been assigned a value) and false otherwise */
public boolean isSetLoggingTransactionInfo() {
return EncodingUtils.testBit(__isset_bitfield, __LOGGINGTRANSACTIONINFO_ISSET_ID);
}
public void setLoggingTransactionInfoIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __LOGGINGTRANSACTIONINFO_ISSET_ID, value);
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case AGENT_ID:
if (value == null) {
unsetAgentId();
} else {
setAgentId((String)value);
}
break;
case APPLICATION_NAME:
if (value == null) {
unsetApplicationName();
} else {
setApplicationName((String)value);
}
break;
case AGENT_START_TIME:
if (value == null) {
unsetAgentStartTime();
} else {
setAgentStartTime((Long)value);
}
break;
case TRANSACTION_ID:
if (value == null) {
unsetTransactionId();
} else {
setTransactionId((ByteBuffer)value);
}
break;
case SPAN_ID:
if (value == null) {
unsetSpanId();
} else {
setSpanId((Long)value);
}
break;
case PARENT_SPAN_ID:
if (value == null) {
unsetParentSpanId();
} else {
setParentSpanId((Long)value);
}
break;
case START_TIME:
if (value == null) {
unsetStartTime();
} else {
setStartTime((Long)value);
}
break;
case ELAPSED:
if (value == null) {
unsetElapsed();
} else {
setElapsed((Integer)value);
}
break;
case RPC:
if (value == null) {
unsetRpc();
} else {
setRpc((String)value);
}
break;
case SERVICE_TYPE:
if (value == null) {
unsetServiceType();
} else {
setServiceType((Short)value);
}
break;
case END_POINT:
if (value == null) {
unsetEndPoint();
} else {
setEndPoint((String)value);
}
break;
case REMOTE_ADDR:
if (value == null) {
unsetRemoteAddr();
} else {
setRemoteAddr((String)value);
}
break;
case ANNOTATIONS:
if (value == null) {
unsetAnnotations();
} else {
setAnnotations((List<TAnnotation>)value);
}
break;
case FLAG:
if (value == null) {
unsetFlag();
} else {
setFlag((Short)value);
}
break;
case ERR:
if (value == null) {
unsetErr();
} else {
setErr((Integer)value);
}
break;
case SPAN_EVENT_LIST:
if (value == null) {
unsetSpanEventList();
} else {
setSpanEventList((List<TSpanEvent>)value);
}
break;
case PARENT_APPLICATION_NAME:
if (value == null) {
unsetParentApplicationName();
} else {
setParentApplicationName((String)value);
}
break;
case PARENT_APPLICATION_TYPE:
if (value == null) {
unsetParentApplicationType();
} else {
setParentApplicationType((Short)value);
}
break;
case ACCEPTOR_HOST:
if (value == null) {
unsetAcceptorHost();
} else {
setAcceptorHost((String)value);
}
break;
case API_ID:
if (value == null) {
unsetApiId();
} else {
setApiId((Integer)value);
}
break;
case EXCEPTION_INFO:
if (value == null) {
unsetExceptionInfo();
} else {
setExceptionInfo((TIntStringValue)value);
}
break;
case APPLICATION_SERVICE_TYPE:
if (value == null) {
unsetApplicationServiceType();
} else {
setApplicationServiceType((Short)value);
}
break;
case LOGGING_TRANSACTION_INFO:
if (value == null) {
unsetLoggingTransactionInfo();
} else {
setLoggingTransactionInfo((Byte)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case AGENT_ID:
return getAgentId();
case APPLICATION_NAME:
return getApplicationName();
case AGENT_START_TIME:
return Long.valueOf(getAgentStartTime());
case TRANSACTION_ID:
return getTransactionId();
case SPAN_ID:
return Long.valueOf(getSpanId());
case PARENT_SPAN_ID:
return Long.valueOf(getParentSpanId());
case START_TIME:
return Long.valueOf(getStartTime());
case ELAPSED:
return Integer.valueOf(getElapsed());
case RPC:
return getRpc();
case SERVICE_TYPE:
return Short.valueOf(getServiceType());
case END_POINT:
return getEndPoint();
case REMOTE_ADDR:
return getRemoteAddr();
case ANNOTATIONS:
return getAnnotations();
case FLAG:
return Short.valueOf(getFlag());
case ERR:
return Integer.valueOf(getErr());
case SPAN_EVENT_LIST:
return getSpanEventList();
case PARENT_APPLICATION_NAME:
return getParentApplicationName();
case PARENT_APPLICATION_TYPE:
return Short.valueOf(getParentApplicationType());
case ACCEPTOR_HOST:
return getAcceptorHost();
case API_ID:
return Integer.valueOf(getApiId());
case EXCEPTION_INFO:
return getExceptionInfo();
case APPLICATION_SERVICE_TYPE:
return Short.valueOf(getApplicationServiceType());
case LOGGING_TRANSACTION_INFO:
return Byte.valueOf(getLoggingTransactionInfo());
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case AGENT_ID:
return isSetAgentId();
case APPLICATION_NAME:
return isSetApplicationName();
case AGENT_START_TIME:
return isSetAgentStartTime();
case TRANSACTION_ID:
return isSetTransactionId();
case SPAN_ID:
return isSetSpanId();
case PARENT_SPAN_ID:
return isSetParentSpanId();
case START_TIME:
return isSetStartTime();
case ELAPSED:
return isSetElapsed();
case RPC:
return isSetRpc();
case SERVICE_TYPE:
return isSetServiceType();
case END_POINT:
return isSetEndPoint();
case REMOTE_ADDR:
return isSetRemoteAddr();
case ANNOTATIONS:
return isSetAnnotations();
case FLAG:
return isSetFlag();
case ERR:
return isSetErr();
case SPAN_EVENT_LIST:
return isSetSpanEventList();
case PARENT_APPLICATION_NAME:
return isSetParentApplicationName();
case PARENT_APPLICATION_TYPE:
return isSetParentApplicationType();
case ACCEPTOR_HOST:
return isSetAcceptorHost();
case API_ID:
return isSetApiId();
case EXCEPTION_INFO:
return isSetExceptionInfo();
case APPLICATION_SERVICE_TYPE:
return isSetApplicationServiceType();
case LOGGING_TRANSACTION_INFO:
return isSetLoggingTransactionInfo();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof TSpan)
return this.equals((TSpan)that);
return false;
}
public boolean equals(TSpan that) {
if (that == null)
return false;
boolean this_present_agentId = true && this.isSetAgentId();
boolean that_present_agentId = true && that.isSetAgentId();
if (this_present_agentId || that_present_agentId) {
if (!(this_present_agentId && that_present_agentId))
return false;
if (!this.agentId.equals(that.agentId))
return false;
}
boolean this_present_applicationName = true && this.isSetApplicationName();
boolean that_present_applicationName = true && that.isSetApplicationName();
if (this_present_applicationName || that_present_applicationName) {
if (!(this_present_applicationName && that_present_applicationName))
return false;
if (!this.applicationName.equals(that.applicationName))
return false;
}
boolean this_present_agentStartTime = true;
boolean that_present_agentStartTime = true;
if (this_present_agentStartTime || that_present_agentStartTime) {
if (!(this_present_agentStartTime && that_present_agentStartTime))
return false;
if (this.agentStartTime != that.agentStartTime)
return false;
}
boolean this_present_transactionId = true && this.isSetTransactionId();
boolean that_present_transactionId = true && that.isSetTransactionId();
if (this_present_transactionId || that_present_transactionId) {
if (!(this_present_transactionId && that_present_transactionId))
return false;
if (!this.transactionId.equals(that.transactionId))
return false;
}
boolean this_present_spanId = true;
boolean that_present_spanId = true;
if (this_present_spanId || that_present_spanId) {
if (!(this_present_spanId && that_present_spanId))
return false;
if (this.spanId != that.spanId)
return false;
}
boolean this_present_parentSpanId = true && this.isSetParentSpanId();
boolean that_present_parentSpanId = true && that.isSetParentSpanId();
if (this_present_parentSpanId || that_present_parentSpanId) {
if (!(this_present_parentSpanId && that_present_parentSpanId))
return false;
if (this.parentSpanId != that.parentSpanId)
return false;
}
boolean this_present_startTime = true;
boolean that_present_startTime = true;
if (this_present_startTime || that_present_startTime) {
if (!(this_present_startTime && that_present_startTime))
return false;
if (this.startTime != that.startTime)
return false;
}
boolean this_present_elapsed = true && this.isSetElapsed();
boolean that_present_elapsed = true && that.isSetElapsed();
if (this_present_elapsed || that_present_elapsed) {
if (!(this_present_elapsed && that_present_elapsed))
return false;
if (this.elapsed != that.elapsed)
return false;
}
boolean this_present_rpc = true && this.isSetRpc();
boolean that_present_rpc = true && that.isSetRpc();
if (this_present_rpc || that_present_rpc) {
if (!(this_present_rpc && that_present_rpc))
return false;
if (!this.rpc.equals(that.rpc))
return false;
}
boolean this_present_serviceType = true;
boolean that_present_serviceType = true;
if (this_present_serviceType || that_present_serviceType) {
if (!(this_present_serviceType && that_present_serviceType))
return false;
if (this.serviceType != that.serviceType)
return false;
}
boolean this_present_endPoint = true && this.isSetEndPoint();
boolean that_present_endPoint = true && that.isSetEndPoint();
if (this_present_endPoint || that_present_endPoint) {
if (!(this_present_endPoint && that_present_endPoint))
return false;
if (!this.endPoint.equals(that.endPoint))
return false;
}
boolean this_present_remoteAddr = true && this.isSetRemoteAddr();
boolean that_present_remoteAddr = true && that.isSetRemoteAddr();
if (this_present_remoteAddr || that_present_remoteAddr) {
if (!(this_present_remoteAddr && that_present_remoteAddr))
return false;
if (!this.remoteAddr.equals(that.remoteAddr))
return false;
}
boolean this_present_annotations = true && this.isSetAnnotations();
boolean that_present_annotations = true && that.isSetAnnotations();
if (this_present_annotations || that_present_annotations) {
if (!(this_present_annotations && that_present_annotations))
return false;
if (!this.annotations.equals(that.annotations))
return false;
}
boolean this_present_flag = true && this.isSetFlag();
boolean that_present_flag = true && that.isSetFlag();
if (this_present_flag || that_present_flag) {
if (!(this_present_flag && that_present_flag))
return false;
if (this.flag != that.flag)
return false;
}
boolean this_present_err = true && this.isSetErr();
boolean that_present_err = true && that.isSetErr();
if (this_present_err || that_present_err) {
if (!(this_present_err && that_present_err))
return false;
if (this.err != that.err)
return false;
}
boolean this_present_spanEventList = true && this.isSetSpanEventList();
boolean that_present_spanEventList = true && that.isSetSpanEventList();
if (this_present_spanEventList || that_present_spanEventList) {
if (!(this_present_spanEventList && that_present_spanEventList))
return false;
if (!this.spanEventList.equals(that.spanEventList))
return false;
}
boolean this_present_parentApplicationName = true && this.isSetParentApplicationName();
boolean that_present_parentApplicationName = true && that.isSetParentApplicationName();
if (this_present_parentApplicationName || that_present_parentApplicationName) {
if (!(this_present_parentApplicationName && that_present_parentApplicationName))
return false;
if (!this.parentApplicationName.equals(that.parentApplicationName))
return false;
}
boolean this_present_parentApplicationType = true && this.isSetParentApplicationType();
boolean that_present_parentApplicationType = true && that.isSetParentApplicationType();
if (this_present_parentApplicationType || that_present_parentApplicationType) {
if (!(this_present_parentApplicationType && that_present_parentApplicationType))
return false;
if (this.parentApplicationType != that.parentApplicationType)
return false;
}
boolean this_present_acceptorHost = true && this.isSetAcceptorHost();
boolean that_present_acceptorHost = true && that.isSetAcceptorHost();
if (this_present_acceptorHost || that_present_acceptorHost) {
if (!(this_present_acceptorHost && that_present_acceptorHost))
return false;
if (!this.acceptorHost.equals(that.acceptorHost))
return false;
}
boolean this_present_apiId = true && this.isSetApiId();
boolean that_present_apiId = true && that.isSetApiId();
if (this_present_apiId || that_present_apiId) {
if (!(this_present_apiId && that_present_apiId))
return false;
if (this.apiId != that.apiId)
return false;
}
boolean this_present_exceptionInfo = true && this.isSetExceptionInfo();
boolean that_present_exceptionInfo = true && that.isSetExceptionInfo();
if (this_present_exceptionInfo || that_present_exceptionInfo) {
if (!(this_present_exceptionInfo && that_present_exceptionInfo))
return false;
if (!this.exceptionInfo.equals(that.exceptionInfo))
return false;
}
boolean this_present_applicationServiceType = true && this.isSetApplicationServiceType();
boolean that_present_applicationServiceType = true && that.isSetApplicationServiceType();
if (this_present_applicationServiceType || that_present_applicationServiceType) {
if (!(this_present_applicationServiceType && that_present_applicationServiceType))
return false;
if (this.applicationServiceType != that.applicationServiceType)
return false;
}
boolean this_present_loggingTransactionInfo = true && this.isSetLoggingTransactionInfo();
boolean that_present_loggingTransactionInfo = true && that.isSetLoggingTransactionInfo();
if (this_present_loggingTransactionInfo || that_present_loggingTransactionInfo) {
if (!(this_present_loggingTransactionInfo && that_present_loggingTransactionInfo))
return false;
if (this.loggingTransactionInfo != that.loggingTransactionInfo)
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_agentId = true && (isSetAgentId());
list.add(present_agentId);
if (present_agentId)
list.add(agentId);
boolean present_applicationName = true && (isSetApplicationName());
list.add(present_applicationName);
if (present_applicationName)
list.add(applicationName);
boolean present_agentStartTime = true;
list.add(present_agentStartTime);
if (present_agentStartTime)
list.add(agentStartTime);
boolean present_transactionId = true && (isSetTransactionId());
list.add(present_transactionId);
if (present_transactionId)
list.add(transactionId);
boolean present_spanId = true;
list.add(present_spanId);
if (present_spanId)
list.add(spanId);
boolean present_parentSpanId = true && (isSetParentSpanId());
list.add(present_parentSpanId);
if (present_parentSpanId)
list.add(parentSpanId);
boolean present_startTime = true;
list.add(present_startTime);
if (present_startTime)
list.add(startTime);
boolean present_elapsed = true && (isSetElapsed());
list.add(present_elapsed);
if (present_elapsed)
list.add(elapsed);
boolean present_rpc = true && (isSetRpc());
list.add(present_rpc);
if (present_rpc)
list.add(rpc);
boolean present_serviceType = true;
list.add(present_serviceType);
if (present_serviceType)
list.add(serviceType);
boolean present_endPoint = true && (isSetEndPoint());
list.add(present_endPoint);
if (present_endPoint)
list.add(endPoint);
boolean present_remoteAddr = true && (isSetRemoteAddr());
list.add(present_remoteAddr);
if (present_remoteAddr)
list.add(remoteAddr);
boolean present_annotations = true && (isSetAnnotations());
list.add(present_annotations);
if (present_annotations)
list.add(annotations);
boolean present_flag = true && (isSetFlag());
list.add(present_flag);
if (present_flag)
list.add(flag);
boolean present_err = true && (isSetErr());
list.add(present_err);
if (present_err)
list.add(err);
boolean present_spanEventList = true && (isSetSpanEventList());
list.add(present_spanEventList);
if (present_spanEventList)
list.add(spanEventList);
boolean present_parentApplicationName = true && (isSetParentApplicationName());
list.add(present_parentApplicationName);
if (present_parentApplicationName)
list.add(parentApplicationName);
boolean present_parentApplicationType = true && (isSetParentApplicationType());
list.add(present_parentApplicationType);
if (present_parentApplicationType)
list.add(parentApplicationType);
boolean present_acceptorHost = true && (isSetAcceptorHost());
list.add(present_acceptorHost);
if (present_acceptorHost)
list.add(acceptorHost);
boolean present_apiId = true && (isSetApiId());
list.add(present_apiId);
if (present_apiId)
list.add(apiId);
boolean present_exceptionInfo = true && (isSetExceptionInfo());
list.add(present_exceptionInfo);
if (present_exceptionInfo)
list.add(exceptionInfo);
boolean present_applicationServiceType = true && (isSetApplicationServiceType());
list.add(present_applicationServiceType);
if (present_applicationServiceType)
list.add(applicationServiceType);
boolean present_loggingTransactionInfo = true && (isSetLoggingTransactionInfo());
list.add(present_loggingTransactionInfo);
if (present_loggingTransactionInfo)
list.add(loggingTransactionInfo);
return list.hashCode();
}
@Override
public int compareTo(TSpan other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetAgentId()).compareTo(other.isSetAgentId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetAgentId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.agentId, other.agentId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetApplicationName()).compareTo(other.isSetApplicationName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetApplicationName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.applicationName, other.applicationName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetAgentStartTime()).compareTo(other.isSetAgentStartTime());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetAgentStartTime()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.agentStartTime, other.agentStartTime);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetTransactionId()).compareTo(other.isSetTransactionId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTransactionId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.transactionId, other.transactionId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetSpanId()).compareTo(other.isSetSpanId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSpanId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.spanId, other.spanId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetParentSpanId()).compareTo(other.isSetParentSpanId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetParentSpanId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.parentSpanId, other.parentSpanId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetStartTime()).compareTo(other.isSetStartTime());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetStartTime()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.startTime, other.startTime);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetElapsed()).compareTo(other.isSetElapsed());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetElapsed()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.elapsed, other.elapsed);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetRpc()).compareTo(other.isSetRpc());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetRpc()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.rpc, other.rpc);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetServiceType()).compareTo(other.isSetServiceType());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetServiceType()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.serviceType, other.serviceType);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetEndPoint()).compareTo(other.isSetEndPoint());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetEndPoint()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.endPoint, other.endPoint);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetRemoteAddr()).compareTo(other.isSetRemoteAddr());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetRemoteAddr()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.remoteAddr, other.remoteAddr);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetAnnotations()).compareTo(other.isSetAnnotations());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetAnnotations()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.annotations, other.annotations);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetFlag()).compareTo(other.isSetFlag());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetFlag()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.flag, other.flag);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetErr()).compareTo(other.isSetErr());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetErr()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.err, other.err);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetSpanEventList()).compareTo(other.isSetSpanEventList());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSpanEventList()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.spanEventList, other.spanEventList);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetParentApplicationName()).compareTo(other.isSetParentApplicationName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetParentApplicationName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.parentApplicationName, other.parentApplicationName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetParentApplicationType()).compareTo(other.isSetParentApplicationType());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetParentApplicationType()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.parentApplicationType, other.parentApplicationType);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetAcceptorHost()).compareTo(other.isSetAcceptorHost());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetAcceptorHost()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.acceptorHost, other.acceptorHost);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetApiId()).compareTo(other.isSetApiId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetApiId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.apiId, other.apiId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetExceptionInfo()).compareTo(other.isSetExceptionInfo());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetExceptionInfo()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.exceptionInfo, other.exceptionInfo);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetApplicationServiceType()).compareTo(other.isSetApplicationServiceType());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetApplicationServiceType()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.applicationServiceType, other.applicationServiceType);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetLoggingTransactionInfo()).compareTo(other.isSetLoggingTransactionInfo());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetLoggingTransactionInfo()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.loggingTransactionInfo, other.loggingTransactionInfo);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TSpan(");
boolean first = true;
sb.append("agentId:");
if (this.agentId == null) {
sb.append("null");
} else {
sb.append(this.agentId);
}
first = false;
if (!first) sb.append(", ");
sb.append("applicationName:");
if (this.applicationName == null) {
sb.append("null");
} else {
sb.append(this.applicationName);
}
first = false;
if (!first) sb.append(", ");
sb.append("agentStartTime:");
sb.append(this.agentStartTime);
first = false;
if (!first) sb.append(", ");
sb.append("transactionId:");
if (this.transactionId == null) {
sb.append("null");
} else {
org.apache.thrift.TBaseHelper.toString(this.transactionId, sb);
}
first = false;
if (!first) sb.append(", ");
sb.append("spanId:");
sb.append(this.spanId);
first = false;
if (isSetParentSpanId()) {
if (!first) sb.append(", ");
sb.append("parentSpanId:");
sb.append(this.parentSpanId);
first = false;
}
if (!first) sb.append(", ");
sb.append("startTime:");
sb.append(this.startTime);
first = false;
if (isSetElapsed()) {
if (!first) sb.append(", ");
sb.append("elapsed:");
sb.append(this.elapsed);
first = false;
}
if (isSetRpc()) {
if (!first) sb.append(", ");
sb.append("rpc:");
if (this.rpc == null) {
sb.append("null");
} else {
sb.append(this.rpc);
}
first = false;
}
if (!first) sb.append(", ");
sb.append("serviceType:");
sb.append(this.serviceType);
first = false;
if (isSetEndPoint()) {
if (!first) sb.append(", ");
sb.append("endPoint:");
if (this.endPoint == null) {
sb.append("null");
} else {
sb.append(this.endPoint);
}
first = false;
}
if (isSetRemoteAddr()) {
if (!first) sb.append(", ");
sb.append("remoteAddr:");
if (this.remoteAddr == null) {
sb.append("null");
} else {
sb.append(this.remoteAddr);
}
first = false;
}
if (isSetAnnotations()) {
if (!first) sb.append(", ");
sb.append("annotations:");
if (this.annotations == null) {
sb.append("null");
} else {
sb.append(this.annotations);
}
first = false;
}
if (isSetFlag()) {
if (!first) sb.append(", ");
sb.append("flag:");
sb.append(this.flag);
first = false;
}
if (isSetErr()) {
if (!first) sb.append(", ");
sb.append("err:");
sb.append(this.err);
first = false;
}
if (isSetSpanEventList()) {
if (!first) sb.append(", ");
sb.append("spanEventList:");
if (this.spanEventList == null) {
sb.append("null");
} else {
sb.append(this.spanEventList);
}
first = false;
}
if (isSetParentApplicationName()) {
if (!first) sb.append(", ");
sb.append("parentApplicationName:");
if (this.parentApplicationName == null) {
sb.append("null");
} else {
sb.append(this.parentApplicationName);
}
first = false;
}
if (isSetParentApplicationType()) {
if (!first) sb.append(", ");
sb.append("parentApplicationType:");
sb.append(this.parentApplicationType);
first = false;
}
if (isSetAcceptorHost()) {
if (!first) sb.append(", ");
sb.append("acceptorHost:");
if (this.acceptorHost == null) {
sb.append("null");
} else {
sb.append(this.acceptorHost);
}
first = false;
}
if (isSetApiId()) {
if (!first) sb.append(", ");
sb.append("apiId:");
sb.append(this.apiId);
first = false;
}
if (isSetExceptionInfo()) {
if (!first) sb.append(", ");
sb.append("exceptionInfo:");
if (this.exceptionInfo == null) {
sb.append("null");
} else {
sb.append(this.exceptionInfo);
}
first = false;
}
if (isSetApplicationServiceType()) {
if (!first) sb.append(", ");
sb.append("applicationServiceType:");
sb.append(this.applicationServiceType);
first = false;
}
if (isSetLoggingTransactionInfo()) {
if (!first) sb.append(", ");
sb.append("loggingTransactionInfo:");
sb.append(this.loggingTransactionInfo);
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
if (exceptionInfo != null) {
exceptionInfo.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class TSpanStandardSchemeFactory implements SchemeFactory {
public TSpanStandardScheme getScheme() {
return new TSpanStandardScheme();
}
}
private static class TSpanStandardScheme extends StandardScheme<TSpan> {
public void read(org.apache.thrift.protocol.TProtocol iprot, TSpan struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // AGENT_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.agentId = iprot.readString();
struct.setAgentIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // APPLICATION_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.applicationName = iprot.readString();
struct.setApplicationNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // AGENT_START_TIME
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.agentStartTime = iprot.readI64();
struct.setAgentStartTimeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // TRANSACTION_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.transactionId = iprot.readBinary();
struct.setTransactionIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 7: // SPAN_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.spanId = iprot.readI64();
struct.setSpanIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 8: // PARENT_SPAN_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.parentSpanId = iprot.readI64();
struct.setParentSpanIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 9: // START_TIME
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.startTime = iprot.readI64();
struct.setStartTimeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 10: // ELAPSED
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.elapsed = iprot.readI32();
struct.setElapsedIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 11: // RPC
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.rpc = iprot.readString();
struct.setRpcIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 12: // SERVICE_TYPE
if (schemeField.type == org.apache.thrift.protocol.TType.I16) {
struct.serviceType = iprot.readI16();
struct.setServiceTypeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 13: // END_POINT
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.endPoint = iprot.readString();
struct.setEndPointIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 14: // REMOTE_ADDR
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.remoteAddr = iprot.readString();
struct.setRemoteAddrIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 15: // ANNOTATIONS
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list8 = iprot.readListBegin();
struct.annotations = new ArrayList<TAnnotation>(_list8.size);
TAnnotation _elem9;
for (int _i10 = 0; _i10 < _list8.size; ++_i10)
{
_elem9 = new TAnnotation();
_elem9.read(iprot);
struct.annotations.add(_elem9);
}
iprot.readListEnd();
}
struct.setAnnotationsIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 16: // FLAG
if (schemeField.type == org.apache.thrift.protocol.TType.I16) {
struct.flag = iprot.readI16();
struct.setFlagIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 17: // ERR
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.err = iprot.readI32();
struct.setErrIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 18: // SPAN_EVENT_LIST
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list11 = iprot.readListBegin();
struct.spanEventList = new ArrayList<TSpanEvent>(_list11.size);
TSpanEvent _elem12;
for (int _i13 = 0; _i13 < _list11.size; ++_i13)
{
_elem12 = new TSpanEvent();
_elem12.read(iprot);
struct.spanEventList.add(_elem12);
}
iprot.readListEnd();
}
struct.setSpanEventListIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 19: // PARENT_APPLICATION_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.parentApplicationName = iprot.readString();
struct.setParentApplicationNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 20: // PARENT_APPLICATION_TYPE
if (schemeField.type == org.apache.thrift.protocol.TType.I16) {
struct.parentApplicationType = iprot.readI16();
struct.setParentApplicationTypeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 21: // ACCEPTOR_HOST
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.acceptorHost = iprot.readString();
struct.setAcceptorHostIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 25: // API_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.apiId = iprot.readI32();
struct.setApiIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 26: // EXCEPTION_INFO
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.exceptionInfo = new TIntStringValue();
struct.exceptionInfo.read(iprot);
struct.setExceptionInfoIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 30: // APPLICATION_SERVICE_TYPE
if (schemeField.type == org.apache.thrift.protocol.TType.I16) {
struct.applicationServiceType = iprot.readI16();
struct.setApplicationServiceTypeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 31: // LOGGING_TRANSACTION_INFO
if (schemeField.type == org.apache.thrift.protocol.TType.BYTE) {
struct.loggingTransactionInfo = iprot.readByte();
struct.setLoggingTransactionInfoIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, TSpan struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.agentId != null) {
oprot.writeFieldBegin(AGENT_ID_FIELD_DESC);
oprot.writeString(struct.agentId);
oprot.writeFieldEnd();
}
if (struct.applicationName != null) {
oprot.writeFieldBegin(APPLICATION_NAME_FIELD_DESC);
oprot.writeString(struct.applicationName);
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(AGENT_START_TIME_FIELD_DESC);
oprot.writeI64(struct.agentStartTime);
oprot.writeFieldEnd();
if (struct.transactionId != null) {
oprot.writeFieldBegin(TRANSACTION_ID_FIELD_DESC);
oprot.writeBinary(struct.transactionId);
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(SPAN_ID_FIELD_DESC);
oprot.writeI64(struct.spanId);
oprot.writeFieldEnd();
if (struct.isSetParentSpanId()) {
oprot.writeFieldBegin(PARENT_SPAN_ID_FIELD_DESC);
oprot.writeI64(struct.parentSpanId);
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(START_TIME_FIELD_DESC);
oprot.writeI64(struct.startTime);
oprot.writeFieldEnd();
if (struct.isSetElapsed()) {
oprot.writeFieldBegin(ELAPSED_FIELD_DESC);
oprot.writeI32(struct.elapsed);
oprot.writeFieldEnd();
}
if (struct.rpc != null) {
if (struct.isSetRpc()) {
oprot.writeFieldBegin(RPC_FIELD_DESC);
oprot.writeString(struct.rpc);
oprot.writeFieldEnd();
}
}
oprot.writeFieldBegin(SERVICE_TYPE_FIELD_DESC);
oprot.writeI16(struct.serviceType);
oprot.writeFieldEnd();
if (struct.endPoint != null) {
if (struct.isSetEndPoint()) {
oprot.writeFieldBegin(END_POINT_FIELD_DESC);
oprot.writeString(struct.endPoint);
oprot.writeFieldEnd();
}
}
if (struct.remoteAddr != null) {
if (struct.isSetRemoteAddr()) {
oprot.writeFieldBegin(REMOTE_ADDR_FIELD_DESC);
oprot.writeString(struct.remoteAddr);
oprot.writeFieldEnd();
}
}
if (struct.annotations != null) {
if (struct.isSetAnnotations()) {
oprot.writeFieldBegin(ANNOTATIONS_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.annotations.size()));
for (TAnnotation _iter14 : struct.annotations)
{
_iter14.write(oprot);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
}
if (struct.isSetFlag()) {
oprot.writeFieldBegin(FLAG_FIELD_DESC);
oprot.writeI16(struct.flag);
oprot.writeFieldEnd();
}
if (struct.isSetErr()) {
oprot.writeFieldBegin(ERR_FIELD_DESC);
oprot.writeI32(struct.err);
oprot.writeFieldEnd();
}
if (struct.spanEventList != null) {
if (struct.isSetSpanEventList()) {
oprot.writeFieldBegin(SPAN_EVENT_LIST_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.spanEventList.size()));
for (TSpanEvent _iter15 : struct.spanEventList)
{
_iter15.write(oprot);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
}
if (struct.parentApplicationName != null) {
if (struct.isSetParentApplicationName()) {
oprot.writeFieldBegin(PARENT_APPLICATION_NAME_FIELD_DESC);
oprot.writeString(struct.parentApplicationName);
oprot.writeFieldEnd();
}
}
if (struct.isSetParentApplicationType()) {
oprot.writeFieldBegin(PARENT_APPLICATION_TYPE_FIELD_DESC);
oprot.writeI16(struct.parentApplicationType);
oprot.writeFieldEnd();
}
if (struct.acceptorHost != null) {
if (struct.isSetAcceptorHost()) {
oprot.writeFieldBegin(ACCEPTOR_HOST_FIELD_DESC);
oprot.writeString(struct.acceptorHost);
oprot.writeFieldEnd();
}
}
if (struct.isSetApiId()) {
oprot.writeFieldBegin(API_ID_FIELD_DESC);
oprot.writeI32(struct.apiId);
oprot.writeFieldEnd();
}
if (struct.exceptionInfo != null) {
if (struct.isSetExceptionInfo()) {
oprot.writeFieldBegin(EXCEPTION_INFO_FIELD_DESC);
struct.exceptionInfo.write(oprot);
oprot.writeFieldEnd();
}
}
if (struct.isSetApplicationServiceType()) {
oprot.writeFieldBegin(APPLICATION_SERVICE_TYPE_FIELD_DESC);
oprot.writeI16(struct.applicationServiceType);
oprot.writeFieldEnd();
}
if (struct.isSetLoggingTransactionInfo()) {
oprot.writeFieldBegin(LOGGING_TRANSACTION_INFO_FIELD_DESC);
oprot.writeByte(struct.loggingTransactionInfo);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class TSpanTupleSchemeFactory implements SchemeFactory {
public TSpanTupleScheme getScheme() {
return new TSpanTupleScheme();
}
}
private static class TSpanTupleScheme extends TupleScheme<TSpan> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, TSpan struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetAgentId()) {
optionals.set(0);
}
if (struct.isSetApplicationName()) {
optionals.set(1);
}
if (struct.isSetAgentStartTime()) {
optionals.set(2);
}
if (struct.isSetTransactionId()) {
optionals.set(3);
}
if (struct.isSetSpanId()) {
optionals.set(4);
}
if (struct.isSetParentSpanId()) {
optionals.set(5);
}
if (struct.isSetStartTime()) {
optionals.set(6);
}
if (struct.isSetElapsed()) {
optionals.set(7);
}
if (struct.isSetRpc()) {
optionals.set(8);
}
if (struct.isSetServiceType()) {
optionals.set(9);
}
if (struct.isSetEndPoint()) {
optionals.set(10);
}
if (struct.isSetRemoteAddr()) {
optionals.set(11);
}
if (struct.isSetAnnotations()) {
optionals.set(12);
}
if (struct.isSetFlag()) {
optionals.set(13);
}
if (struct.isSetErr()) {
optionals.set(14);
}
if (struct.isSetSpanEventList()) {
optionals.set(15);
}
if (struct.isSetParentApplicationName()) {
optionals.set(16);
}
if (struct.isSetParentApplicationType()) {
optionals.set(17);
}
if (struct.isSetAcceptorHost()) {
optionals.set(18);
}
if (struct.isSetApiId()) {
optionals.set(19);
}
if (struct.isSetExceptionInfo()) {
optionals.set(20);
}
if (struct.isSetApplicationServiceType()) {
optionals.set(21);
}
if (struct.isSetLoggingTransactionInfo()) {
optionals.set(22);
}
oprot.writeBitSet(optionals, 23);
if (struct.isSetAgentId()) {
oprot.writeString(struct.agentId);
}
if (struct.isSetApplicationName()) {
oprot.writeString(struct.applicationName);
}
if (struct.isSetAgentStartTime()) {
oprot.writeI64(struct.agentStartTime);
}
if (struct.isSetTransactionId()) {
oprot.writeBinary(struct.transactionId);
}
if (struct.isSetSpanId()) {
oprot.writeI64(struct.spanId);
}
if (struct.isSetParentSpanId()) {
oprot.writeI64(struct.parentSpanId);
}
if (struct.isSetStartTime()) {
oprot.writeI64(struct.startTime);
}
if (struct.isSetElapsed()) {
oprot.writeI32(struct.elapsed);
}
if (struct.isSetRpc()) {
oprot.writeString(struct.rpc);
}
if (struct.isSetServiceType()) {
oprot.writeI16(struct.serviceType);
}
if (struct.isSetEndPoint()) {
oprot.writeString(struct.endPoint);
}
if (struct.isSetRemoteAddr()) {
oprot.writeString(struct.remoteAddr);
}
if (struct.isSetAnnotations()) {
{
oprot.writeI32(struct.annotations.size());
for (TAnnotation _iter16 : struct.annotations)
{
_iter16.write(oprot);
}
}
}
if (struct.isSetFlag()) {
oprot.writeI16(struct.flag);
}
if (struct.isSetErr()) {
oprot.writeI32(struct.err);
}
if (struct.isSetSpanEventList()) {
{
oprot.writeI32(struct.spanEventList.size());
for (TSpanEvent _iter17 : struct.spanEventList)
{
_iter17.write(oprot);
}
}
}
if (struct.isSetParentApplicationName()) {
oprot.writeString(struct.parentApplicationName);
}
if (struct.isSetParentApplicationType()) {
oprot.writeI16(struct.parentApplicationType);
}
if (struct.isSetAcceptorHost()) {
oprot.writeString(struct.acceptorHost);
}
if (struct.isSetApiId()) {
oprot.writeI32(struct.apiId);
}
if (struct.isSetExceptionInfo()) {
struct.exceptionInfo.write(oprot);
}
if (struct.isSetApplicationServiceType()) {
oprot.writeI16(struct.applicationServiceType);
}
if (struct.isSetLoggingTransactionInfo()) {
oprot.writeByte(struct.loggingTransactionInfo);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, TSpan struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(23);
if (incoming.get(0)) {
struct.agentId = iprot.readString();
struct.setAgentIdIsSet(true);
}
if (incoming.get(1)) {
struct.applicationName = iprot.readString();
struct.setApplicationNameIsSet(true);
}
if (incoming.get(2)) {
struct.agentStartTime = iprot.readI64();
struct.setAgentStartTimeIsSet(true);
}
if (incoming.get(3)) {
struct.transactionId = iprot.readBinary();
struct.setTransactionIdIsSet(true);
}
if (incoming.get(4)) {
struct.spanId = iprot.readI64();
struct.setSpanIdIsSet(true);
}
if (incoming.get(5)) {
struct.parentSpanId = iprot.readI64();
struct.setParentSpanIdIsSet(true);
}
if (incoming.get(6)) {
struct.startTime = iprot.readI64();
struct.setStartTimeIsSet(true);
}
if (incoming.get(7)) {
struct.elapsed = iprot.readI32();
struct.setElapsedIsSet(true);
}
if (incoming.get(8)) {
struct.rpc = iprot.readString();
struct.setRpcIsSet(true);
}
if (incoming.get(9)) {
struct.serviceType = iprot.readI16();
struct.setServiceTypeIsSet(true);
}
if (incoming.get(10)) {
struct.endPoint = iprot.readString();
struct.setEndPointIsSet(true);
}
if (incoming.get(11)) {
struct.remoteAddr = iprot.readString();
struct.setRemoteAddrIsSet(true);
}
if (incoming.get(12)) {
{
org.apache.thrift.protocol.TList _list18 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
struct.annotations = new ArrayList<TAnnotation>(_list18.size);
TAnnotation _elem19;
for (int _i20 = 0; _i20 < _list18.size; ++_i20)
{
_elem19 = new TAnnotation();
_elem19.read(iprot);
struct.annotations.add(_elem19);
}
}
struct.setAnnotationsIsSet(true);
}
if (incoming.get(13)) {
struct.flag = iprot.readI16();
struct.setFlagIsSet(true);
}
if (incoming.get(14)) {
struct.err = iprot.readI32();
struct.setErrIsSet(true);
}
if (incoming.get(15)) {
{
org.apache.thrift.protocol.TList _list21 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
struct.spanEventList = new ArrayList<TSpanEvent>(_list21.size);
TSpanEvent _elem22;
for (int _i23 = 0; _i23 < _list21.size; ++_i23)
{
_elem22 = new TSpanEvent();
_elem22.read(iprot);
struct.spanEventList.add(_elem22);
}
}
struct.setSpanEventListIsSet(true);
}
if (incoming.get(16)) {
struct.parentApplicationName = iprot.readString();
struct.setParentApplicationNameIsSet(true);
}
if (incoming.get(17)) {
struct.parentApplicationType = iprot.readI16();
struct.setParentApplicationTypeIsSet(true);
}
if (incoming.get(18)) {
struct.acceptorHost = iprot.readString();
struct.setAcceptorHostIsSet(true);
}
if (incoming.get(19)) {
struct.apiId = iprot.readI32();
struct.setApiIdIsSet(true);
}
if (incoming.get(20)) {
struct.exceptionInfo = new TIntStringValue();
struct.exceptionInfo.read(iprot);
struct.setExceptionInfoIsSet(true);
}
if (incoming.get(21)) {
struct.applicationServiceType = iprot.readI16();
struct.setApplicationServiceTypeIsSet(true);
}
if (incoming.get(22)) {
struct.loggingTransactionInfo = iprot.readByte();
struct.setLoggingTransactionInfoIsSet(true);
}
}
}
}
|
package com.acgist.snail.context.initializer;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.acgist.snail.context.NodeContext;
import com.acgist.snail.utils.Performance;
class DhtInitializerTest extends Performance {
@Test
void testDhtInitializer() {
DhtInitializer.newInstance().sync();
assertTrue(NodeContext.getInstance().nodes().size() > 0);
}
}
|
package faceID;
public class faceGet {
private String userid;
private String faceid;
private String boosid;
/**
*get set 方法 在java文件上右键 选择 source →generate getters and setters....
*/
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getFaceid() {
return faceid;
}
public void setFaceid(String faceid) {
this.faceid = faceid;
}
public String getBoosid() {
return boosid;
}
public void setBoosid(String boosid) {
this.boosid = boosid;
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.api.protocolrecords.impl.pb;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.RefreshNodesResourcesResponseProto;
import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesResourcesResponse;
import com.google.protobuf.TextFormat;
@Private
@Unstable
public class RefreshNodesResourcesResponsePBImpl extends RefreshNodesResourcesResponse {
RefreshNodesResourcesResponseProto proto =
RefreshNodesResourcesResponseProto.getDefaultInstance();
RefreshNodesResourcesResponseProto.Builder builder = null;
boolean viaProto = false;
public RefreshNodesResourcesResponsePBImpl() {
builder = RefreshNodesResourcesResponseProto.newBuilder();
}
public RefreshNodesResourcesResponsePBImpl(
RefreshNodesResourcesResponseProto proto) {
this.proto = proto;
viaProto = true;
}
public RefreshNodesResourcesResponseProto getProto() {
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
@Override
public int hashCode() {
return getProto().hashCode();
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other.getClass().isAssignableFrom(this.getClass())) {
return this.getProto().equals(this.getClass().cast(other).getProto());
}
return false;
}
@Override
public String toString() {
return TextFormat.shortDebugString(getProto());
}
}
|
package module518packageJava0;
import java.lang.Integer;
public class Foo51 {
Integer int0;
Integer int1;
public void foo0() {
new module518packageJava0.Foo50().foo8();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
public void foo5() {
foo4();
}
public void foo6() {
foo5();
}
public void foo7() {
foo6();
}
public void foo8() {
foo7();
}
}
|
package com.kiuwan.importer.beans;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="violation")
public class Violation {
File file;
Rule rule;
public Violation() {
}
public Violation(File file, Rule rule) {
this.file = file;
this.rule = rule;
}
public File getFile() {
return file;
}
@XmlElement
public void setFile(File file) {
this.file = file;
}
public Rule getRule() {
return rule;
}
@XmlElement
public void setRule(Rule rule) {
this.rule = rule;
}
}
|
package com.hubspot.jinjava.lib.filter;
import static com.hubspot.jinjava.util.Logging.ENGINE_LOG;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.hubspot.jinjava.util.Objects;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
import com.hubspot.jinjava.objects.date.PyishDate;
public class PrettyPrintFilter implements Filter {
@Override
public String getName() {
return "pprint";
}
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
if(var == null) {
return "null";
}
String varStr = null;
if(var instanceof String || var instanceof Number || var instanceof PyishDate || var instanceof Iterable || var instanceof Map) {
varStr = Objects.toString(var);
}
else {
varStr = objPropsToString(var);
}
return StringEscapeUtils.escapeHtml4("{% raw %}(" + var.getClass().getSimpleName() + ": " + varStr + "){% endraw %}");
}
private String objPropsToString(Object var) {
List<String> props = new LinkedList<String>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(var.getClass());
for(PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
try {
if(pd.getPropertyType().equals(Class.class)) {
continue;
}
Method readMethod = pd.getReadMethod();
if(readMethod != null && !readMethod.getDeclaringClass().equals(Object.class)) {
props.add(pd.getName() + "=" + readMethod.invoke(var));
}
}
catch(Exception e) {
ENGINE_LOG.error("Error reading bean value", e);
}
}
} catch (IntrospectionException e) {
ENGINE_LOG.error("Error inspecting bean", e);
}
return '{' + StringUtils.join(props, ", ") + '}';
}
}
|
package com.wwb.gulimall.product.controller;
import java.util.Arrays;
import java.util.Map;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.wwb.gulimall.product.entity.SpuCommentEntity;
import com.wwb.gulimall.product.service.SpuCommentService;
import com.wwb.common.utils.PageUtils;
import com.wwb.common.utils.R;
/**
* 商品评价
*
* @author weiweibin
* @email weiweibin@gmail.com
* @date 2020-06-29 11:51:33
*/
@RestController
@RequestMapping("product/spucomment")
public class SpuCommentController {
@Autowired
private SpuCommentService spuCommentService;
/**
* 列表
*/
@RequestMapping("/list")
//@RequiresPermissions("product:spucomment:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = spuCommentService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
//@RequiresPermissions("product:spucomment:info")
public R info(@PathVariable("id") Long id){
SpuCommentEntity spuComment = spuCommentService.getById(id);
return R.ok().put("spuComment", spuComment);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("product:spucomment:save")
public R save(@RequestBody SpuCommentEntity spuComment){
spuCommentService.save(spuComment);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("product:spucomment:update")
public R update(@RequestBody SpuCommentEntity spuComment){
spuCommentService.updateById(spuComment);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("product:spucomment:delete")
public R delete(@RequestBody Long[] ids){
spuCommentService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
package xyz.malkki.yeeja.connection.commands;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.function.Function;
public class AdjustBright extends YeelightCommand<Void> {
private int percentage;
private int duration;
public AdjustBright(int percentage, int duration) {
this.percentage = percentage;
this.duration = duration;
}
@NotNull
@Override
public String getMethod() {
return "adjust_bright";
}
@NotNull
@Override
public Object[] getParams() {
return new Object[] { percentage, duration };
}
@NotNull
@Override
public Function<List<Object>, Void> responseParser() {
return response -> null;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.verify;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteInterruptedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.compute.ComputeJob;
import org.apache.ignite.compute.ComputeJobAdapter;
import org.apache.ignite.compute.ComputeJobResult;
import org.apache.ignite.compute.ComputeJobResultPolicy;
import org.apache.ignite.compute.ComputeTaskAdapter;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.cache.CacheGroupContext;
import org.apache.ignite.internal.processors.cache.DynamicCacheDescriptor;
import org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtLocalPartition;
import org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionState;
import org.apache.ignite.internal.processors.cache.persistence.CacheDataRow;
import org.apache.ignite.internal.processors.task.GridInternal;
import org.apache.ignite.internal.util.lang.GridIterator;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.resources.IgniteInstanceResource;
import org.apache.ignite.resources.LoggerResource;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Task for comparing update counters and checksums between primary and backup partitions of specified caches.
* <br>
* Argument: Set of cache names, 'null' will trigger verification for all caches.
* <br>
* Result: If there are any update counter conflicts (which signals about concurrent updates in
* cluster), map with all counter conflicts is returned. Otherwise, map with all hash conflicts is returned.
* Each conflict is represented by list of {@link PartitionHashRecord} with data from different nodes.
* Successful verification always returns empty map.
* <br>
* Works properly only on idle cluster - there may be false positive conflict reports if data in cluster is being
* concurrently updated.
*
* @deprecated Legacy version of {@link VerifyBackupPartitionsTaskV2}.
*/
@GridInternal
@Deprecated
public class VerifyBackupPartitionsTask extends ComputeTaskAdapter<Set<String>,
Map<PartitionKey, List<PartitionHashRecord>>> {
/** */
private static final long serialVersionUID = 0L;
/** Injected logger. */
@LoggerResource
private IgniteLogger log;
/** {@inheritDoc} */
@NotNull @Override public Map<? extends ComputeJob, ClusterNode> map(
List<ClusterNode> subgrid, Set<String> cacheNames) throws IgniteException {
Map<ComputeJob, ClusterNode> jobs = new HashMap<>();
for (ClusterNode node : subgrid)
jobs.put(new VerifyBackupPartitionsJob(cacheNames), node);
return jobs;
}
/** {@inheritDoc} */
@Nullable @Override public Map<PartitionKey, List<PartitionHashRecord>> reduce(List<ComputeJobResult> results)
throws IgniteException {
Map<PartitionKey, List<PartitionHashRecord>> clusterHashes = new HashMap<>();
for (ComputeJobResult res : results) {
Map<PartitionKey, PartitionHashRecord> nodeHashes = res.getData();
for (Map.Entry<PartitionKey, PartitionHashRecord> e : nodeHashes.entrySet()) {
if (!clusterHashes.containsKey(e.getKey()))
clusterHashes.put(e.getKey(), new ArrayList<PartitionHashRecord>());
clusterHashes.get(e.getKey()).add(e.getValue());
}
}
Map<PartitionKey, List<PartitionHashRecord>> hashConflicts = new HashMap<>();
Map<PartitionKey, List<PartitionHashRecord>> updateCntrConflicts = new HashMap<>();
for (Map.Entry<PartitionKey, List<PartitionHashRecord>> e : clusterHashes.entrySet()) {
Integer partHash = null;
Long updateCntr = null;
for (PartitionHashRecord record : e.getValue()) {
if (partHash == null) {
partHash = record.partitionHash();
updateCntr = record.updateCounter();
}
else {
if (record.updateCounter() != updateCntr) {
updateCntrConflicts.put(e.getKey(), e.getValue());
break;
}
if (record.partitionHash() != partHash) {
hashConflicts.put(e.getKey(), e.getValue());
break;
}
}
}
}
return updateCntrConflicts.isEmpty() ? hashConflicts : updateCntrConflicts;
}
/** {@inheritDoc} */
@Override public ComputeJobResultPolicy result(ComputeJobResult res, List<ComputeJobResult> rcvd) {
ComputeJobResultPolicy superRes = super.result(res, rcvd);
// Deny failover.
if (superRes == ComputeJobResultPolicy.FAILOVER) {
superRes = ComputeJobResultPolicy.WAIT;
log.warning("VerifyBackupPartitionsJob failed on node " +
"[consistentId=" + res.getNode().consistentId() + "]", res.getException());
}
return superRes;
}
/**
* Legacy version of {@link VerifyBackupPartitionsTaskV2} internal job, kept for compatibility.
*/
@Deprecated
private static class VerifyBackupPartitionsJob extends ComputeJobAdapter {
/** */
private static final long serialVersionUID = 0L;
/** Ignite instance. */
@IgniteInstanceResource
private IgniteEx ignite;
/** Injected logger. */
@LoggerResource
private IgniteLogger log;
/** Cache names. */
private Set<String> cacheNames;
/** Counter of processed partitions. */
private final AtomicInteger completionCntr = new AtomicInteger(0);
/**
* @param names Names.
*/
public VerifyBackupPartitionsJob(Set<String> names) {
cacheNames = names;
}
/** {@inheritDoc} */
@Override public Map<PartitionKey, PartitionHashRecord> execute() throws IgniteException {
Set<Integer> grpIds = new HashSet<>();
Set<String> missingCaches = new HashSet<>();
if (cacheNames != null) {
for (String cacheName : cacheNames) {
DynamicCacheDescriptor desc = ignite.context().cache().cacheDescriptor(cacheName);
if (desc == null) {
missingCaches.add(cacheName);
continue;
}
grpIds.add(desc.groupId());
}
if (!missingCaches.isEmpty()) {
StringBuilder strBuilder = new StringBuilder("The following caches do not exist: ");
for (String name : missingCaches)
strBuilder.append(name).append(", ");
strBuilder.delete(strBuilder.length() - 2, strBuilder.length());
throw new IgniteException(strBuilder.toString());
}
}
else {
Collection<CacheGroupContext> groups = ignite.context().cache().cacheGroups();
for (CacheGroupContext grp : groups) {
if (!grp.systemCache() && !grp.isLocal())
grpIds.add(grp.groupId());
}
}
List<Future<Map<PartitionKey, PartitionHashRecord>>> partHashCalcFutures = new ArrayList<>();
completionCntr.set(0);
for (Integer grpId : grpIds) {
CacheGroupContext grpCtx = ignite.context().cache().cacheGroup(grpId);
if (grpCtx == null)
continue;
List<GridDhtLocalPartition> parts = grpCtx.topology().localPartitions();
for (GridDhtLocalPartition part : parts)
partHashCalcFutures.add(calculatePartitionHashAsync(grpCtx, part));
}
Map<PartitionKey, PartitionHashRecord> res = new HashMap<>();
long lastProgressLogTs = U.currentTimeMillis();
for (int i = 0; i < partHashCalcFutures.size(); ) {
Future<Map<PartitionKey, PartitionHashRecord>> fut = partHashCalcFutures.get(i);
try {
Map<PartitionKey, PartitionHashRecord> partHash = fut.get(100, TimeUnit.MILLISECONDS);
res.putAll(partHash);
i++;
}
catch (InterruptedException | ExecutionException e) {
for (int j = i + 1; j < partHashCalcFutures.size(); j++)
partHashCalcFutures.get(j).cancel(false);
if (e instanceof InterruptedException)
throw new IgniteInterruptedException((InterruptedException)e);
else if (e.getCause() instanceof IgniteException)
throw (IgniteException)e.getCause();
else
throw new IgniteException(e.getCause());
}
catch (TimeoutException ignored) {
if (U.currentTimeMillis() - lastProgressLogTs > 3 * 60 * 1000L) {
lastProgressLogTs = U.currentTimeMillis();
log.warning("idle_verify is still running, processed " + completionCntr.get() + " of " +
partHashCalcFutures.size() + " local partitions");
}
}
}
return res;
}
/**
* @param grpCtx Group context.
* @param part Local partition.
*/
private Future<Map<PartitionKey, PartitionHashRecord>> calculatePartitionHashAsync(
final CacheGroupContext grpCtx,
final GridDhtLocalPartition part
) {
return ForkJoinPool.commonPool().submit(new Callable<Map<PartitionKey, PartitionHashRecord>>() {
@Override public Map<PartitionKey, PartitionHashRecord> call() throws Exception {
return calculatePartitionHash(grpCtx, part);
}
});
}
/**
* @param grpCtx Group context.
* @param part Local partition.
*/
private Map<PartitionKey, PartitionHashRecord> calculatePartitionHash(
CacheGroupContext grpCtx,
GridDhtLocalPartition part
) {
if (!part.reserve())
return Collections.emptyMap();
int partHash = 0;
long partSize;
long updateCntrBefore;
try {
if (part.state() != GridDhtPartitionState.OWNING)
return Collections.emptyMap();
updateCntrBefore = part.updateCounter();
partSize = part.dataStore().fullSize();
GridIterator<CacheDataRow> it = grpCtx.offheap().partitionIterator(part.id());
while (it.hasNextX()) {
CacheDataRow row = it.nextX();
partHash += row.key().hashCode();
partHash += Arrays.hashCode(row.value().valueBytes(grpCtx.cacheObjectContext()));
}
long updateCntrAfter = part.updateCounter();
if (updateCntrBefore != updateCntrAfter) {
throw new IgniteException("Cluster is not idle: update counter of partition [grpId=" +
grpCtx.groupId() + ", partId=" + part.id() + "] changed during hash calculation [before=" +
updateCntrBefore + ", after=" + updateCntrAfter + "]");
}
}
catch (IgniteCheckedException e) {
U.error(log, "Can't calculate partition hash [grpId=" + grpCtx.groupId() +
", partId=" + part.id() + "]", e);
return Collections.emptyMap();
}
finally {
part.release();
}
Object consId = ignite.context().discovery().localNode().consistentId();
boolean isPrimary = part.primary(grpCtx.topology().readyTopologyVersion());
PartitionKey partKey = new PartitionKey(grpCtx.groupId(), part.id(), grpCtx.cacheOrGroupName());
PartitionHashRecord partRec = new PartitionHashRecord(
partKey, isPrimary, consId, partHash, updateCntrBefore, partSize);
completionCntr.incrementAndGet();
return Collections.singletonMap(partKey, partRec);
}
}
}
|
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.internal.constraintvalidators.bv.time.pastorpresent;
import java.time.Instant;
import java.util.Date;
/**
* Check that the {@code java.util.Date} passed to be validated is in the
* past.
*
* @author Alaa Nassef
* @author Guillaume Smet
*/
public class PastOrPresentValidatorForDate extends AbstractPastOrPresentInstantBasedValidator<Date> {
@Override
protected Instant getInstant(Date value) {
return value.toInstant();
}
}
|
package sagan.site.guides;
import java.util.List;
import java.util.stream.Collectors;
import sagan.site.projects.Project;
import sagan.site.projects.ProjectMetadataService;
import sagan.site.support.nav.Navigation;
import sagan.site.support.nav.Section;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Controller that handles requests for getting started guide docs at /guides/gs.
*
* @see TutorialController
* @see TopicalController
*/
@Controller
@Navigation(Section.GUIDES)
@RequestMapping("/guides/gs")
class GettingStartedGuideController {
private final GettingStartedGuides guides;
private final ProjectMetadataService projectMetadataService;
@Autowired
public GettingStartedGuideController(GettingStartedGuides guides, ProjectMetadataService projectMetadataService) {
this.guides = guides;
this.projectMetadataService = projectMetadataService;
}
@GetMapping("/{guide}")
public String viewGuide(@PathVariable String guide, Model model) {
GettingStartedGuide gsGuide = this.guides.findByName(guide).get();
List<Project> projects = gsGuide.getProjects()
.stream().map(name -> this.projectMetadataService.fetchFullProject(name))
.collect(Collectors.toList());
model.addAttribute("guide", gsGuide);
model.addAttribute("projects", projects);
model.addAttribute("description", "this guide is designed to get you productive as quickly as " +
"possible and using the latest Spring project releases and techniques as recommended by the Spring team");
return "guides/gs/guide";
}
@GetMapping("/{guide}/images/{image:[a-zA-Z0-9._-]+}")
public ResponseEntity<byte[]> loadImage(@PathVariable String guide, @PathVariable String image) {
return this.guides.findByName(guide)
.flatMap(gs -> gs.getImageContent(image))
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
}
|
package com.tvd12.ezyfoxserver.event;
import com.tvd12.ezyfoxserver.entity.EzySession;
import com.tvd12.ezyfoxserver.entity.EzyUser;
import lombok.Getter;
public class EzySimpleStreamingEvent extends EzySimpleUserSessionEvent implements EzyStreamingEvent {
@Getter
private final byte[] bytes;
public EzySimpleStreamingEvent(EzyUser user, EzySession session, byte[] bytes) {
super(user, session);
this.bytes = bytes;
}
}
|
package com.kyperbox;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.BitmapFontLoader.BitmapFontParameter;
import com.badlogic.gdx.assets.loaders.ParticleEffectLoader;
import com.badlogic.gdx.assets.loaders.ParticleEffectLoader.ParticleEffectParameter;
import com.badlogic.gdx.assets.loaders.ShaderProgramLoader;
import com.badlogic.gdx.assets.loaders.ShaderProgramLoader.ShaderProgramParameter;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.viewport.FillViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.kyperbox.ads.AdClient;
import com.kyperbox.ads.MockAdClient;
import com.kyperbox.console.IDevConsole;
import com.kyperbox.console.MockDevConsole;
import com.kyperbox.dic.Localizer;
import com.kyperbox.input.GameInput;
import com.kyperbox.input.ICWrapper;
import com.kyperbox.managers.Priority.PriorityComparator;
import com.kyperbox.managers.StateManager;
import com.kyperbox.managers.TransitionManager;
import com.kyperbox.umisc.BaseGameObjectFactory;
import com.kyperbox.umisc.IGameObjectFactory;
import com.kyperbox.umisc.IGameObjectGetter;
import com.kyperbox.umisc.KyperMapLoader;
import com.kyperbox.umisc.SaveUtils;
import com.kyperbox.umisc.UserData;
public abstract class KyperBoxGame extends ApplicationAdapter {
public static String TAG = "KyperBox->";
public static final String NOT_SUPPORTED = "[NOT SUPPORTED]";
public static final String NULL_STRING = "NULL";
public static final String COLON = ":";
public static final String IMAGE_FOLDER = "image";
public static final String MUSIC_FOLDER = "music";
public static final String SFX_FOLDER = "sound";
public static final String TMX_FOLDER = "maps";
public static final String PARTICLE_FOLDER = "particles";
public static final String SHADER_FOLDER = "shaders";
public static final String GAME_ATLAS = "game.atlas";
public static final String FILE_SEPARATOR = "/";
public static final String VERTEX_SUFFIX = ".vert";
public static final String FRAGMENT_SUFFIX = ".frag";
public static final String SPACE_SEPARATOR = " ";
public static final String DASH_SEPARATOR = " - ";
public static final MapProperties NULL_PROPERTIES = new MapProperties();
public static final Array<ICWrapper> controllers = new Array<ICWrapper>();
private static ShaderProgram DEFAULT_SHADER;
public static ShaderProgram getDefaultShader() {
if (DEFAULT_SHADER == null)
DEFAULT_SHADER = SpriteBatch.createDefaultShader();
return DEFAULT_SHADER;
}
private static final String GAME_DATA_NAME = "GAME_GLOBALS";
protected Stage game_stage;
private AssetManager assets;
private Viewport view;
private SoundManager sound;
private GameState transition_state;
private ObjectMap<String, GameState> game_states;
private Array<GameState> current_gamestates;
private IGameObjectFactory object_factory;
private Preferences game_prefs;
private Color clearColor = Color.BLACK;
public static boolean DEBUG_LOGGING = true; // TURN OFF -- preface all logging with this
private InputMultiplexer input_multiplexer;
private static PriorityComparator prio_compare;
private UserData global_data;
private GameInput input;
private String game_name;
private String prefs_name;
private Localizer localizer;
private AdClient ad_client;
private IDevConsole console;
public KyperBoxGame(String prefs, String game_name, Viewport view) {
this.view = view;
this.prefs_name = prefs;
if (game_name == null)
this.game_name = this.getClass().getSimpleName();
else
this.game_name = game_name;
if (prefs_name == null)
prefs_name = this.game_name + "_data";
// WARNING ===========
}// DO NOT USE ===========
public KyperBoxGame(String game_name, Viewport view) {
this(null, game_name, view);
}
public KyperBoxGame(Viewport view) {
this(null, view);
}
public KyperBoxGame() {
this(new FillViewport(Resolutions._720.WIDTH(), Resolutions._720.HEIGHT()));
}
public String getGameName() {
return game_name;
}
public GameState getTransitionState() {
return transition_state;
}
public static PriorityComparator getPriorityComperator() {
if (prio_compare == null)
prio_compare = new PriorityComparator();
return prio_compare;
}
/**
* set the developer console - recommended to leave null for deployment
*
* @param console
*/
public void setDevConsole(IDevConsole console) {
this.console = console;
}
/**
* check if the dev console is available
*
* @return false if null or is instance of mock console
*/
public boolean isDevConsoleAvailable() {
return console != null || !(console instanceof MockDevConsole);
}
/**
* return the dev console if there is one. Otherwise return null. If you want to
* check against a boolean instead of null then try isDevConsoleAvailable()
*
* @return
*/
public IDevConsole getDevConsole() {
return console;
}
/**
* get the localization localizer object to help wtih localization. This must be
* set usign setLocalizer or it will return a useless empty one
*
* @return
*/
public Localizer getLocalizer() {
if (localizer == null)
localizer = new Localizer();
return localizer;
}
public void setLocalizer(Localizer localizer) {
this.localizer = localizer;
}
@Override
public void create() {
game_prefs = Gdx.app.getPreferences(prefs_name);
game_stage = new Stage(view);
game_states = new ObjectMap<String, GameState>();
game_stage.setDebugAll(false);
game_stage.getBatch().setShader(getDefaultShader());
current_gamestates = new Array<GameState>();
transition_state = new GameState(null);
transition_state.setGame(this);
assets = new AssetManager();
assets.setLoader(TiledMap.class, new KyperMapLoader(assets.getFileHandleResolver()));
assets.setLoader(ParticleEffect.class, new ParticleEffectLoader(assets.getFileHandleResolver()));
assets.setLoader(ShaderProgram.class,
new ShaderProgramLoader(assets.getFileHandleResolver(), VERTEX_SUFFIX, FRAGMENT_SUFFIX));
sound = new SoundManager(this);
ShaderProgram.pedantic = false;
object_factory = new BaseGameObjectFactory();
global_data = new UserData(GAME_DATA_NAME);
input = new GameInput();
if (ad_client == null)
ad_client = new MockAdClient();
if (console == null) {
console = new MockDevConsole();
}
console.create(this);
input_multiplexer = new InputMultiplexer();
if (console != null)
console.addToMultiplexer(input_multiplexer);
input_multiplexer.addProcessor(game_stage);
input_multiplexer.addProcessor(input);
Gdx.input.setInputProcessor(input_multiplexer);
initiate();
}
public void setClearColor(Color color) {
this.clearColor = color;
}
public Color getClearColor() {
return clearColor;
}
/**
* set the games adclient if one is available. mostly only for mobile- requires
* a custom implementation for each platform. Mock version will be used to avoid
* errors.
*
* @param ad_client
*/
public void setAdClient(AdClient ad_client) {
this.ad_client = ad_client;
}
/**
* get the adclient available. if none was set will return a mock version to
* maintain cross platform compatibility
*
* @return ad_client
*/
public AdClient getAdClient() {
return ad_client;
}
/**
* get the preferences used for this game
*
* @return
*/
public Preferences getGamePreferences() {
return game_prefs;
}
/**
* check if the debug render is on
*
* @return
*/
public boolean getDebugEnabled() {
return game_stage.isDebugAll();
}
/**
* enable or disable debug rendering
*
* @param enable
*/
public void debugEnabled(boolean enable) {
game_stage.setDebugAll(enable);
}
public Stage getGameStage() {
return game_stage;
}
public Viewport getView() {
return view;
}
/**
* get the global data for this game.
*
* @return
*/
public UserData getGlobals() {
return global_data;
}
/**
* save the global data to the preferences
*/
public void saveGlobals() {
SaveUtils.saveToPrefs(game_prefs, global_data);
}
/**
* try to load global data from the game preferences
*/
public void loadGlobals() {
SaveUtils.loadFromPrefs(game_prefs, global_data);
}
public GameInput getInput() {
return input;
}
public void registerGameObject(String objectname, IGameObjectGetter getter) {
this.object_factory.registerGameObject(objectname, getter);
}
protected IGameObjectFactory getObjectFactory() {
return object_factory;
}
/**
* register a game state
*
* @param name - name of the game state - this will be used for logging and
* storing data
* @param tmx - the tmx associated with this state.
* @param manager - the manager for this gamestate - this handles all the logic
*/
public void registerGameState(String name, String tmx, StateManager manager) {
game_states.put(name, new GameState(name, tmx, manager));
game_states.get(name).setGame(this);
}
/**
* register a gamestate and use its tmx file as its name
*
* @param tmx - the tmx associated with this state
* @param manager - the manager for this gamestate - this handles the logic
*/
public void registerGameState(String tmx, StateManager manager) {
registerGameState(tmx, tmx, manager);
}
/**
* register a gamestate with no name and manager
*
* @param tmx - the tmx associated with this gamestate
*/
public void registerGameState(String tmx) {
game_states.put(tmx, new GameState(tmx));
game_states.get(tmx).setGame(this);
}
/**
* clear all other states currently in the state stack and set the state to the
* one given
*
* @param state_name - the name of the gamestate to set it to
*/
public void setGameState(final String state_name) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
for (GameState gs : current_gamestates)
gs.remove();
GameState state = game_states.get(state_name);
state.init();
for (GameState gs : current_gamestates) {
if (state != gs)
gs.dispose();
}
current_gamestates.clear();
current_gamestates.add(state);
game_stage.addActor(state);
}
});
}
/**
* push a gamestate on to the state stack. Gamestates have state specific flags
* to indicate whether it should halt the update/render of the state directly
* under it
*
* @param state - the gamestate to use
*/
public void pushGameState(final GameState state) {
Gdx.app.postRunnable(new Runnable() {
public void run() {
if (current_gamestates.contains(state, true))
return;
if (current_gamestates.peek() != null)
current_gamestates.peek().disableLayers(true);
state.init();
current_gamestates.add(state);
game_stage.addActor(state);
}
});
}
/**
* * push a gamestate on to the state stack. Gamestates have state specific
* flags to indicate whether it should halt the update/render of the state
* directly under it
*
* @param state_name - the name of the gamestate to use
*/
public void pushGameState(String state_name) {
pushGameState(game_states.get(state_name));
}
/**
* pop the topmost state on the statestack
*
* @return - the popped state in case you would like to refference it
*/
public GameState popGameState() {
final GameState popped_state = current_gamestates.pop();
if (current_gamestates.size > 0 && current_gamestates.peek() != null)
current_gamestates.peek().disableLayers(false);
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
popped_state.remove();
popped_state.dispose();
}
});
return popped_state;
}
/**
* transition to another state
*
* @param state - state to transition to
* @param duration - duration of transition (*2 for in out)
* @param type - type of TransitionManager.Type
*/
public void transitionTo(String state, float duration, int type) {
if (transition_state.getManager() == null || !(transition_state.getManager() instanceof TransitionManager)) {
transition_state.setManager(new TransitionManager());
}
TransitionManager ts = (TransitionManager) transition_state.getManager();
ts.reset();
ts.setNextState(state);
ts.setTransitionType(type);
ts.setDuration(duration);
pushGameState(transition_state);
}
/**
* get the gamestate by name
*
* @param name
* @return
*/
public GameState getState(String name) {
if (game_states.containsKey(name))
return game_states.get(name);
error(TAG, "GameState-> not registerd [" + name + "].");
return null;
}
public Array<GameState> getCurrentStates() {
return current_gamestates;
}
/**
* get the sound manager
*
* @return
*/
public SoundManager getSoundManager() {
return sound;
}
/**
* get the assetmanager
*
* @return
*/
public AssetManager getAssetManager() {
return assets;
}
@Override
public void render() {
clear(clearColor);
AnimatedTiledMapTile.updateAnimationBaseTime();
game_stage.getViewport().apply();
game_stage.draw();
if (console != null) {
console.consoleDraw();
}
for (int i = 0; i < controllers.size; i++) {
if (controllers.get(i).isConnected())
controllers.get(i).update();
}
input.update();
float delta = Math.min(Gdx.graphics.getDeltaTime(), 1f);
if (console != null)
console.consoleUpdate(delta);
if (current_gamestates.size > 0)
for (int i = 0; i < current_gamestates.size; i++) {
GameState cs = current_gamestates.get(i);
if (i + 1 < current_gamestates.size) {
if (!current_gamestates.get(i + 1).haltsUpdate())
cs.act(delta);
} else
cs.act(delta);
}
}
private static void clear(Color c) {
Gdx.gl.glClearColor(c.r, c.g, c.b, c.a);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
@Override
public void dispose() {
game_stage.dispose();
assets.dispose();
if (console != null)
console.dispose();
}
// ========================================
// ASSET METHODS
// ========================================
/**
* get a shader program from the shaders folder
*
* @param name - name of the shader
* @return
*/
public ShaderProgram getShader(String name) {
return assets.get(SHADER_FOLDER + FILE_SEPARATOR + name, ShaderProgram.class);
}
/**
* get a particle effect from the particles folder
*
* @param name
* @return
*/
public ParticleEffect getParticleEffect(String name) {
return assets.get(PARTICLE_FOLDER + FILE_SEPARATOR + name, ParticleEffect.class);
}
/**
* get a sound from the sounds folder
*
* @param name
* @return
*/
public Sound getSound(String name) {
return assets.get(SFX_FOLDER + FILE_SEPARATOR + name, Sound.class);
}
/**
* get a music file from the music folder
*
* @param name
* @return
*/
public Music getMusic(String name) {
return assets.get(MUSIC_FOLDER + FILE_SEPARATOR + name, Music.class);
}
/**
* get a texture atlas from the image folder
*
* @param name
* @return
*/
public TextureAtlas getAtlas(String name) {
return assets.get(IMAGE_FOLDER + FILE_SEPARATOR + name, TextureAtlas.class);
}
/**
* get a tiledmap from the maps folder
*
* @param name
* @return
*/
public TiledMap getTiledMap(String name) {
return assets.get(TMX_FOLDER + FILE_SEPARATOR + name, TiledMap.class);
}
/**
* get a bitmap font
*
* @param name
* @return
*/
public BitmapFont getFont(String name) {
return assets.get(name, BitmapFont.class);
}
public void loadShader(String name) {
ShaderProgramParameter param = new ShaderProgramParameter();
param.fragmentFile = SHADER_FOLDER + FILE_SEPARATOR + name + FRAGMENT_SUFFIX;
param.vertexFile = SHADER_FOLDER + FILE_SEPARATOR + name + VERTEX_SUFFIX;
assets.load(SHADER_FOLDER + FILE_SEPARATOR + name, ShaderProgram.class, param);
}
public void loadParticleEffect(String name, String atlas) {
ParticleEffectParameter param = new ParticleEffectParameter();
param.atlasFile = atlas;
assets.load(PARTICLE_FOLDER + FILE_SEPARATOR + name, ParticleEffect.class, param);
}
public void loadFont(String name, String atlas) {
BitmapFontParameter bfp = new BitmapFontParameter();
bfp.atlasName = atlas;
assets.load(name, BitmapFont.class, bfp);
}
public void loadFont(String name) {
assets.load(name, BitmapFont.class);
}
public void loadSound(String name) {
assets.load(SFX_FOLDER + FILE_SEPARATOR + name, Sound.class);
}
public void loadMusic(String name) {
assets.load(MUSIC_FOLDER + FILE_SEPARATOR + name, Music.class);
}
public void loadAtlas(String name) {
assets.load(IMAGE_FOLDER + FILE_SEPARATOR + name, TextureAtlas.class);
}
public void loadTiledMap(String name) {
assets.load(TMX_FOLDER + FILE_SEPARATOR + name, TiledMap.class);
}
public static void error(String tag, String message) {
Gdx.app.error(TAG + tag, message);
}
public static void log(String tag, String message) {
Gdx.app.log(TAG + tag, message);
}
@Override
public void resize(int width, int height) {
game_stage.getViewport().update(width, height);
for (int i = 0; i < current_gamestates.size; i++) {
current_gamestates.get(i).resize(width, height);
}
if (console != null)
console.updateSize(width, height);
}
/**
* use this to register your gamestates and set the initial gamestate other
* setup type things can also be done here.
*/
public abstract void initiate();
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.cam.ceb.como.tools.periodictable;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.log4j.Logger;
/**
*
* @author pb556
*/
public class PeriodicTable {
private final static ArrayList<Element> elements = new ArrayList<Element>();
private static Logger logger = Logger.getLogger(PeriodicTable.class);
public static int getNumberOfLoneElectrons(Element e, int numOfBonds) {
return getNumberOfValenceElectrons(e) - numOfBonds;
}
public static int getNumberOfLonePairs(Element e, int numOfBonds) {
return getNumberOfLoneElectrons(e, numOfBonds) / 2;
}
public static int getNumberOfValenceElectrons(Element e) {
if (e.getGroup() < 3) {
return e.getGroup();
}
if (e.getSymbol().equals("He")) {
return 2;
}
if (e.getGroup() > 12) {
return e.getGroup() - 10;
}
if (e.getGroup() >= 3 && e.getGroup() <= 12) {
// sum up s + d for transition metals
OrbitalConfiguration s = e.getElectronConfiguration().getLastOrbital(Orbital.s);
OrbitalConfiguration d = e.getElectronConfiguration().getLastOrbital(Orbital.d);
int valEl = 0;
if (s != null) {
valEl += s.getNumberOfElectrons();
}
if (d != null) {
valEl += d.getNumberOfElectrons();
}
return valEl;
}
if (e.getGroup() == 0) {
OrbitalConfiguration f = e.getElectronConfiguration().getLastOrbital(Orbital.f);
if (f != null) {
return f.getNumberOfElectrons();
}
}
return -1;
}
public static int getNumberOfPossibleBonds(Element e) {
OrbitalConfiguration o = e.getElectronConfiguration().getLastOrbital();
return o.getOrbital().getMaxNumberOfElectrons() - o.getNumberOfElectrons();
}
public static Collection<Element> getElements() {
return elements;
}
public static Element getElementByName(String name) {
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getName().equalsIgnoreCase(name.trim())) {
return elements.get(i);
}
}
logger.error("The element with the name '" + name + "' does not exist.");
return new Element();
}
public static Element getElementBySymbol(String symbol) {
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getSymbol().equalsIgnoreCase(symbol.trim())) {
return elements.get(i);
}
}
logger.error("The element with the symbol '" + symbol + "' does not exist.");
return new Element();
}
public static Element getElementByAtomicNumber(int atomicNumber) {
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getAtomicNumber() == atomicNumber) {
return elements.get(i);
}
}
logger.error("The element with the atomic number " + atomicNumber + " does not exist.");
return new Element();
}
public static Collection<Element> getElementByClassification(ElementCategory cat) {
ArrayList<Element> selectedElements = new ArrayList<Element>();
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getElementCategory() == cat) {
selectedElements.add(elements.get(i));
}
}
return selectedElements;
}
public static Element getElementByPosition(int period, int group) {
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getPeriod() == period && elements.get(i).getGroup() == group) {
return elements.get(i);
}
}
logger.error("The position (" + period + ", " + group + ") does not define a valid element.");
return new Element();
}
public static Collection<Element> getElementByBlock(Block block) {
ArrayList<Element> selectedElements = new ArrayList<Element>();
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getBlock() == block) {
selectedElements.add(elements.get(i));
}
}
return selectedElements;
}
public static Collection<Element> getElementByPeriod(int period, Block block) {
Collection<Element> blockElements = getElementByBlock(block);
ArrayList<Element> selectedElements = new ArrayList<Element>();
for (Element e : blockElements) {
if (e.getPeriod() == period) {
selectedElements.add(e);
}
}
return selectedElements;
}
public static Collection<Element> getElementByGroup(int group, Block block) {
Collection<Element> blockElements = getElementByBlock(block);
ArrayList<Element> selectedElements = new ArrayList<Element>();
for (Element e : blockElements) {
if (e.getGroup() == group) {
selectedElements.add(e);
}
}
return selectedElements;
}
public static Collection<Element> getElementByPeriod(int period) {
ArrayList<Element> selectedElements = new ArrayList<Element>();
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getPeriod() == period) {
selectedElements.add(elements.get(i));
}
}
return selectedElements;
}
public static Collection<Element> getElementByGroup(int group) {
ArrayList<Element> selectedElements = new ArrayList<Element>();
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getGroup() == group) {
selectedElements.add(elements.get(i));
}
}
return selectedElements;
}
public static Collection<Element> getElementByAtomicNumberRange(int atomicNumberStart, int atomicNumberEnd) {
if (atomicNumberStart > atomicNumberEnd) {
int x = atomicNumberStart;
atomicNumberStart = atomicNumberEnd;
atomicNumberEnd = x;
logger.warn("Invalid indices for atomicNumberStart and atomicNumberEnd were set and had to be switched.");
}
ArrayList<Element> selectedElements = new ArrayList<Element>();
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).atomicNumber >= atomicNumberStart && elements.get(i).atomicNumber <= atomicNumberEnd) {
selectedElements.add(elements.get(i));
}
}
return selectedElements;
}
public static Collection<Element> getElementByPositionRange(int periodStart, int periodEnd, int groupStart, int groupEnd) {
if (periodStart > periodEnd) {
int x = periodStart;
periodStart = periodEnd;
periodEnd = x;
logger.warn("Invalid indices for rowStart and rowEnd were set and had to be switched.");
}
if (groupStart > groupEnd) {
int x = groupStart;
groupStart = groupEnd;
groupEnd = x;
logger.warn("Invalid indices for colStart and colEnd were set and had to be switched.");
}
ArrayList<Element> selectedElements = new ArrayList<Element>();
for (int i = 0; i < elements.size(); i++) {
if (elements.get(i).getPeriod() >= periodStart && elements.get(i).getPeriod() <= periodEnd
&& elements.get(i).getGroup() >= groupStart && elements.get(i).getGroup() <= groupEnd) {
selectedElements.add(elements.get(i));
}
}
return selectedElements;
}
static {
elements.add(PeriodicTableElements.getHydrogen());
elements.add(PeriodicTableElements.getHelium());
elements.add(PeriodicTableElements.getLithium());
elements.add(PeriodicTableElements.getBeryllium());
elements.add(PeriodicTableElements.getBoron());
elements.add(PeriodicTableElements.getCarbon());
elements.add(PeriodicTableElements.getNitrogen());
elements.add(PeriodicTableElements.getOxygen());
elements.add(PeriodicTableElements.getFluorine());
elements.add(PeriodicTableElements.getNeon());
elements.add(PeriodicTableElements.getSodium());
elements.add(PeriodicTableElements.getMagnesium());
elements.add(PeriodicTableElements.getAluminium());
elements.add(PeriodicTableElements.getSilicon());
elements.add(PeriodicTableElements.getPhosphorus());
elements.add(PeriodicTableElements.getSulphur());
elements.add(PeriodicTableElements.getChlorine());
elements.add(PeriodicTableElements.getArgon());
elements.add(PeriodicTableElements.getPotassium());
elements.add(PeriodicTableElements.getCalcium());
elements.add(PeriodicTableElements.getScandium());
elements.add(PeriodicTableElements.getTitanium());
elements.add(PeriodicTableElements.getVanadium());
elements.add(PeriodicTableElements.getChromium());
elements.add(PeriodicTableElements.getManganese());
elements.add(PeriodicTableElements.getIron());
elements.add(PeriodicTableElements.getCobalt());
elements.add(PeriodicTableElements.getNickel());
elements.add(PeriodicTableElements.getCopper());
elements.add(PeriodicTableElements.getZinc());
elements.add(PeriodicTableElements.getGallium());
elements.add(PeriodicTableElements.getGermanium());
elements.add(PeriodicTableElements.getArsenic());
elements.add(PeriodicTableElements.getSelenium());
elements.add(PeriodicTableElements.getBromine());
elements.add(PeriodicTableElements.getKrypton());
elements.add(PeriodicTableElements.getRubidium());
elements.add(PeriodicTableElements.getStrontium());
elements.add(PeriodicTableElements.getYttrium());
elements.add(PeriodicTableElements.getZirconium());
elements.add(PeriodicTableElements.getNiobium());
elements.add(PeriodicTableElements.getMolybdenum());
elements.add(PeriodicTableElements.getTechnetium());
elements.add(PeriodicTableElements.getRuthenium());
elements.add(PeriodicTableElements.getRhodium());
elements.add(PeriodicTableElements.getPalladium());
elements.add(PeriodicTableElements.getSilver());
elements.add(PeriodicTableElements.getCadmium());
elements.add(PeriodicTableElements.getIndium());
elements.add(PeriodicTableElements.getTin());
elements.add(PeriodicTableElements.getAntimony());
elements.add(PeriodicTableElements.getTellurium());
elements.add(PeriodicTableElements.getIodine());
elements.add(PeriodicTableElements.getXenon());
elements.add(PeriodicTableElements.getCaesium());
elements.add(PeriodicTableElements.getBarium());
elements.add(PeriodicTableElements.getLanthanum());
elements.add(PeriodicTableElements.getCerium());
elements.add(PeriodicTableElements.getPraseodymium());
elements.add(PeriodicTableElements.getNeodymium());
elements.add(PeriodicTableElements.getPromethium());
elements.add(PeriodicTableElements.getSamarium());
elements.add(PeriodicTableElements.getEuropium());
elements.add(PeriodicTableElements.getGadolinium());
elements.add(PeriodicTableElements.getTerbium());
elements.add(PeriodicTableElements.getDysprosium());
elements.add(PeriodicTableElements.getHolmium());
elements.add(PeriodicTableElements.getErbium());
elements.add(PeriodicTableElements.getThulium());
elements.add(PeriodicTableElements.getYtterbium());
elements.add(PeriodicTableElements.getLutetium());
elements.add(PeriodicTableElements.getHafnium());
elements.add(PeriodicTableElements.getTantalum());
elements.add(PeriodicTableElements.getTungsten());
elements.add(PeriodicTableElements.getRhenium());
elements.add(PeriodicTableElements.getOsmium());
elements.add(PeriodicTableElements.getIridium());
elements.add(PeriodicTableElements.getPlatinum());
elements.add(PeriodicTableElements.getGold());
elements.add(PeriodicTableElements.getMercury());
elements.add(PeriodicTableElements.getThallium());
elements.add(PeriodicTableElements.getLead());
elements.add(PeriodicTableElements.getBismuth());
elements.add(PeriodicTableElements.getPolonium());
elements.add(PeriodicTableElements.getAstatine());
elements.add(PeriodicTableElements.getRadon());
elements.add(PeriodicTableElements.getFrancium());
elements.add(PeriodicTableElements.getRadium());
elements.add(PeriodicTableElements.getActinium());
elements.add(PeriodicTableElements.getThorium());
elements.add(PeriodicTableElements.getProtactinium());
elements.add(PeriodicTableElements.getUranium());
elements.add(PeriodicTableElements.getNeptunium());
elements.add(PeriodicTableElements.getPlutonium());
elements.add(PeriodicTableElements.getAmericium());
elements.add(PeriodicTableElements.getCurium());
elements.add(PeriodicTableElements.getBerkelium());
elements.add(PeriodicTableElements.getCalifornium());
elements.add(PeriodicTableElements.getEinsteinium());
elements.add(PeriodicTableElements.getFermium());
elements.add(PeriodicTableElements.getMendelevium());
elements.add(PeriodicTableElements.getNobelium());
elements.add(PeriodicTableElements.getLawrencium());
elements.add(PeriodicTableElements.getRutherfordium());
elements.add(PeriodicTableElements.getDubnium());
elements.add(PeriodicTableElements.getSeaborgium());
elements.add(PeriodicTableElements.getBohrium());
elements.add(PeriodicTableElements.getHassium());
elements.add(PeriodicTableElements.getMeitnerium());
elements.add(PeriodicTableElements.getDarmstadtium());
elements.add(PeriodicTableElements.getRoentgenium());
elements.add(PeriodicTableElements.getCopernicium());
elements.add(PeriodicTableElements.getUnuntrium());
elements.add(PeriodicTableElements.getFlerovium());
elements.add(PeriodicTableElements.getUnunpentium());
elements.add(PeriodicTableElements.getLivermorium());
elements.add(PeriodicTableElements.getUnunseptium());
elements.add(PeriodicTableElements.getUnunoctium());
}
}
|
/* file: NumericTableInputId.java */
/*******************************************************************************
* Copyright 2014-2017 Intel Corporation
* All Rights Reserved.
*
* If this software was obtained under the Intel Simplified Software License,
* the following terms apply:
*
* The source code, information and material ("Material") contained herein is
* owned by Intel Corporation or its suppliers or licensors, and title to such
* Material remains with Intel Corporation or its suppliers or licensors. The
* Material contains proprietary information of Intel or its suppliers and
* licensors. The Material is protected by worldwide copyright laws and treaty
* provisions. No part of the Material may be used, copied, reproduced,
* modified, published, uploaded, posted, transmitted, distributed or disclosed
* in any way without Intel's prior express written permission. No license under
* any patent, copyright or other intellectual property rights in the Material
* is granted to or conferred upon you, either expressly, by implication,
* inducement, estoppel or otherwise. Any license under such intellectual
* property rights must be express and approved by Intel in writing.
*
* Unless otherwise agreed by Intel in writing, you may not remove or alter this
* notice or any other notice embedded in Materials by Intel or Intel's
* suppliers or licensors in any way.
*
*
* If this software was obtained under the Apache License, Version 2.0 (the
* "License"), the following terms apply:
*
* 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.
*******************************************************************************/
/**
* @ingroup implicit_als_training_distributed
* @{
*/
package com.intel.daal.algorithms.implicit_als.training;
/**
* <a name="DAAL-CLASS-ALGORITHMS__IMPLICIT_ALS__TRAINING__NUMERICTABLEINPUTID"></a>
* @brief Available identifiers of input numeric table objects for the implicit ALS
* training algorithm in the distributed processing mode
*/
public final class NumericTableInputId {
private int _value;
static {
System.loadLibrary("JavaAPI");
}
/**
* Constructs the input numeric table object identifier using the provided value
* @param value Value corresponding to the input numeric table object identifier
*/
public NumericTableInputId(int value) {
_value = value;
}
/**
* Returns the value corresponding to the input numeric table object identifier
* @return Value corresponding to the input numeric table object identifier
*/
public int getValue() {
return _value;
}
private static final int dataId = 0;
/** %Input data table */
public static final NumericTableInputId data = new NumericTableInputId(
dataId); /*!< %Input data table that contains ratings */
}
/** @} */
|
/*
* Copyright 2012-2013 eBay Software Foundation and ios-driver committers
*
* 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.uiautomation.ios.wkrdp.internal;
import com.google.common.collect.ImmutableMap;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.WebDriverException;
import org.uiautomation.ios.ServerSideSession;
import org.uiautomation.ios.utils.PlistManager;
import org.uiautomation.ios.wkrdp.MessageHandler;
import org.uiautomation.ios.wkrdp.MessageListener;
import org.uiautomation.ios.wkrdp.RemoteExceptionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Communication logic for the WKRDP to connect to an app, and to a specific webview inside that
* app.
*
* @see WebKitRemoteDebugProtocol#sendWebkitCommand(org.json.JSONObject, int) to use the protocol
* itself.
*/
public abstract class WebKitRemoteDebugProtocol {
private static final Logger log = Logger.getLogger(WebKitRemoteDebugProtocol.class.getName());
protected final MessageHandler handler;
private Thread listen;
private String connectionId;
private String bundleId;
private final PlistManager plist = new PlistManager();
private final static String senderBase = "E0F4C128-F4FF-4D45-A538-BA382CD660";
private int commandId = 0;
private volatile boolean keepGoing = true;
private volatile boolean readyToBeStopped = true;
public abstract void start();
public abstract void stop();
protected abstract void read() throws Exception;
protected abstract void sendMessage(String message);
protected void startListenerThread() {
listen = new Thread(new Runnable() {
@Override
public void run() {
try {
readyToBeStopped = false;
keepGoing = true;
while (keepGoing) {
read();
sleepTight(50);
}
} catch (Exception e) {
log.log(Level.WARNING, "listener thread", e);
} finally {
readyToBeStopped = true;
}
}
});
listen.start();
}
public WebKitRemoteDebugProtocol(ServerSideSession session) {
this.handler = new DefaultMessageHandler(session);
}
public void addListener(MessageListener listener) {
handler.addListener(listener);
}
public String getConnectionId() {
return connectionId;
}
public void register() {
if (connectionId != null) {
throw new WebDriverException("Session already created.");
}
connectionId = UUID.randomUUID().toString();
Map<String, String> var = ImmutableMap.of("$WIRConnectionIdentifierKey", connectionId);
sendSystemCommand(PlistManager.SET_CONNECTION_KEY, var);
}
public void connect(String bundleId) {
if (connectionId == null) {
throw new WebDriverException("Cannot connect to app " + bundleId + ".Call register first.");
}
Map<String, String> var = ImmutableMap.of
(
"$WIRConnectionIdentifierKey", this.connectionId,
"$bundleId", bundleId
);
sendSystemCommand(PlistManager.CONNECT_TO_APP, var);
this.bundleId = bundleId;
}
public void attachToPage(int pageId) {
String senderKey = generateSenderString(pageId);
if (connectionId == null || bundleId == null) {
throw new WebDriverException("You need to call register and connect first.");
}
Map<String, String> var = ImmutableMap.of
(
"$WIRConnectionIdentifierKey", connectionId,
"$bundleId", bundleId,
"$WIRSenderKey", senderKey,
"$WIRPageIdentifierKey", "" + pageId
);
sendSystemCommand(PlistManager.SET_SENDER_KEY, var);
}
private void sendSystemCommand(String templateName, Map<String, String> variables) {
String xml = plist.loadFromTemplate(templateName);
for (String key : variables.keySet()) {
xml = xml.replace(key, variables.get(key));
}
sendMessage(xml);
}
public synchronized JSONObject sendWebkitCommand(JSONObject command, int pageId) {
String sender = generateSenderString(pageId);
try {
commandId++;
command.put("id", commandId);
long start = System.currentTimeMillis();
String xml = plist.JSONCommand(command);
Map<String, String> var = ImmutableMap.of
(
"$WIRConnectionIdentifierKey", connectionId,
"$bundleId", bundleId,
"$WIRSenderKey", sender,
"$WIRPageIdentifierKey", "" + pageId
);
for (String key : var.keySet()) {
xml = xml.replace(key, var.get(key));
}
Future<JSONObject> future = this.handler.createMessageFuture(commandId);
sendMessage(xml);
JSONObject response;
try {
response = future.get(60, TimeUnit.SECONDS);
} catch (TimeoutException | InterruptedException | ExecutionException e) {
throw new WebDriverException("Problem getting webdriver command response", e);
}
JSONObject error = response.optJSONObject("error");
if (error != null) {
throw new RemoteExceptionException(error, command);
} else if (response.optBoolean("wasThrown", false)) {
throw new WebDriverException("remote JS exception " + response.toString(2));
} else {
if (log.isLoggable(Level.FINE)) {
log.fine(
System.currentTimeMillis() + "\t\t" + (System.currentTimeMillis() - start) + "ms\t"
+ command.getString("method") + " " + command);
}
JSONObject res = response.getJSONObject("result");
if (res == null) {
System.err.println("GOT a null result from " + response.toString(2));
}
return res;
}
} catch (JSONException e) {
throw new WebDriverException(e);
} catch (NullPointerException e) {
throw new WebDriverException("the server didn't respond. Is the app still alive ?");
}
}
private String generateSenderString(int pageIdentifierKey) {
if (pageIdentifierKey < 10) {
return senderBase + "0" + pageIdentifierKey;
} else {
return senderBase + pageIdentifierKey;
}
}
public void stopListenerThread() {
if (handler != null) {
handler.stop();
}
keepGoing = false;
if (listen != null) {
listen.interrupt();
}
while (!readyToBeStopped) {
sleepTight(50);
}
}
private static void sleepTight(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ignore) {
//Thread.currentThread().interrupt();
}
}
}
|
/**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2019 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.pnc.mapper.api;
import org.jboss.pnc.dto.SCMRepository;
import org.jboss.pnc.model.RepositoryConfiguration;
import org.mapstruct.BeanMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
/**
*
* @author Honza Brázdil <jbrazdil@redhat.com>
*/
@Mapper(config = MapperCentralConfig.class)
public interface SCMRepositoryMapper extends EntityMapper<Integer, RepositoryConfiguration, SCMRepository, SCMRepository> {
@Override
@Mapping(target="internalUrlNormalized", ignore = true)
@Mapping(target="externalUrlNormalized", ignore = true)
@Mapping(target="buildConfigurations", ignore = true)
RepositoryConfiguration toEntity(SCMRepository dtoEntity);
@Override
@IdEntity
default RepositoryConfiguration toIDEntity(SCMRepository dtoEntity) {
if (dtoEntity == null) {
return null;
}
RepositoryConfiguration entity = new RepositoryConfiguration();
entity.setId(Integer.valueOf(dtoEntity.getId()));
return entity;
}
@Override
@Reference
default SCMRepository toRef(RepositoryConfiguration dbEntity){
return toDTO(dbEntity);
}
@Override
@BeanMapping(ignoreUnmappedSourceProperties = {"internalUrlNormalized", "externalUrlNormalized",
"buildConfigurations"})
SCMRepository toDTO(RepositoryConfiguration dbEntity);
}
|
package com.maybetm.configuration;
/**
* @author zebzeev-sv
* @version 14.10.2019 19:43
*/
public abstract class TestHelper {
public static void configProxy() {
configProxy("192.168.54.10", "3128");
}
private static void configProxy(String host, String port) {
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", port);
System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", port);
}
}
|
/*
* Copyright © 2015 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jcanephora.core;
/**
* Exception class representing an error caused by the programmer trying to
* re-bind an index buffer on an array object other than the default.
*/
public final class JCGLExceptionIndexBufferAlreadyConfigured extends JCGLException
{
private static final long serialVersionUID = 1L;
/**
* Construct an exception.
*
* @param message The message
*/
public JCGLExceptionIndexBufferAlreadyConfigured(
final String message)
{
super(message);
}
}
|
package com.walmartlabs.concord.it.tasks.serializationtest;
/*-
* *****
* Concord
* -----
* Copyright (C) 2017 - 2018 Walmart 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.
* =====
*/
import com.walmartlabs.concord.sdk.Context;
import com.walmartlabs.concord.sdk.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Named;
@Named("serializationTest")
public class SerializationTestTask implements Task {
private static final Logger log = LoggerFactory.getLogger(SerializationTestTask.class);
@Override
public void execute(Context ctx) {
log.info("Setting a variable...");
ctx.setVariable("test", new NonSerializableThingy("Hello!"));
}
}
|
package com.esotericsoftware.SpineStandard.utils;
public class SpineUtils {
static public final float PI = 3.1415927f;
static public final float PI2 = PI * 2;
static public final float radiansToDegrees = 180f / PI;
static public final float radDeg = radiansToDegrees;
static public final float degreesToRadians = PI / 180;
static public final float degRad = degreesToRadians;
public static float cosDeg(float angle) {
return (float) Math.cos(angle * degRad);
}
public static float sinDeg(float angle) {
return (float) Math.sin(angle * degRad);
}
public static float cos(float angle) {
return (float) Math.cos(angle);
}
public static float sin(float angle) {
return (float) Math.sin(angle);
}
public static float atan2(float y, float x) {
return (float) Math.atan2(y, x);
}
static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) {
if (src == null) throw new IllegalArgumentException("src cannot be null.");
if (dest == null) throw new IllegalArgumentException("dest cannot be null.");
try {
System.arraycopy(src, srcPos, dest, destPos, length);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new ArrayIndexOutOfBoundsException( //
"Src: " + java.lang.reflect.Array.getLength(src) + ", " + srcPos //
+ ", dest: " + java.lang.reflect.Array.getLength(dest) + ", " + destPos //
+ ", count: " + length);
}
}
}
|
package application;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import model.dao.DaoFactory;
import model.dao.SellerDao;
import model.entities.Department;
import model.entities.Seller;
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SellerDao sellerDao = DaoFactory.createSellerDao();
System.out.println("=== TEST 1: seller findById =====");
Seller seller = sellerDao.findById(4);
System.out.println(seller);
System.out.println("\n=== TEST 2: seller findByDepartment =====");
Department department = new Department(2, null);
List<Seller> list = sellerDao.findByDepartment(department);
for(Seller obj : list) {
System.out.println(obj);
}
System.out.println("\n=== TEST 3: seller findAll =====");
list = sellerDao.findAll();
for(Seller obj : list) {
System.out.println(obj);
}
System.out.println("\n=== TEST 4: seller findAll =====");
Seller newSeller = new Seller(null, "Greg", "greg@gmail.com", new Date(), 4000.0, department);
sellerDao.insert(newSeller);
System.out.println("Inserted! New id = " + newSeller.getId());
System.out.println("\n=== TEST 5: seller update =====");
seller = sellerDao.findById(1);
seller.setName("Marta Waine");
sellerDao.update(seller);
System.out.println("Update completed");
System.out.println("\n=== TEST 6: seller delete =====");
System.out.print("Enter id for delete test: ");
int id = sc.nextInt();
sellerDao.deleteById(id);
System.out.println("Delete completed");
sc.close();
}
}
|
package com.atguigu.gmall.sms.controller;
import java.util.List;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.atguigu.gmall.sms.entity.CouponSpuEntity;
import com.atguigu.gmall.sms.service.CouponSpuService;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.bean.PageParamVo;
/**
* 优惠券与产品关联
*
* @author taoge
* @email taoge@atguigu.com
* @date 2021-06-22 19:40:26
*/
@Api(tags = "优惠券与产品关联 管理")
@RestController
@RequestMapping("sms/couponspu")
public class CouponSpuController {
@Autowired
private CouponSpuService couponSpuService;
/**
* 列表
*/
@GetMapping
@ApiOperation("分页查询")
public ResponseVo<PageResultVo> queryCouponSpuByPage(PageParamVo paramVo){
PageResultVo pageResultVo = couponSpuService.queryPage(paramVo);
return ResponseVo.ok(pageResultVo);
}
/**
* 信息
*/
@GetMapping("{id}")
@ApiOperation("详情查询")
public ResponseVo<CouponSpuEntity> queryCouponSpuById(@PathVariable("id") Long id){
CouponSpuEntity couponSpu = couponSpuService.getById(id);
return ResponseVo.ok(couponSpu);
}
/**
* 保存
*/
@PostMapping
@ApiOperation("保存")
public ResponseVo<Object> save(@RequestBody CouponSpuEntity couponSpu){
couponSpuService.save(couponSpu);
return ResponseVo.ok();
}
/**
* 修改
*/
@PostMapping("/update")
@ApiOperation("修改")
public ResponseVo update(@RequestBody CouponSpuEntity couponSpu){
couponSpuService.updateById(couponSpu);
return ResponseVo.ok();
}
/**
* 删除
*/
@PostMapping("/delete")
@ApiOperation("删除")
public ResponseVo delete(@RequestBody List<Long> ids){
couponSpuService.removeByIds(ids);
return ResponseVo.ok();
}
}
|
package com.kexin.mall.coupon.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.math.BigDecimal;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 商品会员价格
*
* @author kexinwen
* @email kexinwen.ca@gmail.com
* @date 2021-03-28 18:44:17
*/
@Data
@TableName("sms_member_price")
public class MemberPriceEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* sku_id
*/
private Long skuId;
/**
* 会员等级id
*/
private Long memberLevelId;
/**
* 会员等级名
*/
private String memberLevelName;
/**
* 会员对应价格
*/
private BigDecimal memberPrice;
/**
* 可否叠加其他优惠[0-不可叠加优惠,1-可叠加]
*/
private Integer addOther;
}
|
/*
* Copyright 2000-2016 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.codeInsight.daemon;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.LocalInspectionToolSession;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.JavaElementVisitor;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiIdentifier;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class HighlightSeverityTest extends LightDaemonAnalyzerTestCase {
@NonNls static final String BASE_PATH = "/codeInsight/daemonCodeAnalyzer/highlightSeverity";
public void testErrorLikeUnusedSymbol() throws Exception {
enableInspectionTool(new LocalInspectionTool() {
@NotNull
@Override
public String getShortName() {
return getDisplayName();
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder,
boolean isOnTheFly,
@NotNull LocalInspectionToolSession session) {
return new JavaElementVisitor() {
@Override
public void visitIdentifier(PsiIdentifier identifier) {
if (identifier.getText().equals("k")) {
holder.registerProblem(identifier, "Variable 'k' is never used");
}
}
};
}
@NotNull
@Override
public HighlightDisplayLevel getDefaultLevel() {
return HighlightDisplayLevel.ERROR;
}
@Nls
@NotNull
@Override
public String getDisplayName() {
return "x";
}
@Nls
@NotNull
@Override
public String getGroupDisplayName() {
return getDisplayName();
}
});
doTest(BASE_PATH + "/" + getTestName(false) + ".java", true, false);
}
}
|
/**
* Copyright (C) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject;
import com.google.common.collect.ImmutableSet;
import com.google.inject.internal.MoreTypesTest;
import com.google.inject.internal.UniqueAnnotationsTest;
import com.google.inject.internal.WeakKeySetTest;
import com.google.inject.internal.util.LineNumbersTest;
import com.google.inject.matcher.MatcherTest;
import com.google.inject.name.NamedEquivalanceTest;
import com.google.inject.name.NamesTest;
import com.google.inject.spi.BindingTargetVisitorTest;
import com.google.inject.spi.ElementApplyToTest;
import com.google.inject.spi.ElementSourceTest;
import com.google.inject.spi.ElementsTest;
import com.google.inject.spi.HasDependenciesTest;
import com.google.inject.spi.InjectionPointTest;
import com.google.inject.spi.InjectorSpiTest;
import com.google.inject.spi.ModuleAnnotatedMethodScannerTest;
import com.google.inject.spi.ModuleRewriterTest;
import com.google.inject.spi.ModuleSourceTest;
import com.google.inject.spi.ProviderMethodsTest;
import com.google.inject.spi.SpiBindingsTest;
import com.google.inject.spi.ToolStageInjectorTest;
import com.google.inject.util.NoopOverrideTest;
import com.google.inject.util.OverrideModuleTest;
import com.google.inject.util.ProvidersTest;
import com.google.inject.util.TypesTest;
import com.googlecode.guice.GuiceTck;
import com.googlecode.guice.Jsr330Test;
import junit.framework.Test;
import junit.framework.TestSuite;
import java.util.Set;
/**
* @author crazybob@google.com (Bob Lee)
*/
public class AllTests {
private static final Set<String> SUPPRESSED_TEST_NAMES = ImmutableSet.of(
"testUnscopedProviderWorksOutsideOfRequestedScope(" + ScopesTest.class.getName() + ")",
"testCannotConvertUnannotatedBindings(" + TypeConversionTest.class.getName() + ")"
);
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(GuiceTck.suite());
suite.addTestSuite(BinderTest.class);
suite.addTest(BinderTestSuite.suite());
suite.addTestSuite(BindingAnnotationTest.class);
suite.addTestSuite(BindingOrderTest.class);
suite.addTestSuite(BindingTest.class);
suite.addTestSuite(BoundInstanceInjectionTest.class);
suite.addTestSuite(BoundProviderTest.class);
suite.addTestSuite(CircularDependencyTest.class);
suite.addTestSuite(DuplicateBindingsTest.class);
// ErrorHandlingTest.class is not a testcase
suite.addTestSuite(EagerSingletonTest.class);
suite.addTestSuite(GenericInjectionTest.class);
suite.addTestSuite(ImplicitBindingTest.class);
suite.addTestSuite(TypeListenerTest.class);
suite.addTestSuite(InjectorTest.class);
suite.addTestSuite(JitBindingsTest.class);
// IntegrationTest is AOP-only
suite.addTestSuite(KeyTest.class);
suite.addTestSuite(LoggerInjectionTest.class);
// MethodInterceptionTest is AOP-only
suite.addTestSuite(MembersInjectorTest.class);
suite.addTestSuite(ModulesTest.class);
suite.addTestSuite(ModuleTest.class);
suite.addTestSuite(ModuleAnnotatedMethodScannerTest.class);
suite.addTestSuite(NullableInjectionPointTest.class);
suite.addTestSuite(OptionalBindingTest.class);
suite.addTestSuite(OverrideModuleTest.class);
suite.addTestSuite(ParentInjectorTest.class);
suite.addTestSuite(PrivateModuleTest.class);
suite.addTestSuite(ProviderInjectionTest.class);
suite.addTestSuite(ProvisionExceptionTest.class);
suite.addTestSuite(ProvisionListenerTest.class);
// ProxyFactoryTest is AOP-only
suite.addTestSuite(ReflectionTest.class);
suite.addTestSuite(RequestInjectionTest.class);
suite.addTestSuite(RequireAtInjectOnConstructorsTest.class);
suite.addTestSuite(ScopesTest.class);
suite.addTestSuite(SerializationTest.class);
suite.addTestSuite(SuperclassTest.class);
suite.addTestSuite(TypeConversionTest.class);
suite.addTestSuite(TypeLiteralInjectionTest.class);
suite.addTestSuite(TypeLiteralTest.class);
suite.addTestSuite(TypeLiteralTypeResolutionTest.class);
suite.addTestSuite(WeakKeySetTest.class);
// internal
suite.addTestSuite(LineNumbersTest.class);
suite.addTestSuite(MoreTypesTest.class);
suite.addTestSuite(UniqueAnnotationsTest.class);
// matcher
suite.addTestSuite(MatcherTest.class);
// names
suite.addTestSuite(NamesTest.class);
suite.addTestSuite(NamedEquivalanceTest.class);
// spi
suite.addTestSuite(BindingTargetVisitorTest.class);
suite.addTestSuite(ElementsTest.class);
suite.addTestSuite(ElementApplyToTest.class);
suite.addTestSuite(HasDependenciesTest.class);
suite.addTestSuite(InjectionPointTest.class);
suite.addTestSuite(InjectorSpiTest.class);
suite.addTestSuite(ModuleRewriterTest.class);
suite.addTestSuite(ProviderMethodsTest.class);
suite.addTestSuite(SpiBindingsTest.class);
suite.addTestSuite(ToolStageInjectorTest.class);
suite.addTestSuite(ModuleSourceTest.class);
suite.addTestSuite(ElementSourceTest.class);
// tools
// suite.addTestSuite(JmxTest.class); not a testcase
// util
suite.addTestSuite(NoopOverrideTest.class);
suite.addTestSuite(ProvidersTest.class);
suite.addTestSuite(TypesTest.class);
/*if[AOP]*/
suite.addTestSuite(com.google.inject.internal.ProxyFactoryTest.class);
suite.addTestSuite(IntegrationTest.class);
suite.addTestSuite(MethodInterceptionTest.class);
suite.addTestSuite(com.googlecode.guice.BytecodeGenTest.class);
/*end[AOP]*/
// googlecode.guice
suite.addTestSuite(com.googlecode.guice.OSGiContainerTest.class);
suite.addTestSuite(Jsr330Test.class);
return SuiteUtils.removeSuppressedTests(suite, SUPPRESSED_TEST_NAMES);
}
}
|
/**
*
* Copyright 2015 Florian Schmaus
*
* 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.jivesoftware.smack;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import org.jivesoftware.smack.sasl.SASLError;
import org.jivesoftware.smack.sasl.SASLErrorException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smack.util.StringUtils;
import org.igniterealtime.smack.inttest.AbstractSmackLowLevelIntegrationTest;
import org.igniterealtime.smack.inttest.SmackIntegrationTest;
import org.igniterealtime.smack.inttest.SmackIntegrationTestEnvironment;
public class LoginIntegrationTest extends AbstractSmackLowLevelIntegrationTest {
public LoginIntegrationTest(SmackIntegrationTestEnvironment environment) {
super(environment);
}
/**
* Check that the server is returning the correct error when trying to login using an invalid
* (i.e. non-existent) user.
*
* @throws InterruptedException
* @throws XMPPException
* @throws IOException
* @throws SmackException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
@SmackIntegrationTest
public void testInvalidLogin() throws SmackException, IOException, XMPPException,
InterruptedException, KeyManagementException, NoSuchAlgorithmException {
final String nonExistentUserString = StringUtils.insecureRandomString(24);
XMPPTCPConnectionConfiguration conf = getConnectionConfiguration().setUsernameAndPassword(
nonExistentUserString, "invalidPassword").build();
XMPPTCPConnection connection = new XMPPTCPConnection(conf);
connection.connect();
try {
connection.login();
fail("Exception expected");
}
catch (SASLErrorException e) {
assertEquals(SASLError.not_authorized, e.getSASLFailure().getSASLError());
}
}
}
|
package alpha.proyectos.is2.fpuna.py.alpha.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.UUID;
import alpha.proyectos.is2.fpuna.py.alpha.R;
import alpha.proyectos.is2.fpuna.py.alpha.service.ProyectoService;
import alpha.proyectos.is2.fpuna.py.alpha.service.ServiceBuilder;
import alpha.proyectos.is2.fpuna.py.alpha.utils.PreferenceUtils;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DatosProyectoActivity extends AppCompatActivity {
private ProyectoService service;
private String idProyecto;
final PreferenceUtils preferenceUtils = new PreferenceUtils(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datos_proyecto);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
service = (ProyectoService) ServiceBuilder.create(ProyectoService.class, preferenceUtils.getAuthToken());
idProyecto = getIntent().getStringExtra("EXTRA_ID_PROYECTO");
final String nombre = getIntent().getStringExtra("EXTRA_NOMBRE");
final String estado = getIntent().getStringExtra("EXTRA_ESTADO");
final String categoria = getIntent().getStringExtra("EXTRA_CATEGORIA");
final String descripcion = getIntent().getStringExtra("EXTRA_DESCRIPCION");
final String fechaCreacion = getIntent().getStringExtra("EXTRA_FECHA_CREACION");
final String fechaFin = getIntent().getStringExtra("EXTRA_FECHA_FIN");
final String idPropietario = getIntent().getStringExtra("EXTRA_ID_PROPIETARIO");
final String propietario = getIntent().getStringExtra("EXTRA_NOMBRE_PROPIETARIO");
TextView nombreView = (TextView) findViewById(R.id.nombre);
nombreView.setText(nombre);
TextView propietarioView = (TextView) findViewById(R.id.propietario);
propietarioView.setText(propietario);
TextView descripcionView = (TextView) findViewById(R.id.descripcion);
descripcionView.setText(descripcion);
TextView estadoView = (TextView) findViewById(R.id.estado);
estadoView.setText(estado);
TextView categoriaView = (TextView) findViewById(R.id.categoria);
categoriaView.setText(categoria);
TextView fechaCreacionView = (TextView) findViewById(R.id.fechaCreacion);
fechaCreacionView.setText(fechaCreacion);
TextView fechaFinView = (TextView) findViewById(R.id.fechaFin);
fechaFinView.setText(fechaFin);
Button editarBtn = (Button) findViewById(R.id.button_editar);
editarBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(DatosProyectoActivity.this, EditarProyectoActivity.class);
intent.putExtra("EXTRA_ID_PROYECTO", idProyecto);
intent.putExtra("EXTRA_NOMBRE", nombre);
intent.putExtra("EXTRA_ESTADO", estado);
intent.putExtra("EXTRA_FECHA_CREACION", fechaCreacion);
intent.putExtra("EXTRA_DESCRIPCION", descripcion);
intent.putExtra("EXTRA_FECHA_FIN", fechaFin);
intent.putExtra("EXTRA_ID_PROPIETARIO", idPropietario);
intent.putExtra("EXTRA_NOMBRE_PROPIETARIO", propietario);
startActivity(intent);
}
});
/*Button verHitosBtn = (Button) findViewById(R.id.ver_hitos_btn);
verHitosBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DatosProyectoActivity.this, ListaHitosActivity.class);
i.putExtra("EXTRA_ID_PROYECTO", idProyecto);
startActivity(i);
}
});*/
Button eliminarBtn = (Button) findViewById(R.id.button_eliminar);
eliminarBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showMessageSuccess("Confirmar", "Esta seguro que desea eliminar el Proyecto ?");
}
});
View.OnClickListener verHitosListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DatosProyectoActivity.this, ListaHitosActivity.class);
i.putExtra("EXTRA_ID_PROYECTO", idProyecto);
startActivity(i);
}
};
TextView verHitos = (TextView) findViewById(R.id.ver_hitos);
verHitos.setOnClickListener(verHitosListener);
ImageView linkHitos = (ImageView) findViewById(R.id.ver_hitos_link);
linkHitos.setOnClickListener(verHitosListener);
/*View.OnClickListener verTareasListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DatosProyectoActivity.this, ListaTareasActivity.class);
i.putExtra("EXTRA_ID_PROYECTO", idProyecto);
startActivity(i);
}
};
TextView verTareas = (TextView) findViewById(R.id.ver_tareas);
verTareas.setOnClickListener(verTareasListener);
ImageView linkTareas = (ImageView) findViewById(R.id.ver_tareas_link);
linkTareas.setOnClickListener(verTareasListener);*/
View.OnClickListener verSolicitudesListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(DatosProyectoActivity.this, SolicitudesActivity.class);
i.putExtra("EXTRA_ID_PROYECTO", idProyecto);
startActivity(i);
}
};
TextView verSolicitudes = (TextView) findViewById(R.id.ver_solicitudes);
verSolicitudes.setOnClickListener(verSolicitudesListener);
ImageView linkSolicitudes = (ImageView) findViewById(R.id.ver_solicitudes_link);
linkSolicitudes.setOnClickListener(verSolicitudesListener);
}
private void showMessageSuccess(String titulo, String mensaje) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(mensaje).setTitle(titulo);
builder.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
UUID uuid = UUID.fromString(idProyecto);
Call<ResponseBody> call = service.eliminar(uuid);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
showMessageSuccess("Exitoso", "Proyecto eliminado exitosamente");
} else {
showMessage("Error", "Ocurrio un error al realizar la operación");
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
showMessage("Error", "Ocurrio un error al realizar la operación");
}
});
System.err.println("Error editar proyecto, eliminar proyecto");
}
});
builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
System.err.println("Error editar proyecto, NO eliminar proyecto");
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void showMessage(String titulo, String mensaje) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(mensaje).setTitle(titulo);
builder.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
|
package indi.pet.chatting.util;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author <a href="maimengzzz@gmail.com">韩超</a>
* @since 2018.11.05
*/
public class MD5Util {
private static String toHex(byte[] bytes){
final char[] HEX_DIGITS="0123456789ABCDEF".toCharArray();
StringBuilder ret=new StringBuilder(bytes.length*2);
for (int i=0;i<bytes.length;i++){
ret.append(HEX_DIGITS[(bytes[i]>>4)&0x0f]);
ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
}
return ret.toString();
}
/**
* 获取一个字符串的MD5码
* @param source 源字符串
* @return 根据源字符串生成的MD5值
* @throws NoSuchAlgorithmException 获取md5对象时失败
* @throws UnsupportedEncodingException 编码错误
*/
public static String getMD5Code(String source) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md5=MessageDigest.getInstance("MD5");
return toHex(md5.digest(source.getBytes(StandardCharsets.UTF_8)));
}
}
|
package hirelah.storage.serialisetests;
import static hirelah.commons.util.JsonUtil.readJsonFile;
import static hirelah.testutil.Assert.assertThrows;
import static hirelah.testutil.TypicalAttributes.getTypicalAttributes;
import static hirelah.testutil.TypicalQuestions.getTypicalQns;
import static hirelah.testutil.TypicalTranscript.getTypicalTranscript;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import hirelah.commons.exceptions.IllegalValueException;
import hirelah.commons.util.JsonUtil;
import hirelah.model.hirelah.Transcript;
import hirelah.storage.JsonSerializableTranscript;
public class JsonSerializableTranscriptTest {
private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data", "JsonSerializableTranscriptTest");
private static final Path TYPICAL_TRANSCRIPT_FILE = TEST_DATA_FOLDER.resolve("ValidTranscript.json");
private static final Path INVALID_TRANSCRIPT_FILE = TEST_DATA_FOLDER.resolve("InvalidTranscript.json");
@Test
public void toModelType_validTranscriptFile_success() throws Exception {
JsonSerializableTranscript dataFromFile = readJsonFile(TYPICAL_TRANSCRIPT_FILE,
JsonSerializableTranscript.class).get();
Transcript transcriptFromFile = dataFromFile.toModelType(getTypicalQns(), getTypicalAttributes());
assertEquals(getTypicalTranscript(), transcriptFromFile);
}
@Test
public void toModelType_invalidTranscriptFile_throwsIllegalValueException() throws Exception {
JsonSerializableTranscript dataFromFile = JsonUtil.readJsonFile(INVALID_TRANSCRIPT_FILE,
JsonSerializableTranscript.class).get();
assertThrows(IllegalValueException.class, () -> {
dataFromFile.toModelType(getTypicalQns(), getTypicalAttributes());
});
}
}
|
package org.gluu.service.cache;
import org.apache.commons.lang.SerializationUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* Important : keep it weld free. It's reused by oxd !
*
* @author yuriyz
*/
public class RedisClusterProvider extends AbstractRedisProvider {
private static final Logger LOG = LoggerFactory.getLogger(RedisClusterProvider.class);
private JedisCluster pool;
public RedisClusterProvider(RedisConfiguration redisConfiguration) {
super(redisConfiguration);
}
public void create() {
try {
LOG.debug("Starting RedisClusterProvider ... configuration:" + getRedisConfiguration());
JedisPoolConfig poolConfig = createPoolConfig();
String password = redisConfiguration.getPassword();
pool = new JedisCluster(hosts(getRedisConfiguration().getServers()), redisConfiguration.getConnectionTimeout(), redisConfiguration.getSoTimeout(), redisConfiguration.getMaxRetryAttempts(), password, poolConfig);
testConnection();
LOG.debug("RedisClusterProvider started.");
} catch (Exception e) {
LOG.error("Failed to start RedisClusterProvider.");
throw new IllegalStateException("Error starting RedisClusterProvider", e);
}
}
public static Set<HostAndPort> hosts(String servers) {
final String[] serverWithPorts = StringUtils.split(servers.trim(), ",");
Set<HostAndPort> set = new HashSet<HostAndPort>();
for (String serverWithPort : serverWithPorts) {
final String[] split = serverWithPort.trim().split(":");
String host = split[0];
int port = Integer.parseInt(split[1].trim());
set.add(new HostAndPort(host, port));
}
return set;
}
public void destroy() {
LOG.debug("Destroying RedisClusterProvider");
try {
pool.close();
} catch (IOException e) {
LOG.error("Failed to destroy RedisClusterProvider", e);
return;
}
LOG.debug("Destroyed RedisClusterProvider");
}
@Override
public JedisCluster getDelegate() {
return pool;
}
@Override
public boolean hasKey(String key) {
Boolean hasKey = pool.exists(key);
return Boolean.TRUE.equals(hasKey);
}
@Override
public Object get(String key) {
byte[] value = pool.get(key.getBytes());
Object deserialized = null;
if (value != null && value.length > 0) {
deserialized = SerializationUtils.deserialize(value);
}
return deserialized;
}
@Override
public void put(int expirationInSeconds, String key, Object object) {
String status = pool.setex(key.getBytes(), expirationInSeconds, SerializationUtils.serialize((Serializable) object));
LOG.trace("put - key: " + key + ", status: " + status);
}
@Override
public void put(String key, Object object) {
String status = pool.set(key.getBytes(), SerializationUtils.serialize((Serializable) object));
LOG.trace("put - key: " + key + ", status: " + status);
}
@Override
public void remove(String key) {
Long entriesRemoved = pool.del(key.getBytes());
LOG.trace("remove - key: " + key + ", entriesRemoved: " + entriesRemoved);
}
@Override
public void clear() {
LOG.trace("clear not allowed for cluster deployments");
}
}
|
/*
* Copyright 2019 Wolfgang Reder.
*
* 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 at.or.reder.dcc.cv;
import at.or.reder.dcc.util.Localizable;
import at.or.reder.dcc.util.ResourceDescription;
import javax.validation.constraints.NotNull;
/**
*
* @author Wolfgang Reder
*/
public interface EnumeratedValueBuilder
{
public EnumeratedValueBuilder copy(EnumeratedValue value);
public EnumeratedValueBuilder value(int value);
public EnumeratedValueBuilder addDescription(String locale,
@NotNull ResourceDescription description);
public EnumeratedValueBuilder addDescriptions(Localizable<? extends ResourceDescription> description);
public EnumeratedValueBuilder removeDescription(String locale);
public EnumeratedValueBuilder clearDescriptions();
public EnumeratedValue build();
}
|
package com.wei.you.zhihu.spider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* Spring boot项目启动类
*
* @author sunzc
*
* 2017年6月10日 下午7:21:38
*/
@SpringBootApplication
@ServletComponentScan(value = { "com.wei.you.zhihu.spider" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
/*
* Copyright 2012-2018 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 io.suricate.monitoring.repository;
import io.suricate.monitoring.model.entity.Asset;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Repository used to manage Asset data
*/
public interface AssetRepository extends JpaRepository<Asset, Long> {
}
|
/*
* Copyright (c) 2010-2018. Axon Framework
*
* 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.axonframework.eventsourcing.eventstore.jpa;
import org.axonframework.eventhandling.DomainEventMessage;
import org.axonframework.eventsourcing.eventstore.AbstractSnapshotEventEntry;
import org.axonframework.serialization.Serializer;
import javax.persistence.Entity;
/**
* Default implementation of an event entry containing a serialized snapshot of an aggregate. This implementation is
* used by the {@link JpaEventStorageEngine} to store snapshot events. Event payload and metadata are serialized to a
* byte array.
*
* @author Rene de Waele
*/
@Entity
public class SnapshotEventEntry extends AbstractSnapshotEventEntry<byte[]> {
/**
* Construct a new default snapshot event entry from an aggregate. The snapshot payload and metadata will be
* serialized to a byte array.
* <p>
* The given {@code serializer} will be used to serialize the payload and metadata in the given {@code
* eventMessage}. The type of the serialized data will be the same as the given {@code contentType}.
*
* @param eventMessage The snapshot event message to convert to a serialized event entry
* @param serializer The serializer to convert the snapshot event
*/
public SnapshotEventEntry(DomainEventMessage<?> eventMessage, Serializer serializer) {
super(eventMessage, serializer, byte[].class);
}
/**
* Default constructor required by JPA
*/
protected SnapshotEventEntry() {
}
}
|
package com.github.jinahya.database.metadata.bind;
/*-
* #%L
* database-metadata-bind
* %%
* Copyright (C) 2011 - 2019 Jinahya, 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%
*/
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jin Kwon <jinahya_at_gmail.com>
*/
@Slf4j
class ReflectionTest {
// -----------------------------------------------------------------------------------------------------------------
private static void method(Integer v) {
}
private static void method(int v) {
}
// -----------------------------------------------------------------------------------------------------------------
@Disabled
@Test
void test() throws NoSuchMethodException {
final boolean b1 = true;
final Boolean b2 = true;
assertThat(b1).isInstanceOf(Boolean.class);
assertThat(b2).isInstanceOf(Boolean.class);
final int i1 = 1;
final Integer i2 = 1;
assertThat(i1).isInstanceOf(Integer.class);
assertThat(i2).isIn(Integer.class);
assertThat(i1).isInstanceOf(Number.class);
assertThat(i2).isInstanceOf(Number.class);
final long l1 = 1L;
final Long l2 = 1L;
assertThat(l1).isInstanceOf(Long.class);
assertThat(l2).isInstanceOf(Long.class);
assertThat(l1).isInstanceOf(Number.class);
assertThat(l2).isInstanceOf(Number.class);
assertThat(Integer.TYPE).isEqualTo(int.class);
for (Method method : getClass().getDeclaredMethods()) {
log.debug("method: {}", method);
}
log.debug("method with Integer: {}", getClass().getDeclaredMethod("method", Integer.class));
log.debug("method with TYPE: {}", getClass().getDeclaredMethod("method", Integer.TYPE));
log.debug("method with int: {}", getClass().getDeclaredMethod("method", int.class));
}
@Disabled
@Test
void listType() throws ReflectiveOperationException {
final Field field = getClass().getDeclaredField("list");
final Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
final Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
final String typeName = elementType.getTypeName();
log.debug("typeName: {}", typeName);
}
}
}
|
/*
* 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.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.api.DemoService;
import org.apache.dubbo.config.api.Greeting;
import org.apache.dubbo.config.mock.MockProtocol2;
import org.apache.dubbo.config.mock.MockRegistryFactory2;
import org.apache.dubbo.config.mock.TestProxyFactory;
import org.apache.dubbo.config.provider.impl.DemoServiceImpl;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.service.GenericService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_DEFAULT;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.withSettings;
public class ServiceConfigTest {
private Protocol protocolDelegate = Mockito.mock(Protocol.class);
private Registry registryDelegate = Mockito.mock(Registry.class);
private Exporter exporter = Mockito.mock(Exporter.class);
private ServiceConfig<DemoServiceImpl> service = new ServiceConfig<DemoServiceImpl>();
private ServiceConfig<DemoServiceImpl> service2 = new ServiceConfig<DemoServiceImpl>();
private ServiceConfig<DemoServiceImpl> delayService = new ServiceConfig<DemoServiceImpl>();
@BeforeEach
public void setUp() throws Exception {
MockProtocol2.delegate = protocolDelegate;
MockRegistryFactory2.registry = registryDelegate;
Mockito.when(protocolDelegate.export(Mockito.any(Invoker.class))).thenReturn(exporter);
ApplicationConfig app = new ApplicationConfig("app");
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("mockprotocol2");
ProviderConfig provider = new ProviderConfig();
provider.setExport(true);
provider.setProtocol(protocolConfig);
RegistryConfig registry = new RegistryConfig();
registry.setProtocol("mockprotocol2");
registry.setAddress("N/A");
ArgumentConfig argument = new ArgumentConfig();
argument.setIndex(0);
argument.setCallback(false);
MethodConfig method = new MethodConfig();
method.setName("echo");
method.setArguments(Collections.singletonList(argument));
service.setProvider(provider);
service.setApplication(app);
service.setRegistry(registry);
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setMethods(Collections.singletonList(method));
service2.setProvider(provider);
service2.setApplication(app);
service2.setRegistry(registry);
service2.setInterface(DemoService.class);
service2.setRef(new DemoServiceImpl());
service2.setMethods(Collections.singletonList(method));
service2.setProxy("testproxyfactory");
delayService.setProvider(provider);
delayService.setApplication(app);
delayService.setRegistry(registry);
delayService.setInterface(DemoService.class);
delayService.setRef(new DemoServiceImpl());
delayService.setMethods(Collections.singletonList(method));
delayService.setDelay(100);
ApplicationModel.getConfigManager().clear();
}
@AfterEach
public void tearDown() {
ApplicationModel.getConfigManager().clear();
}
@Test
public void testExport() throws Exception {
service.export();
assertThat(service.getExportedUrls(), hasSize(1));
URL url = service.toUrl();
assertThat(url.getProtocol(), equalTo("mockprotocol2"));
assertThat(url.getPath(), equalTo(DemoService.class.getName()));
assertThat(url.getParameters(), hasEntry(ANYHOST_KEY, "true"));
assertThat(url.getParameters(), hasEntry(APPLICATION_KEY, "app"));
assertThat(url.getParameters(), hasKey(BIND_IP_KEY));
assertThat(url.getParameters(), hasKey(BIND_PORT_KEY));
assertThat(url.getParameters(), hasEntry(EXPORT_KEY, "true"));
assertThat(url.getParameters(), hasEntry("echo.0.callback", "false"));
assertThat(url.getParameters(), hasEntry(GENERIC_KEY, "false"));
assertThat(url.getParameters(), hasEntry(INTERFACE_KEY, DemoService.class.getName()));
assertThat(url.getParameters(), hasKey(METHODS_KEY));
assertThat(url.getParameters().get(METHODS_KEY), containsString("echo"));
assertThat(url.getParameters(), hasEntry(SIDE_KEY, PROVIDER));
Mockito.verify(protocolDelegate).export(Mockito.any(Invoker.class));
}
@Test
public void testProxy() throws Exception {
service2.export();
assertThat(service2.getExportedUrls(), hasSize(1));
assertEquals(2, TestProxyFactory.count); // local injvm and registry protocol, so expected is 2
}
@Test
public void testDelayExport() throws Exception {
delayService.export();
assertTrue(delayService.getExportedUrls().isEmpty());
//add 300ms to ensure that the delayService has been exported
TimeUnit.MILLISECONDS.sleep(delayService.getDelay() + 300);
assertThat(delayService.getExportedUrls(), hasSize(1));
}
@Test
@Disabled("cannot pass in travis")
public void testUnexport() throws Exception {
System.setProperty(SHUTDOWN_WAIT_KEY, "0");
try {
service.export();
service.unexport();
Thread.sleep(1000);
Mockito.verify(exporter, Mockito.atLeastOnce()).unexport();
} finally {
System.clearProperty(SHUTDOWN_TIMEOUT_KEY);
}
}
@Test
public void testInterfaceClass() throws Exception {
ServiceConfig<Greeting> service = new ServiceConfig<Greeting>();
service.setInterface(Greeting.class.getName());
service.setRef(Mockito.mock(Greeting.class));
assertThat(service.getInterfaceClass() == Greeting.class, is(true));
service = new ServiceConfig<Greeting>();
service.setRef(Mockito.mock(Greeting.class, withSettings().extraInterfaces(GenericService.class)));
assertThat(service.getInterfaceClass() == GenericService.class, is(true));
}
@Test
public void testInterface1() throws Exception {
Assertions.assertThrows(IllegalStateException.class, () -> {
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoServiceImpl.class);
});
}
@Test
public void testInterface2() throws Exception {
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.class);
assertThat(service.getInterface(), equalTo(DemoService.class.getName()));
}
@Test
public void testProvider() throws Exception {
ServiceConfig service = new ServiceConfig();
ProviderConfig provider = new ProviderConfig();
service.setProvider(provider);
assertThat(service.getProvider(), is(provider));
}
@Test
public void testGeneric1() throws Exception {
ServiceConfig service = new ServiceConfig();
service.setGeneric(GENERIC_SERIALIZATION_DEFAULT);
assertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_DEFAULT));
service.setGeneric(GENERIC_SERIALIZATION_NATIVE_JAVA);
assertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_NATIVE_JAVA));
service.setGeneric(GENERIC_SERIALIZATION_BEAN);
assertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_BEAN));
}
@Test
public void testGeneric2() throws Exception {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceConfig service = new ServiceConfig();
service.setGeneric("illegal");
});
}
@Test
public void testMock() throws Exception {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceConfig service = new ServiceConfig();
service.setMock("true");
});
}
@Test
public void testMock2() throws Exception {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceConfig service = new ServiceConfig();
service.setMock(true);
});
}
}
|
package uk.gov.hmcts.reform.bulkscanprocessor.services;
import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.specialized.BlobInputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import uk.gov.hmcts.reform.bulkscanprocessor.entity.Envelope;
import uk.gov.hmcts.reform.bulkscanprocessor.entity.Status;
import uk.gov.hmcts.reform.bulkscanprocessor.exceptions.FileSizeExceedMaxUploadLimit;
import uk.gov.hmcts.reform.bulkscanprocessor.model.common.Classification;
import uk.gov.hmcts.reform.bulkscanprocessor.model.common.Event;
import uk.gov.hmcts.reform.bulkscanprocessor.services.storage.LeaseAcquirer;
import uk.gov.hmcts.reform.bulkscanprocessor.tasks.processor.BlobManager;
import uk.gov.hmcts.reform.bulkscanprocessor.tasks.processor.DocumentProcessor;
import uk.gov.hmcts.reform.bulkscanprocessor.tasks.processor.EnvelopeProcessor;
import uk.gov.hmcts.reform.bulkscanprocessor.tasks.processor.ZipFileProcessor;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.zip.ZipInputStream;
import static java.time.Instant.now;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
@ExtendWith(MockitoExtension.class)
@SuppressWarnings("unchecked")
class UploadEnvelopeDocumentsServiceTest {
private static final String CONTAINER_1 = "container-1";
private static final String ZIP_FILE_NAME = "zip-file-name";
// used to construct service
@Mock private BlobManager blobManager;
@Mock private ZipFileProcessor zipFileProcessor;
@Mock private DocumentProcessor documentProcessor;
@Mock private EnvelopeProcessor envelopeProcessor;
@Mock private LeaseAcquirer leaseAcquirer;
// used inside the service methods
@Mock private BlobContainerClient blobContainer;
@Mock private BlobClient blobClient;
private UploadEnvelopeDocumentsService uploadService;
@BeforeEach
void setUp() {
uploadService = new UploadEnvelopeDocumentsService(
blobManager,
zipFileProcessor,
documentProcessor,
envelopeProcessor,
leaseAcquirer
);
}
@Test
void should_do_nothing_when_blob_manager_fails_to_retrieve_container_representation() {
// given
willThrow(new RuntimeException("i failed")).given(blobManager).listContainerClient(CONTAINER_1);
// when
uploadService.processByContainer(CONTAINER_1, getEnvelopes());
// then
verifyNoInteractions(zipFileProcessor, documentProcessor, envelopeProcessor);
verifyNoInteractions(zipFileProcessor, documentProcessor, envelopeProcessor);
}
@Test
void should_do_nothing_when_failing_to_get_block_blob_reference() {
// given
given(blobManager.listContainerClient(CONTAINER_1)).willReturn(blobContainer);
// and
willThrow(new RuntimeException("Error getting BlobClient"))
.given(blobContainer).getBlobClient(ZIP_FILE_NAME);
// when
uploadService.processByContainer(CONTAINER_1, getEnvelopes());
// then
verifyNoInteractions(zipFileProcessor, documentProcessor, envelopeProcessor);
}
@Test
void should_do_nothing_when_failing_to_acquire_lease() {
// given
given(blobManager.listContainerClient(CONTAINER_1)).willReturn(blobContainer);
given(blobContainer.getBlobContainerName()).willReturn(CONTAINER_1);
given(blobContainer.getBlobClient(ZIP_FILE_NAME)).willReturn(blobClient);
doThrow(new RuntimeException("Error in uploading docs"))
.when(leaseAcquirer).ifAcquiredOrElse(any(), any(), any(), anyBoolean());
// when
uploadService.processByContainer(CONTAINER_1, getEnvelopes()); // for storage exception
// then
verifyNoInteractions(zipFileProcessor, documentProcessor, envelopeProcessor);
}
@Test
void should_do_nothing_when_failing_to_open_stream() {
// given
given(blobManager.listContainerClient(CONTAINER_1)).willReturn(blobContainer);
given(blobContainer.getBlobContainerName()).willReturn(CONTAINER_1);
given(blobContainer.getBlobClient(ZIP_FILE_NAME)).willReturn(blobClient);
leaseAcquired();
// and
willThrow(new RuntimeException("openInputStream error")).given(blobClient).openInputStream();
// when
uploadService.processByContainer(CONTAINER_1, getEnvelopes());
// then
verifyNoInteractions(zipFileProcessor, documentProcessor);
}
@Test
void should_do_nothing_when_failing_to_read_blob_input_stream() throws Exception {
// given
given(blobManager.listContainerClient(CONTAINER_1)).willReturn(blobContainer);
given(blobContainer.getBlobContainerName()).willReturn(CONTAINER_1);
given(blobContainer.getBlobClient(ZIP_FILE_NAME)).willReturn(blobClient);
leaseAcquired();
given(blobClient.openInputStream()).willReturn(mock(BlobInputStream.class));
given(blobClient.getContainerName()).willReturn(CONTAINER_1);
// and
willThrow(new IOException("failed")).given(zipFileProcessor)
.extractPdfFiles(any(ZipInputStream.class), eq(ZIP_FILE_NAME), any());
Envelope envelope = mock(Envelope.class);
UUID envelopeId = UUID.randomUUID();
given(envelope.getId()).willReturn(envelopeId);
given(envelope.getZipFileName()).willReturn(ZIP_FILE_NAME);
// when
uploadService.processByContainer(CONTAINER_1, singletonList(envelope));
// then
verifyNoInteractions(documentProcessor);
// and
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
verify(envelopeProcessor, times(1))
.createEvent(eventCaptor.capture(), eq(CONTAINER_1), eq(ZIP_FILE_NAME), eq("failed"), eq(envelopeId));
assertThat(eventCaptor.getValue()).isEqualTo(Event.DOC_UPLOAD_FAILURE);
}
@Test
void should_mark_as_doc_upload_failure_when_unable_to_upload_pdfs() throws Exception {
// given
given(blobManager.listContainerClient(CONTAINER_1)).willReturn(blobContainer);
given(blobContainer.getBlobContainerName()).willReturn(CONTAINER_1);
given(blobContainer.getBlobClient(ZIP_FILE_NAME)).willReturn(blobClient);
leaseAcquired();
given(blobClient.openInputStream()).willReturn(mock(BlobInputStream.class));
doAnswer(invocation -> {
var okAction = (Consumer) invocation.getArgument(2);
okAction.accept(emptyList());
return null;
}).when(zipFileProcessor).extractPdfFiles(any(ZipInputStream.class), eq(ZIP_FILE_NAME), any());
// and
willThrow(new RuntimeException("oh no")).given(documentProcessor)
.uploadPdfFiles(emptyList(), emptyList(), "FB_BULK", CONTAINER_1);
// and
Envelope envelope = mock(Envelope.class);
UUID envelopeId = UUID.randomUUID();
given(envelope.getId()).willReturn(envelopeId);
given(envelope.getZipFileName()).willReturn(ZIP_FILE_NAME);
given(envelope.getContainer()).willReturn(CONTAINER_1);
given(envelope.getJurisdiction()).willReturn("FB_BULK");
// when
uploadService.processByContainer(CONTAINER_1, singletonList(envelope));
// then
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
verify(envelopeProcessor, times(1))
.createEvent(eventCaptor.capture(), eq(CONTAINER_1), eq(ZIP_FILE_NAME), eq("oh no"), eq(envelopeId));
assertThat(eventCaptor.getValue()).isEqualTo(Event.DOC_UPLOAD_FAILURE);
// and
verify(envelopeProcessor, times(1)).markAsUploadFailure(envelope);
}
@Test
void should_mark_as_file_size_failure_when_any_pdf_exceeds_upload_limit() throws IOException {
// given
given(blobManager.listContainerClient(CONTAINER_1)).willReturn(blobContainer);
given(blobContainer.getBlobContainerName()).willReturn(CONTAINER_1);
given(blobContainer.getBlobClient(ZIP_FILE_NAME)).willReturn(blobClient);
leaseAcquired();
given(blobClient.openInputStream()).willReturn(mock(BlobInputStream.class));
// and
willThrow(new FileSizeExceedMaxUploadLimit("PDF size exceeds the max upload size limit"))
.given(zipFileProcessor).extractPdfFiles(any(ZipInputStream.class), eq(ZIP_FILE_NAME), any());
// and
Envelope envelope = mock(Envelope.class);
UUID envelopeId = UUID.randomUUID();
given(envelope.getId()).willReturn(envelopeId);
given(envelope.getZipFileName()).willReturn(ZIP_FILE_NAME);
given(blobClient.getContainerName()).willReturn(CONTAINER_1);
// when
uploadService.processByContainer(CONTAINER_1, singletonList(envelope));
// then
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
verify(envelopeProcessor, times(1))
.createEvent(
eventCaptor.capture(),
eq(CONTAINER_1),
eq(ZIP_FILE_NAME),
eq("PDF size exceeds the max upload size limit"),
eq(envelopeId)
);
assertThat(eventCaptor.getValue()).isEqualTo(Event.FILE_SIZE_EXCEED_UPLOAD_LIMIT_FAILURE);
// and
verify(blobManager).tryMoveFileToRejectedContainer(ZIP_FILE_NAME, CONTAINER_1);
verify(envelope).setStatus(Status.COMPLETED);
verify(envelopeProcessor, times(1)).saveEnvelope(envelope);
}
@Test
void should_mark_as_uploaded_when_everything_went_well() throws Exception {
// given
given(blobManager.listContainerClient(CONTAINER_1)).willReturn(blobContainer);
given(blobContainer.getBlobContainerName()).willReturn(CONTAINER_1);
given(blobContainer.getBlobClient(ZIP_FILE_NAME)).willReturn(blobClient);
leaseAcquired();
given(blobClient.openInputStream()).willReturn(mock(BlobInputStream.class));
List<File> files = List.of(mock(File.class));
doAnswer(invocation -> {
var okAction = (Consumer) invocation.getArgument(2);
okAction.accept(files);
return null;
}).when(zipFileProcessor).extractPdfFiles(any(ZipInputStream.class), eq(ZIP_FILE_NAME), any());
// when
uploadService.processByContainer(CONTAINER_1, getEnvelopes());
// then
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
verify(envelopeProcessor, times(1)).handleEvent(any(Envelope.class), eventCaptor.capture());
assertThat(eventCaptor.getValue()).isEqualTo(Event.DOC_UPLOADED);
// and
verify(documentProcessor, times(1)).uploadPdfFiles(files, emptyList(), "jurisdiction", CONTAINER_1);
}
void leaseAcquired() {
doAnswer(invocation -> {
var okAction = (Consumer) invocation.getArgument(1);
okAction.accept(UUID.randomUUID().toString());
return null;
}).when(leaseAcquirer).ifAcquiredOrElse(any(), any(), any(), anyBoolean());
}
private List<Envelope> getEnvelopes() {
// service is only interested in status, createdAt, file name and container
// default state is "CREATED" - that's what we need :+1:
return singletonList(new Envelope(
"po-box",
"jurisdiction",
now(), // delivery date
now(), // opening date
now(), // zip file created at (from blob storage)
ZIP_FILE_NAME,
"case-number",
"previous-service-case-reference",
Classification.EXCEPTION,
emptyList(),
emptyList(),
emptyList(),
CONTAINER_1,
null
));
}
}
|
package dev.spaceseries.spaceapi.config.adapter;
import dev.spaceseries.spaceapi.abstraction.plugin.BungeePlugin;
import dev.spaceseries.spaceapi.config.generic.adapter.ConfigurationAdapter;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class BungeeConfigAdapter implements ConfigurationAdapter {
private final BungeePlugin plugin;
private final File file;
private Configuration configuration;
public BungeeConfigAdapter(BungeePlugin plugin, File file) {
this.plugin = plugin;
this.file = file;
reload();
}
@Override
public void reload() {
try {
this.configuration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(this.file);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public String getString(String path, String def) {
return this.configuration.getString(path, def);
}
@Override
public int getInteger(String path, int def) {
return this.configuration.getInt(path, def);
}
@Override
public boolean getBoolean(String path, boolean def) {
return this.configuration.getBoolean(path, def);
}
@Override
public List<String> getStringList(String path, List<String> def) {
return Optional.of(this.configuration.getStringList(path)).orElse(def);
}
@Override
public List<String> getKeys(String path, List<String> def) {
Configuration section = this.configuration.getSection(path);
if (section == null) {
return def;
}
return Optional.of((List<String>) new ArrayList<>(section.getKeys())).orElse(def);
}
@Override
public Map<String, String> getStringMap(String path, Map<String, String> def) {
Map<String, String> map = new HashMap<>();
Configuration section = this.configuration.getSection(path);
if (section == null) {
return def;
}
for (String key : section.getKeys()) {
map.put(key, section.get(key).toString());
}
return map;
}
@Override
public BungeePlugin getPlugin() {
return this.plugin;
}
}
|
package com.lvcoding.cup;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lvcoding.entity.SysTenant;
import com.lvcoding.service.SysTenantService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
/**
* @Description 描述
* @Date 2020-08-28 12:11 下午
* @Author wuyanshen
*/
@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class SysTenantTest {
@Autowired
private SysTenantService sysTenantService;
@Autowired
private MockMvc mockMvc;
@Autowired
ObjectMapper objectMapper;
// 分页查询租户
@Test
public void find() throws Exception {
mockMvc.perform(get("/tenant/page")
.param("tenantName", "公司")
.header("tenantId",1))
.andDo(print());
}
// 新增租户
@Test
public void add() throws Exception {
String json = "{\"tenantName\":\"测试公司\",\"remark\":\"测试公司\"}";
//SysTenant sysTenant = new SysTenant();
//sysTenant.setTenantName("北京卡普公司");
//sysTenant.setRemark("一家科技公司");
//String req = objectMapper.writeValueAsString(sysTenant);
mockMvc.perform(post("/tenant")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(json))
.andDo(print());
}
// 更新租户
@Test
public void update() throws Exception {
String json = "{id:1, tenantName:太原卡普公司}";
SysTenant sysTenant = new SysTenant();
sysTenant.setId(1);
sysTenant.setTenantName("太原卡普公司");
json = objectMapper.writeValueAsString(sysTenant);
mockMvc.perform(put("/tenant")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(json))
.andDo(print());
}
// 删除租户
@Test
public void remove() throws Exception {
mockMvc.perform(delete("/tenant/2"))
.andDo(print());
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__float_random_modulo_45.java
Label Definition File: CWE369_Divide_by_Zero__float.label.xml
Template File: sources-sinks-45.tmpl.java
*/
/*
* @description
* CWE: 369 Divide by zero
* BadSource: random Set data to a random value between 0.0f (inclusive) and 1.0f (exclusive)
* GoodSource: A hardcoded non-zero number (two)
* Sinks: modulo
* GoodSink: Check for zero before modulo
* BadSink : Modulo by a value that may be zero
* Flow Variant: 45 Data flow: data passed as a private class member variable from one function to another in the same class
*
* */
import java.security.SecureRandom;
public class CWE369_Divide_by_Zero__float_random_modulo_45 extends AbstractTestCase
{
private float dataBad;
private float dataGoodG2B;
private float dataGoodB2G;
private void badSink() throws Throwable
{
float data = dataBad;
/* POTENTIAL FLAW: Possibly modulo by zero */
int result = (int)(100.0 % data);
IO.writeLine(result);
}
public void bad() throws Throwable
{
float data;
/* POTENTIAL FLAW: Set data to a random value between 0.0f (inclusive) and 1.0f (exclusive) */
SecureRandom secureRandom = new SecureRandom();
data = secureRandom.nextFloat();
dataBad = data;
badSink();
}
public void good() throws Throwable
{
goodG2B();
goodB2G();
}
private void goodG2BSink() throws Throwable
{
float data = dataGoodG2B;
/* POTENTIAL FLAW: Possibly modulo by zero */
int result = (int)(100.0 % data);
IO.writeLine(result);
}
/* goodG2B() - use goodsource and badsink */
private void goodG2B() throws Throwable
{
float data;
/* FIX: Use a hardcoded number that won't a divide by zero */
data = 2.0f;
dataGoodG2B = data;
goodG2BSink();
}
private void goodB2GSink() throws Throwable
{
float data = dataGoodB2G;
/* FIX: Check for value of or near zero before modulo */
if (Math.abs(data) > 0.000001)
{
int result = (int)(100.0 % data);
IO.writeLine(result);
}
else
{
IO.writeLine("This would result in a modulo by zero");
}
}
/* goodB2G() - use badsource and goodsink */
private void goodB2G() throws Throwable
{
float data;
/* POTENTIAL FLAW: Set data to a random value between 0.0f (inclusive) and 1.0f (exclusive) */
SecureRandom secureRandom = new SecureRandom();
data = secureRandom.nextFloat();
dataGoodB2G = data;
goodB2GSink();
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
/*
* Copyright 2014-present Open Networking Foundation
*
* 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.onosproject.net.flow;
import org.onosproject.event.AbstractEvent;
import org.onosproject.net.DeviceId;
@Deprecated
/**
* Describes flow rule batch event.
*
* @deprecated in Drake release - no longer a public API
*/
public final class FlowRuleBatchEvent extends AbstractEvent<FlowRuleBatchEvent.Type, FlowRuleBatchRequest> {
/**
* Type of flow rule events.
*/
public enum Type {
// Request has been forwarded to MASTER Node
/**
* Signifies that a batch operation has been initiated.
*/
BATCH_OPERATION_REQUESTED,
// MASTER Node has pushed the batch down to the Device
// (e.g., Received barrier reply)
/**
* Signifies that a batch operation has completed.
*/
BATCH_OPERATION_COMPLETED,
}
private final CompletedBatchOperation result;
private final DeviceId deviceId;
/**
* Constructs a new FlowRuleBatchEvent.
*
* @param request batch operation request
* @param deviceId the device this batch will be processed on
* @return event.
*/
public static FlowRuleBatchEvent requested(FlowRuleBatchRequest request, DeviceId deviceId) {
FlowRuleBatchEvent event = new FlowRuleBatchEvent(Type.BATCH_OPERATION_REQUESTED, request, deviceId);
return event;
}
/**
* Constructs a new FlowRuleBatchEvent.
* @param request batch operation request.
* @param result completed batch operation result.
* @return event.
*/
public static FlowRuleBatchEvent completed(FlowRuleBatchRequest request, CompletedBatchOperation result) {
FlowRuleBatchEvent event = new FlowRuleBatchEvent(Type.BATCH_OPERATION_COMPLETED, request, result);
return event;
}
/**
* Returns the result of this batch operation.
* @return batch operation result.
*/
public CompletedBatchOperation result() {
return result;
}
/**
* Returns the deviceId for this batch.
* @return device id
*/
public DeviceId deviceId() {
return deviceId;
}
/**
* Creates an event of a given type and for the specified flow rule batch.
*
* @param type flow rule batch event type
* @param request event flow rule batch subject
* @param result the result of the batch operation
*/
private FlowRuleBatchEvent(Type type, FlowRuleBatchRequest request, CompletedBatchOperation result) {
super(type, request);
this.result = result;
this.deviceId = result.deviceId();
}
/**
* Creates an event of a given type and for the specified flow rule batch.
*
* @param type flow rule batch event type
* @param request event flow rule batch subject
* @param deviceId the device id for this batch
*/
private FlowRuleBatchEvent(Type type, FlowRuleBatchRequest request, DeviceId deviceId) {
super(type, request);
this.result = null;
this.deviceId = deviceId;
}
}
|
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
* Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
package org.onap.policy.apex.model.policymodel.handling;
import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
import org.onap.policy.apex.model.policymodel.concepts.AxLogic;
import org.onap.policy.apex.model.policymodel.concepts.AxLogicReader;
import org.onap.policy.apex.model.policymodel.concepts.PolicyRuntimeException;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
/**
* This class is used to read Task Logic and Task Selection Logic from files into a string. A
* {@link PolicyLogicReader} can then be used to provide the logic on a {@link AxLogic} class
* constructor.
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class PolicyLogicReader implements AxLogicReader {
private static final String DOT_JAVA = ".java.";
private static final XLogger LOGGER = XLoggerFactory.getXLogger(PolicyModelSplitter.class);
// The path of the logic package
private String logicPackage = "";
// Flag indicating if default logic should be returned
private String defaultLogic;
/**
* {@inheritDoc}.
*/
@Override
public String getLogicPackage() {
return logicPackage;
}
/**
* {@inheritDoc}.
*/
@Override
public AxLogicReader setLogicPackage(final String incomingLogicPackage) {
this.logicPackage = incomingLogicPackage;
return this;
}
/**
* {@inheritDoc}.
*/
@Override
public String getDefaultLogic() {
return defaultLogic;
}
/**
* {@inheritDoc}.
*/
@Override
public AxLogicReader setDefaultLogic(final String incomingDefaultLogic) {
this.defaultLogic = incomingDefaultLogic;
return this;
}
/**
* {@inheritDoc}.
*/
@Override
public String readLogic(final AxLogic axLogic) {
// Java uses compiled logic, other executor types run scripts
if ("JAVA".equals(axLogic.getLogicFlavour())) {
// Check if we're using the default logic
if (defaultLogic != null) {
// Return the java class name for the default logic
return logicPackage + DOT_JAVA + defaultLogic;
} else {
// Return the java class name for the logic
if (axLogic.getKey().getParentLocalName().equals(AxKey.NULL_KEY_NAME)) {
return logicPackage + DOT_JAVA + axLogic.getKey().getParentKeyName()
+ axLogic.getKey().getLocalName();
} else {
return logicPackage + DOT_JAVA + axLogic.getKey().getParentKeyName()
+ axLogic.getKey().getParentLocalName() + axLogic.getKey().getLocalName();
}
}
}
// Now, we read in the script
// Get the package name of the current package and convert dots to slashes for the file path
String fullLogicFilePath = logicPackage.replace(".", "/");
// Now, the logic should be in a sub directory for the logic executor type
fullLogicFilePath += "/" + axLogic.getLogicFlavour().toLowerCase();
// Check if we're using the default logic
if (defaultLogic != null) {
// Default logic
fullLogicFilePath += "/" + defaultLogic;
} else {
if (axLogic.getKey().getParentLocalName().equals(AxKey.NULL_KEY_NAME)) {
fullLogicFilePath += "/" + axLogic.getKey().getParentKeyName() + axLogic.getKey().getLocalName();
} else {
fullLogicFilePath += "/" + axLogic.getKey().getParentKeyName()
+ axLogic.getKey().getParentLocalName() + axLogic.getKey().getLocalName();
}
}
// Now get the type of executor to find the extension of the file
fullLogicFilePath += "." + axLogic.getLogicFlavour().toLowerCase();
final String logicString = ResourceUtils.getResourceAsString(fullLogicFilePath);
// Check if the logic was found
if (logicString == null || logicString.length() == 0) {
String errorMessage = "logic not found for logic \"" + fullLogicFilePath + "\"";
LOGGER.warn(errorMessage);
throw new PolicyRuntimeException(errorMessage);
}
// Return the right trimmed logic string
return logicString.replaceAll("\\s+$", "");
}
}
|
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. 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 DDS;
public interface TRANSPORTPRIORITY_QOS_POLICY_ID
{
public static final int value = 20;
}
|
package io.smallrye.config;
import static io.smallrye.config.SmallRyeConfig.SMALLRYE_CONFIG_PROFILE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.eclipse.microprofile.config.Config;
import org.junit.jupiter.api.Test;
class InterceptorChainTest {
@Test
void chain() {
final Config config = buildConfig(
"my.prop", "1", // original property
"%my.prop.profile", "2", // profile property with expansion
"%prof.my.prop.profile", "3",
"my.prop.relocate", "4", // relocation
"%prof.my.prop.relocate", "${%prof.my.prop.profile}", // profile with relocation
SMALLRYE_CONFIG_PROFILE, "prof" // profile to use
);
assertEquals("3", config.getValue("my.prop", String.class));
}
private static Config buildConfig(String... keyValues) {
return new SmallRyeConfigBuilder()
.addDefaultSources()
.addDefaultInterceptors()
.withSources(KeyValuesConfigSource.config(keyValues))
.withInterceptors(
new RelocateConfigSourceInterceptor(s -> s.replaceAll("my\\.prop", "my.prop.relocate")))
.build();
}
}
|
/* 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.dmn.engine.impl.hitpolicy;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.flowable.dmn.engine.impl.context.Context;
import org.flowable.dmn.engine.impl.mvel.MvelExecutionContext;
import org.flowable.dmn.model.HitPolicy;
import org.flowable.engine.common.api.FlowableException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* @author Yvo Swillens
*/
public class HitPolicyPriority extends AbstractHitPolicy implements ComposeDecisionResultBehavior {
@Override
public String getHitPolicyName() {
return HitPolicy.PRIORITY.getValue();
}
public void composeDecisionResults(final MvelExecutionContext executionContext) {
List<Map<String, Object>> ruleResults = new ArrayList<>(executionContext.getRuleResults().values());
// sort on predefined list(s) of output values
Collections.sort(ruleResults, new Comparator() {
boolean noOutputValuesPresent = true;
public int compare(Object o1, Object o2) {
CompareToBuilder compareToBuilder = new CompareToBuilder();
for (Map.Entry<String, List<Object>> entry : executionContext.getOutputValues().entrySet()) {
List<Object> outputValues = entry.getValue();
if (outputValues != null || !outputValues.isEmpty()) {
noOutputValuesPresent = false;
compareToBuilder.append(((Map) o1).get(entry.getKey()), ((Map) o2).get(entry.getKey()), new OutputOrderComparator<>(outputValues.toArray(new Comparable[outputValues.size()])));
}
}
if (!noOutputValuesPresent) {
return compareToBuilder.toComparison();
} else {
if (Context.getDmnEngineConfiguration().isStrictMode()) {
throw new FlowableException(String.format("HitPolicy: %s; no output values present", getHitPolicyName()));
}
return 0;
}
}
});
executionContext.setDecisionResults(ruleResults.subList(0,1));
}
}
|
package com.codetaylor.mc.artisanworktables.common.recipe.serializer;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.network.PacketBuffer;
import javax.annotation.Nonnull;
public interface IRecipeSerializerPacketWriter<T extends IRecipe<?>> {
void write(@Nonnull PacketBuffer buffer, @Nonnull T recipe);
}
|
/*
* <summary></summary>
* <author>hankcs</author>
* <email>me@hankcs.com</email>
* <create-date>2015/5/6 19:48</create-date>
*
* <copyright file="CharacterBasedGenerativeModel.java">
* Copyright (c) 2003-2015, hankcs. All Right Reserved, http://www.hankcs.com/
* </copyright>
*/
package com.hankcs.hanlp.model.trigram;
import com.hankcs.hanlp.corpus.document.sentence.word.IWord;
import com.hankcs.hanlp.corpus.document.sentence.word.Word;
import com.hankcs.hanlp.corpus.io.ByteArray;
import com.hankcs.hanlp.corpus.io.ICacheAble;
import com.hankcs.hanlp.model.trigram.frequency.Probability;
import java.io.DataOutputStream;
import java.util.LinkedList;
import java.util.List;
/**
* 基于字符的生成模型(其实就是一个TriGram文法模型,或称2阶隐马模型)
*
* @author hankcs
*/
public class CharacterBasedGenerativeModel implements ICacheAble
{
/**
* 2阶隐马的三个参数
*/
double l1, l2, l3;
/**
* 频次统计
*/
Probability tf;
/**
* 用到的标签
*/
static final char[] id2tag = new char[]{'b', 'm', 'e', 's'};
/**
* 视野范围外的事件
*/
static final char[] bos = {'\b', 'x'};
/**
* 无穷小
*/
static final double inf = -1e10;
public CharacterBasedGenerativeModel()
{
tf = new Probability();
}
/**
* 让模型观测一个句子
* @param wordList
*/
public void learn(List<Word> wordList)
{
LinkedList<char[]> sentence = new LinkedList<char[]>();
for (IWord iWord : wordList)
{
String word = iWord.getValue();
if (word.length() == 1)
{
sentence.add(new char[]{word.charAt(0), 's'});
}
else
{
sentence.add(new char[]{word.charAt(0), 'b'});
for (int i = 1; i < word.length() - 1; ++i)
{
sentence.add(new char[]{word.charAt(i), 'm'});
}
sentence.add(new char[]{word.charAt(word.length() - 1), 'e'});
}
}
// 转换完毕,开始统计
char[][] now = new char[3][]; // 定长3的队列
now[1] = bos;
now[2] = bos;
tf.add(1, bos, bos);
tf.add(2, bos);
for (char[] i : sentence)
{
System.arraycopy(now, 1, now, 0, 2);
now[2] = i;
tf.add(1, i); // uni
tf.add(1, now[1], now[2]); // bi
tf.add(1, now); // tri
}
}
/**
* 观测结束,开始训练
*/
public void train()
{
double tl1 = 0.0;
double tl2 = 0.0;
double tl3 = 0.0;
for (String key : tf.d.keySet())
{
if (key.length() != 6) continue; // tri samples
char[][] now = new char[][]
{
{key.charAt(0), key.charAt(1)},
{key.charAt(2), key.charAt(3)},
{key.charAt(4), key.charAt(5)},
};
double c3 = div(tf.get(now) - 1, tf.get(now[0], now[1]) - 1);
double c2 = div(tf.get(now[1], now[2]) - 1, tf.get(now[1]) - 1);
double c1 = div(tf.get(now[2]) - 1, tf.getsum() - 1);
if (c3 >= c1 && c3 >= c2)
tl3 += tf.get(now);
else if (c2 >= c1 && c2 >= c3)
tl2 += tf.get(now);
else if (c1 >= c2 && c1 >= c3)
tl1 += tf.get(now);
}
l1 = div(tl1, tl1 + tl2 + tl3);
l2 = div(tl2, tl1 + tl2 + tl3);
l3 = div(tl3, tl1 + tl2 + tl3);
}
/**
* 求概率
* @param s1 前2个状态
* @param s2 前1个状态
* @param s3 当前状态
* @return 序列的概率
*/
double log_prob(char[] s1, char[] s2, char[] s3)
{
double uni = l1 * tf.freq(s3);
double bi = div(l2 * tf.get(s2, s3), tf.get(s2));
double tri = div(l3 * tf.get(s1, s2, s3), tf.get(s1, s2));
if (uni + bi + tri == 0)
return inf;
return Math.log(uni + bi + tri);
}
/**
* 序列标注
* @param charArray 观测序列
* @return 标注序列
*/
public char[] tag(char[] charArray)
{
if (charArray.length == 0) return new char[0];
if (charArray.length == 1) return new char[]{'s'};
char[] tag = new char[charArray.length];
double[][] now = new double[4][4];
double[] first = new double[4];
// link[i][s][t] := 第i个节点在前一个状态是s,当前状态是t时,前2个状态的tag的值
int[][][] link = new int[charArray.length][4][4];
// 第一个字,只可能是bs
for (int s = 0; s < 4; ++s)
{
double p = (s == 1 || s == 2) ? inf : log_prob(bos, bos, new char[]{charArray[0], id2tag[s]});
first[s] = p;
}
// 第二个字,尚不能完全利用TriGram
for (int f = 0; f < 4; ++f)
{
for (int s = 0; s < 4; ++s)
{
double p = first[f] + log_prob(bos, new char[]{charArray[0], id2tag[f]}, new char[]{charArray[1], id2tag[s]});
now[f][s] = p;
link[1][f][s] = f;
}
}
// 第三个字开始,利用TriGram标注
double[][] pre = new double[4][4];
for (int i = 2; i < charArray.length; i++)
{
// swap(now, pre)
double[][] _ = pre;
pre = now;
now = _;
// end of swap
for (int s = 0; s < 4; ++s)
{
for (int t = 0; t < 4; ++t)
{
now[s][t] = -1e20;
for (int f = 0; f < 4; ++f)
{
double p = pre[f][s] + log_prob(new char[]{charArray[i - 2], id2tag[f]},
new char[]{charArray[i - 1], id2tag[s]},
new char[]{charArray[i], id2tag[t]});
if (p > now[s][t])
{
now[s][t] = p;
link[i][s][t] = f;
}
}
}
}
}
double score = inf;
int s = 0;
int t = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (now[i][j] > score)
{
score = now[i][j];
s = i;
t = j;
}
}
}
for (int i = link.length - 1; i >= 0; --i)
{
tag[i] = id2tag[t];
int f = link[i][s][t];
t = s;
s = f;
}
return tag;
}
/**
* 安全除法
* @param v1
* @param v2
* @return
*/
private static double div(int v1, int v2)
{
if (v2 == 0) return 0.0;
return v1 / (double) v2;
}
/**
* 安全除法
* @param v1
* @param v2
* @return
*/
private static double div(double v1, double v2)
{
if (v2 == 0) return 0.0;
return v1 / v2;
}
@Override
public void save(DataOutputStream out) throws Exception
{
out.writeDouble(l1);
out.writeDouble(l2);
out.writeDouble(l3);
tf.save(out);
}
@Override
public boolean load(ByteArray byteArray)
{
l1 = byteArray.nextDouble();
l2 = byteArray.nextDouble();
l3 = byteArray.nextDouble();
tf.load(byteArray);
return true;
}
}
|
package com.ahao.preferencelibrary.preference;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION_CODES;
import android.support.annotation.DrawableRes;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.ahao.preferencelibrary.R;
public class Preference extends android.preference.Preference {
private boolean _isInitialized = false;
private int _iconResId;
private Drawable _icon;
protected void init(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes) {
setLayoutResource(R.layout.mpl__preference);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Preference, defStyleAttr, defStyleRes);
_iconResId = a.getResourceId(R.styleable.Preference_icon, 0);
a.recycle();
}
@TargetApi(VERSION_CODES.LOLLIPOP)
public Preference(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
if (!_isInitialized) {
_isInitialized = true;
init(context, attrs, defStyleAttr, defStyleRes);
}
}
/**
* Sets the icon for this Preference with a Drawable.
* This icon will be placed into the ID
* {@link android.R.id#icon} within the View created by
* {@link #onCreateView(ViewGroup)}.
*
* @param icon The optional icon for this Preference.
*/
public void setIcon(Drawable icon) {
if ((icon == null && _icon != null) || (icon != null && _icon != icon)) {
_icon = icon;
notifyChanged();
}
}
/**
* Sets the icon for this Preference with a resource ID.
*
* @param iconResId The icon as a resource ID.
* @see #setIcon(Drawable)
*/
public void setIconCompat(@DrawableRes int iconResId) {
if (_iconResId != iconResId) {
_iconResId = iconResId;
setIcon(ContextCompat.getDrawable(getContext(), iconResId));
}
}
/**
* Returns the icon of this Preference.
*
* @return The icon.
* @see #setIcon(Drawable)
*/
public Drawable getIconCompat() {
return _icon;
}
public Preference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (!_isInitialized) {
_isInitialized = true;
init(context, attrs, defStyleAttr, 0);
}
}
public Preference(Context context, AttributeSet attrs) {
super(context, attrs);
if (!_isInitialized) {
_isInitialized = true;
init(context, attrs, 0, 0);
}
}
public Preference(Context context) {
super(context);
if (!_isInitialized) {
_isInitialized = true;
init(context, null, 0, 0);
}
}
@Override
protected void onBindView(final View view) {
super.onBindView(view);
final ImageView imageView = (ImageView) view.findViewById(R.id.icon);
if (imageView != null) {
if (_iconResId != 0 || _icon != null) {
if (_icon == null)
_icon = ContextCompat.getDrawable(getContext(), _iconResId);
if (_icon != null)
imageView.setImageDrawable(_icon);
}
imageView.setVisibility(_icon != null ? View.VISIBLE : View.GONE);
}
final View imageFrame = view.findViewById(R.id.icon_frame);
if (imageFrame != null) {
imageFrame.setVisibility(_icon != null ? View.VISIBLE : View.GONE);
}
}
}
|
/*
* Copyright © 2018 Apple Inc. and the ServiceTalk project 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 io.servicetalk.redis.netty;
import io.servicetalk.client.api.RetryableException;
import io.servicetalk.concurrent.BlockingIterable;
import io.servicetalk.concurrent.BlockingIterator;
import io.servicetalk.concurrent.api.Executor;
import io.servicetalk.concurrent.api.Executors;
import io.servicetalk.redis.api.BlockingPubSubRedisConnection;
import io.servicetalk.redis.api.BlockingRedisCommander;
import io.servicetalk.redis.api.BlockingTransactedRedisCommander;
import io.servicetalk.redis.api.PubSubRedisMessage;
import io.servicetalk.redis.api.RedisException;
import io.servicetalk.redis.api.RedisProtocolSupport;
import io.servicetalk.redis.api.RedisProtocolSupport.BitfieldOperations.Get;
import io.servicetalk.redis.api.RedisProtocolSupport.BitfieldOperations.Incrby;
import io.servicetalk.redis.api.RedisProtocolSupport.BitfieldOperations.Overflow;
import io.servicetalk.redis.api.RedisProtocolSupport.BitfieldOperations.Set;
import io.servicetalk.redis.api.RedisProtocolSupport.ExpireDuration;
import io.servicetalk.redis.api.RedisProtocolSupport.LongitudeLatitudeMember;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import java.nio.channels.ClosedChannelException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;
import static io.servicetalk.concurrent.internal.Await.awaitIndefinitely;
import static io.servicetalk.redis.api.RedisProtocolSupport.BitfieldOverflow.FAIL;
import static io.servicetalk.redis.api.RedisProtocolSupport.BitfieldOverflow.SAT;
import static io.servicetalk.redis.api.RedisProtocolSupport.GeoradiusOrder.ASC;
import static io.servicetalk.redis.api.RedisProtocolSupport.GeoradiusUnit.KM;
import static io.servicetalk.redis.api.RedisProtocolSupport.GeoradiusWithcoord.WITHCOORD;
import static io.servicetalk.redis.api.RedisProtocolSupport.GeoradiusWithdist.WITHDIST;
import static io.servicetalk.redis.api.RedisProtocolSupport.IntegerType.I05;
import static io.servicetalk.redis.api.RedisProtocolSupport.IntegerType.U02;
import static io.servicetalk.redis.api.RedisProtocolSupport.IntegerType.U04;
import static io.servicetalk.redis.api.RedisProtocolSupport.IntegerType.U08;
import static io.servicetalk.redis.api.RedisProtocolSupport.SetCondition.NX;
import static io.servicetalk.redis.api.RedisProtocolSupport.SetExpire.EX;
import static io.servicetalk.redis.netty.SubscribedRedisClientTest.publishTestMessage;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.either;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeThat;
public class BlockingRedisCommanderTest extends BaseRedisClientTest {
protected BlockingRedisCommander commandClient;
@Before
public void createCommandClient() {
commandClient = getEnv().client.asBlockingCommander();
}
@Test
public void simpleResponseTypes() throws Exception {
assertThat(commandClient.ping(), is("PONG"));
assertThat(commandClient.ping("my-pong"), is("my-pong"));
assertThat(commandClient.ping(""), is(""));
assertThat(commandClient.del(key("a-key")), is(greaterThanOrEqualTo(0L)));
assertThat(commandClient.get("missing-key"), is(nullValue()));
assertThat(commandClient.set(key("a-key"), "a-value1"), is("OK"));
assertThat(commandClient.get(key("a-key")), is("a-value1"));
assertThat(commandClient.set(key("a-key"), "a-value2", new ExpireDuration(EX, 10L), null), is("OK"));
assertThat(commandClient.get(key("a-key")), is("a-value2"));
assertThat(commandClient.set(key("exp-key"), "exp-value", null, NX), is(anyOf(nullValue(), equalTo("OK"))));
assertThat(commandClient.zadd(key("a-zset"), null, null, 1, "one"), is(either(equalTo(0L)).or(equalTo(1L))));
assertThat(commandClient.zrank(key("a-zset"), "one"), is(0L));
assertThat(commandClient.zrank("missing-key", "missing-member"), is(nullValue()));
if (getEnv().serverVersion[0] >= 3) {
assertThat(commandClient.zaddIncr(key("a-zset"), null, null, 1, "one"), is(2.0));
}
if (getEnv().serverVersion[0] >= 5) {
assertThat(commandClient.zpopmax(key("a-zset")), contains("2", "one"));
}
assertThat(commandClient.blpop(singletonList("missing-key"), 1), is(nullValue()));
assertThat(commandClient.sadd(key("a-set-1"), "a", "b", "c"), is(greaterThanOrEqualTo(0L)));
assertThat(commandClient.sadd(key("a-set-2"), "c", "d", "e"), is(greaterThanOrEqualTo(0L)));
assertThat(commandClient.sdiff(key("a-set-1"), key("a-set-2"), "missing-key"), containsInAnyOrder("a", "b"));
assertThat(commandClient.sdiffstore(key("diff"), key("a-set-1"), key("a-set-2"), "missing-key"), is(2L));
}
@Test
public void argumentVariants() throws Exception {
assertThat(commandClient.mset(key("key0"), "val0"), is("OK"));
assertThat(commandClient.mset(key("key1"), "val1", key("key2"), "val2", key("key3"), "val3"), is("OK"));
final List<RedisProtocolSupport.KeyValue> keyValues = IntStream.range(4, 10)
.mapToObj(i -> new RedisProtocolSupport.KeyValue(key("key" + i), "val" + i))
.collect(toList());
assertThat(commandClient.mset(keyValues), is("OK"));
assertThat(commandClient.mget(key("key0")), contains("val0"));
assertThat(commandClient.mget(key("key1"), key("key2"), key("key3")), contains("val1", "val2", "val3"));
final List<String> keys = keyValues.stream().map(kv -> kv.key.toString()).collect(toList());
final List<String> expectedValues = keyValues.stream().map(kv -> kv.value.toString()).collect(toList());
assertThat(commandClient.mget(keys), is(expectedValues));
}
@Test
public void unicodeNotMangled() throws Exception {
assertThat(commandClient.set(key("\u263A"), "\u263A-foo"), is("OK"));
assertThat(commandClient.get(key("\u263A")), is("\u263A-foo"));
}
@Test
public void bitfieldOperations() throws Exception {
// Disable these tests for Redis 2 and below
assumeThat(getEnv().serverVersion[0], is(greaterThanOrEqualTo(3)));
commandClient.del(key("bf"));
List<Long> results = commandClient.bitfield(key("bf"), asList(new Incrby(I05, 100L, 1L), new Get(U04, 0L)));
assertThat(results, contains(1L, 0L));
results.clear();
for (int i = 0; i < 4; i++) {
results.addAll(commandClient.bitfield(key("bf"), asList(
new Incrby(U02, 100L, 1L),
new Overflow(SAT),
new Incrby(U02, 102L, 1L))));
}
assertThat(results, contains(1L, 1L, 2L, 2L, 3L, 3L, 0L, 3L));
results = commandClient.bitfield(key("bf"), asList(new Overflow(FAIL), new Incrby(U02, 102L, 1L)));
assertThat(results, contains(nullValue()));
commandClient.del(key("bf"));
// bitfield doesn't support non-numeric offsets (which are used for bitsize-based offsets)
// but it's possible to get the same behaviour by using the bit size provided by the type enum,
// ie. the following is equivalent to:
// BITFIELD bf-<key> SET u8 #2 200 GET u8 #2 GET u4 #4 GET u4 #5
results = commandClient.bitfield(key("bf"), asList(
new Set(U08, U08.getBitSize() * 2, 200L),
new Get(U08, U08.getBitSize() * 2),
new Get(U04, U04.getBitSize() * 4),
new Get(U04, U04.getBitSize() * 5)));
assertThat(results, contains(0L, 200L, 12L, 8L));
}
@Test
public void commandWithSubCommand() throws Exception {
assertThat(commandClient.commandInfo("GET"), hasSize(1));
assertThat(commandClient.objectRefcount("missing-key"), is(nullValue()));
assertThat(commandClient.objectEncoding("missing-key"), is(nullValue()));
if (getEnv().serverVersion[0] >= 4) {
assertThat(commandClient.objectHelp(), hasSize(greaterThanOrEqualTo(5)));
}
}
@Test
public void infoWithAggregationDoesNotThrow() throws Exception {
assertThat(commandClient.info().isEmpty(), is(false));
}
@SuppressWarnings("unchecked")
@Test
public void variableResponseTypes() throws Exception {
// Disable these tests for Redis 2 and below
assumeThat(getEnv().serverVersion[0], is(greaterThanOrEqualTo(3)));
assertThat(commandClient.zrem(key("Sicily"), asList("Palermo", "Catania")), is(lessThanOrEqualTo(2L)));
final Long geoaddLong = commandClient.geoadd(key("Sicily"),
asList(new LongitudeLatitudeMember(13.361389d, 38.115556d, "Palermo"),
new LongitudeLatitudeMember(15.087269d, 37.502669d, "Catania")));
assertThat(geoaddLong, is(2L));
final List<String> georadiusBuffers = commandClient.georadius(key("Sicily"), 15d, 37d, 200d, KM);
assertThat(georadiusBuffers, contains("Palermo", "Catania"));
final List georadiusMixedList = commandClient.georadius(key("Sicily"), 15d, 37d, 200d, KM, WITHCOORD, WITHDIST, null, 5L, ASC, null, null);
final Matcher georadiusResponseMatcher = contains(
contains(is("Catania"), startsWith("56."), contains(startsWith("15."), startsWith("37."))),
contains(is("Palermo"), startsWith("190."), contains(startsWith("13."), startsWith("38."))));
assertThat(georadiusMixedList, georadiusResponseMatcher);
assertThat(commandClient.geodist(key("Sicily"), "Palermo", "Catania"), is(greaterThan(0d)));
assertThat(commandClient.geodist(key("Sicily"), "foo", "bar"), is(nullValue()));
assertThat(commandClient.geopos(key("Sicily"), "Palermo", "NonExisting", "Catania"), contains(
contains(startsWith("13."), startsWith("38.")), is(nullValue()), contains(startsWith("15."), startsWith("37."))));
final List<String> evalBuffers = commandClient.evalList("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
2L, asList("key1", "key2"), asList("first", "second"));
assertThat(evalBuffers, contains("key1", "key2", "first", "second"));
final String evalChars = commandClient.eval("return redis.call('set','foo','bar')",
0L, emptyList(), emptyList());
assertThat(evalChars, is("OK"));
final Long evalLong = commandClient.evalLong("return 10", 0L, emptyList(), emptyList());
assertThat(evalLong, is(10L));
final List<?> evalMixedList = commandClient.evalList("return {1,2,{3,'four'}}", 0L, emptyList(), emptyList());
assertThat(evalMixedList, contains(1L, 2L, asList(3L, "four")));
}
@Test
public void transactionEmpty() throws Exception {
final List<?> results = commandClient.multi().exec();
assertThat(results, is(empty()));
}
@Test
public void transactionExec() throws Exception {
BlockingTransactedRedisCommander tcc = commandClient.multi();
tcc.del(key("a-key"));
tcc.set(key("a-key"), "a-value3");
tcc.ping("in-transac");
tcc.get(key("a-key"));
final List<?> results = tcc.exec();
assertThat(results, contains(1L, "OK", "in-transac", "a-value3"));
}
@Test
public void transactionDiscard() throws Exception {
BlockingTransactedRedisCommander tcc = commandClient.multi();
tcc.ping("in-transac");
final String result = tcc.discard();
assertThat(result, is("OK"));
}
@Test
public void transactionPartialFailure() throws Exception {
BlockingTransactedRedisCommander tcc = commandClient.multi();
tcc.set(key("ptf"), "foo");
tcc.lpop(key("ptf"));
final List<?> results = tcc.exec();
assertThat(results, contains(is("OK"), instanceOf(RedisException.class)));
assertThat(((RedisException) results.get(1)).getMessage(), startsWith("WRONGTYPE"));
}
@Test
public void transactionClose() throws Exception {
BlockingTransactedRedisCommander tcc = commandClient.multi();
tcc.close();
thrown.expect(ClosedChannelException.class);
tcc.ping();
}
@Test
public void monitor() throws Exception {
Executor executor = Executors.newFixedSizeExecutor(1);
try {
BlockingIterable<String> iterable = commandClient.monitor();
BlockingIterator<String> iterator = iterable.iterator();
CountDownLatch latch = new CountDownLatch(1);
executor.execute(() -> {
try {
commandClient.ping();
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
});
latch.await();
assertThat(iterator.next(), is("OK"));
assertThat(iterator.next(), endsWith("\"PING\""));
} finally {
awaitIndefinitely(executor.closeAsync());
}
}
@Test
public void pubSubMultipleSubscribes() throws Exception {
final BlockingPubSubRedisConnection pubSubClient1 = commandClient.subscribe(key("channel-1"));
BlockingIterable<PubSubRedisMessage> messages1 = pubSubClient1.getMessages();
BlockingIterator<PubSubRedisMessage> iterator1 = messages1.iterator();
// Publish a test message
publishTestMessage(key("channel-1"));
// Check ping request get proper response
assertThat(pubSubClient1.ping().getCharSequenceValue(), is(""));
// Subscribe to a pattern on the same connection
final BlockingPubSubRedisConnection pubSubClient2 = pubSubClient1.psubscribe(key("channel-2*"));
BlockingIterable<PubSubRedisMessage> messages2 = pubSubClient2.getMessages();
BlockingIterator<PubSubRedisMessage> iterator2 = messages2.iterator();
// Let's throw a wrench and psubscribe a second time to the same pattern
final BlockingPubSubRedisConnection pubSubClient3 = pubSubClient1.psubscribe(key("channel-2*"));
BlockingIterable<PubSubRedisMessage> messages3 = pubSubClient3.getMessages();
BlockingIterator<PubSubRedisMessage> iterator3 = messages3.iterator();
try {
iterator3.next();
fail("Should have failed");
} catch (IllegalStateException e) {
// Expected
}
// Publish another test message
publishTestMessage(key("channel-202"));
// Check ping request get proper response
assertThat(pubSubClient1.ping("my-pong").getCharSequenceValue(), is("my-pong"));
// Cancel the subscriber, which issues an UNSUBSCRIBE behind the scenes
pubSubClient1.close();
assertThat(iterator1.next(), allOf(
hasProperty("channel", equalTo(key("channel-1"))),
hasProperty("charSequenceValue", equalTo("test-message"))));
// Check the second psubscribe subscription never got anything beyond the subscription confirmation
iterator3.close();
// Cancel the subscriber, which issues an PUNSUBSCRIBE behind the scenes
iterator2.close();
assertThat(iterator2.next(), allOf(
hasProperty("channel", equalTo(key("channel-202"))),
hasProperty("pattern", equalTo(key("channel-2*"))),
hasProperty("charSequenceValue", equalTo("test-message"))));
// It is an error to keep using the pubsub client after all subscriptions have been terminated
try {
pubSubClient1.ping();
fail("Should have failed");
} catch (final RetryableException expected) {
// Expected
}
}
private static String key(CharSequence key) {
return key + "-brct";
}
}
|
/*
* Copyright (c) 2011-2013 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package org.vertx.java.core.sockjs.impl;
import org.vertx.java.core.Handler;
import org.vertx.java.core.VoidHandler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.core.http.ServerWebSocket;
import org.vertx.java.core.http.impl.WebSocketMatcher;
import org.vertx.java.core.impl.VertxInternal;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.core.logging.impl.LoggerFactory;
import org.vertx.java.core.sockjs.SockJSSocket;
import java.util.Map;
/**
* @author <a href="http://tfox.org">Tim Fox</a>
*/
class WebSocketTransport extends BaseTransport {
private static final Logger log = LoggerFactory.getLogger(WebSocketTransport.class);
WebSocketTransport(final VertxInternal vertx, WebSocketMatcher wsMatcher,
RouteMatcher rm, String basePath, final Map<String, Session> sessions,
final JsonObject config,
final Handler<SockJSSocket> sockHandler) {
super(vertx, sessions, config);
String wsRE = basePath + COMMON_PATH_ELEMENT_RE + "websocket";
wsMatcher.addRegEx(wsRE, new Handler<WebSocketMatcher.Match>() {
public void handle(final WebSocketMatcher.Match match) {
if (log.isTraceEnabled()) log.trace("WS, handler");
final Session session = new Session(vertx, sessions, config.getLong("heartbeat_period"), sockHandler);
session.setInfo(match.ws.localAddress(), match.ws.remoteAddress(), match.ws.uri(), match.ws.headers());
session.register(new WebSocketListener(match.ws, session));
}
});
rm.getWithRegEx(wsRE, new Handler<HttpServerRequest>() {
public void handle(HttpServerRequest request) {
if (log.isTraceEnabled()) log.trace("WS, get: " + request.uri());
request.response().setStatusCode(400);
request.response().end("Can \"Upgrade\" only to \"WebSocket\".");
}
});
rm.allWithRegEx(wsRE, new Handler<HttpServerRequest>() {
public void handle(HttpServerRequest request) {
if (log.isTraceEnabled()) log.trace("WS, all: " + request.uri());
request.response().headers().set("Allow", "GET");
request.response().setStatusCode(405);
request.response().end();
}
});
}
private static class WebSocketListener implements TransportListener {
final ServerWebSocket ws;
final Session session;
boolean closed;
WebSocketListener(final ServerWebSocket ws, final Session session) {
this.ws = ws;
this.session = session;
ws.dataHandler(new Handler<Buffer>() {
public void handle(Buffer data) {
if (!session.isClosed()) {
String msgs = data.toString();
if (msgs.equals("")) {
//Ignore empty frames
} else if ((msgs.startsWith("[\"") && msgs.endsWith("\"]")) ||
(msgs.startsWith("\"") && msgs.endsWith("\""))) {
session.handleMessages(msgs);
} else {
//Invalid JSON - we close the connection
close();
}
}
}
});
ws.closeHandler(new VoidHandler() {
public void handle() {
closed = true;
session.shutdown();
}
});
ws.exceptionHandler(new Handler<Throwable>() {
public void handle(Throwable t) {
closed = true;
session.shutdown();
session.handleException(t);
}
});
}
public void sendFrame(final String body) {
if (log.isTraceEnabled()) log.trace("WS, sending frame");
if (!closed) {
ws.writeTextFrame(body);
}
}
public void close() {
if (!closed) {
ws.close();
session.shutdown();
closed = true;
}
}
public void sessionClosed() {
session.writeClosed(this);
closed = true;
ws.close();
}
}
}
|
package com.muscidae.parrot.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
/** @deprecated */
@Deprecated
@SpringBootApplication( exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class } )
public class ParrotConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ParrotConfigApplication.class, args);
}
}
|
package com.github.aznamier.keycloak.event.provider;
import java.util.HashMap;
import java.util.Map;
import org.keycloak.events.Event;
import org.keycloak.events.EventListenerProvider;
import org.keycloak.events.EventListenerTransaction;
import org.keycloak.events.admin.AdminEvent;
import org.keycloak.models.KeycloakSession;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.AMQP.BasicProperties.Builder;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitMqEventListenerProvider implements EventListenerProvider {
private RabbitMqConfig cfg;
private ConnectionFactory factory;
private KeycloakSession session;
private EventListenerTransaction tx = new EventListenerTransaction(this::publishAdminEvent, this::publishEvent);
public RabbitMqEventListenerProvider(RabbitMqConfig cfg, KeycloakSession session) {
this.cfg = cfg;
this.factory = new ConnectionFactory();
this.factory.setUsername(cfg.getUsername());
this.factory.setPassword(cfg.getPassword());
this.factory.setVirtualHost(cfg.getVhost());
this.factory.setHost(cfg.getHostUrl());
this.factory.setPort(cfg.getPort());
this.session = session;
this.session.getTransactionManager().enlistAfterCompletion(tx);
}
@Override
public void close() {
}
@Override
public void onEvent(Event event) {
tx.addEvent(event);
}
@Override
public void onEvent(AdminEvent adminEvent, boolean includeRepresentation) {
tx.addAdminEvent(adminEvent, includeRepresentation);
}
private void publishEvent(Event event) {
EventClientNotificationMqMsg msg = EventClientNotificationMqMsg.create(event);
String routingKey = RabbitMqConfig.calculateRoutingKey(event);
String messageString = RabbitMqConfig.writeAsJson(msg, true);
BasicProperties msgProps = this.getMessageProps(EventClientNotificationMqMsg.class.getName());
this.publishNotification(messageString, msgProps, routingKey);
}
private void publishAdminEvent(AdminEvent adminEvent, boolean includeRepresentation) {
EventAdminNotificationMqMsg msg = EventAdminNotificationMqMsg.create(adminEvent);
String routingKey = RabbitMqConfig.calculateRoutingKey(adminEvent);
String messageString = RabbitMqConfig.writeAsJson(msg, true);
BasicProperties msgProps = this.getMessageProps(EventAdminNotificationMqMsg.class.getName());
this.publishNotification(messageString,msgProps, routingKey);
}
private BasicProperties getMessageProps(String className) {
Map<String,Object> headers = new HashMap<String,Object>();
headers.put("__TypeId__", className);
Builder propsBuilder = new AMQP.BasicProperties.Builder()
.appId("Keycloak")
.headers(headers)
.contentType("application/json")
.contentEncoding("UTF-8");
return propsBuilder.build();
}
private void publishNotification(String messageString, BasicProperties props, String routingKey) {
try {
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.basicPublish(cfg.getExchange(), routingKey, props, messageString.getBytes());
System.out.println("keycloak-to-rabbitmq SUCCESS sending message: " + routingKey);
channel.close();
conn.close();
} catch (Exception ex) {
System.err.println("keycloak-to-rabbitmq ERROR sending message: " + routingKey);
ex.printStackTrace();
}
}
}
|
/*
* Constellation - An open source and standard compliant SDI
* http://www.constellation-sdi.org
*
* Copyright 2014 Geomatys.
*
* 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.constellation.provider;
import org.apache.sis.storage.DataStore;
import org.geotoolkit.map.ElevationModel;
import java.util.Date;
import org.opengis.util.GenericName;
/**
*
* @version $Id$
*
* @author Johann Sorel (Geomatys)
*/
public interface DataProvider extends Provider<GenericName,Data>{
/**
* Original data store.
* @return
*/
DataStore getMainStore();
ElevationModel getElevationModel(GenericName name);
Data get(String key);
/**
* Get the data related to the given key in given version.
* @return LayerDetails if it is in the data provider, or null if not.
*/
Data get(GenericName key, Date version);
}
|
package liulixiang1988;
import okhttp3.OkHttpClient;
/**
* Created by liulixiang on 16/5/26.
*/
public class Main {
public static void main(String[] args) {
OkHttpDemo demo = new OkHttpDemo();
try {
demo.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import java.lang.Math;
import java.util.HashMap;
public class AutomMotorMethods {
final int WHEELTICKS;
double robotAngle;
double robotFrontAngle;
double[] robotPos = new double[2];
// constructor the sets the value of WHEELTICKS
public AutomMotorMethods(int ticks, double robotStartingAngle, double frontAngleOfRobot,
double robotYPos, double robotXPos) {
WHEELTICKS = ticks;
setRobotAngle(robotStartingAngle);
setRobotFrontAngle(frontAngleOfRobot);
robotPos[0] = robotXPos;
robotPos[1] = robotYPos;
}
// return the amount of ticks the wheel has
public int getWHEELTICKS() {
return WHEELTICKS;
}
public void setRobotAngle(double startingRobotAngle) {
robotAngle = startingRobotAngle;
}
public void setRobotFrontAngle(double frontAngle) {
robotFrontAngle = frontAngle;
}
// returns circumference of mecanum wheels
public double getCircumference() {
double circumference = Math.PI*Math.pow(48, 2);
return circumference;
}
// return current angle of robot
public double getCurrentRobotAngle() {
return robotAngle;
}
public double feetTomm(double feet) {
double mmDistance = feet*304.8;
return mmDistance;
}
// not used
public double secondsAnalyzed(double totalSeconds, double excludedSeconds) {
// subtracting the seconds that are not being counted minus the total seconds
double analyzedSeconds = totalSeconds - excludedSeconds;
return analyzedSeconds;
}
// return number of ticks the robot moved for given time(seconds) amount
public int getTicksCrossed(double analyzedSeconds) {
int numTicks = (int)(analyzedSeconds*560);
return numTicks;
}
/* returns the amount of seconds the robot needs to move for given amount of ticks the
the robot needs to move
*/
public double moveForSeconds(int ticks) {
double secondsAmount = ticks/3500;
return secondsAmount;
}
// returns the distance crossed for given tick amount
public double distanceCrossed(int ticksCrossed) {
double circumference = Math.PI*Math.pow(48, 2);
double distancePerTick = circumference/560;
// distance is in mm = millimiters
double distCrossed = ticksCrossed*distancePerTick;
return distCrossed;
}
// returns the tick amount for the given distance
public int tickForDistance(int distanceInmm) {
double circumference = Math.PI*Math.pow(48, 2);
double distancePerTick = circumference/560;
int distanceToTicks = (int)(distanceInmm/distancePerTick);
// distance is in mm = millimiters
return distanceToTicks;
}
// converts an angle from 0-355 to a distance to move your wheels
public int angleToDistance(double angle) {
double circumference = this.getCircumference();
double splittingCircIntoFour = circumference/4;
double distPer360angle = splittingCircIntoFour/90;
int coverDistance = (int)(distPer360angle*angle);
return coverDistance;
}
// updates angle of robot
public void updateAngle(double newestAngle) {
robotAngle = newestAngle;
}
/*
you give it the wheel you want the know the direction it will spin to according
to the direction the robot will turn to
*/
public String getWheelSpinDirectionFromWantedRotationDirection(String wantedTurnDirection,
String wantedWheel) {
String leftFrontSpinDirection = "";
String leftBackSpinDirection = "";
String rightFrontSpinDirection = "";
String rightBackSpinDirection = "";
/* making a dictionary storing a wheel and it's according spin direction
according to robot spin direction */
HashMap<String, String> wheelDirections = new HashMap<String, String>();
if (wantedTurnDirection == "RIGHT") {
leftFrontSpinDirection = "FORWARDS";
leftBackSpinDirection = "FORWARDS";
rightFrontSpinDirection = "BACKWARDS";
rightBackSpinDirection = "BACKWARDS";
}
else if (wantedTurnDirection == "LEFT") {
leftFrontSpinDirection = "BACKWARDS";
leftBackSpinDirection = "BACKWARDS";
rightFrontSpinDirection = "FORWARDS";
rightBackSpinDirection = "FORWARDS";
}
wheelDirections.put("leftFront", leftFrontSpinDirection);
wheelDirections.put("leftBack", leftBackSpinDirection);
wheelDirections.put("rightFront", rightFrontSpinDirection);
wheelDirections.put("rightBack", rightBackSpinDirection);
String wantedWheelSpinDicrection = wheelDirections.get(wantedWheel);
return wantedWheelSpinDicrection;
}
// returns a number value for an according direction of wheel spin
public int getVelocityNumFromWheelSpinDirection(String wheelDirection) {
HashMap<String, Integer> wheelNumDirection = new HashMap<String, Integer>();
wheelNumDirection.put("FORWARDS", 1);
wheelNumDirection.put("BACKWARDS", -1);
int wheelDirectionNumValue = wheelNumDirection.get(wheelDirection);
return wheelDirectionNumValue;
}
public int findOptimumMovementForRobotRotation(double wantedAngle, String wantedWheel) {
HashMap<String, Integer> wheelDirections = new HashMap<String, Integer>();
String leftFrontSpinDirectionStringValue = "";
String leftBackSpinDirectionStringValue = "";
String rightFrontSpinDirectionStringValue = "";
String rightBackSpinDirectionStringValue = "";
int leftFrontSpinDirection = 0;
int leftBackSpinDirection = 0;
int rightFrontSpinDirection = 0;
int rightBackSpinDirection = 0;
double currentRobotAngle = this.getCurrentRobotAngle();
double distanceFromAngleMovingLeft = Math.abs(wantedAngle - currentRobotAngle);
double distanceFromAngleMovingRight = Math.abs((360-currentRobotAngle) + wantedAngle);
boolean moveLeft = false;
String moveInDirection = "";
if (distanceFromAngleMovingRight > distanceFromAngleMovingLeft) {
moveLeft = true;
moveInDirection = "LEFT";
leftFrontSpinDirectionStringValue = getWheelSpinDirectionFromWantedRotationDirection
(moveInDirection, "leftFront");
leftBackSpinDirectionStringValue = getWheelSpinDirectionFromWantedRotationDirection
(moveInDirection, "leftBack");
rightFrontSpinDirectionStringValue = getWheelSpinDirectionFromWantedRotationDirection
(moveInDirection, "rightFront");
rightBackSpinDirectionStringValue = getWheelSpinDirectionFromWantedRotationDirection
(moveInDirection, "rightback");
leftFrontSpinDirection = getVelocityNumFromWheelSpinDirection
(leftFrontSpinDirectionStringValue);
leftBackSpinDirection = getVelocityNumFromWheelSpinDirection
(leftBackSpinDirectionStringValue);
rightFrontSpinDirection = getVelocityNumFromWheelSpinDirection
(rightFrontSpinDirectionStringValue);
rightBackSpinDirection = getVelocityNumFromWheelSpinDirection
(rightBackSpinDirectionStringValue);
}
else {
moveLeft = false;
moveInDirection = "RIGHT";
leftFrontSpinDirectionStringValue = getWheelSpinDirectionFromWantedRotationDirection
(moveInDirection, "leftFront");
leftBackSpinDirectionStringValue = getWheelSpinDirectionFromWantedRotationDirection
(moveInDirection, "leftBack");
rightFrontSpinDirectionStringValue = getWheelSpinDirectionFromWantedRotationDirection
(moveInDirection, "rightFront");
rightBackSpinDirectionStringValue = getWheelSpinDirectionFromWantedRotationDirection
(moveInDirection, "rightback");
leftFrontSpinDirection = getVelocityNumFromWheelSpinDirection
(leftFrontSpinDirectionStringValue);
leftBackSpinDirection = getVelocityNumFromWheelSpinDirection
(leftBackSpinDirectionStringValue);
rightFrontSpinDirection = getVelocityNumFromWheelSpinDirection
(rightFrontSpinDirectionStringValue);
rightBackSpinDirection = getVelocityNumFromWheelSpinDirection
(rightBackSpinDirectionStringValue);
}
wheelDirections.put("leftFront", leftFrontSpinDirection);
wheelDirections.put("leftBack", leftBackSpinDirection);
wheelDirections.put("rightFront", rightFrontSpinDirection);
wheelDirections.put("rightBack", rightBackSpinDirection);
int wantedWheelValue = wheelDirections.get(wantedWheel);
return wantedWheelValue;
}
public void updatePos(double movementXmm, double movementYmm) {
robotPos[0] += movementXmm;
robotPos[1] += movementYmm;
}
}
|
package com.vsp.dicty.domain.model;
public class Lang implements Comparable<Lang> {
private String langCode;
private String lang;
@Override
public int compareTo(Lang lang) {
return this.lang.compareToIgnoreCase(lang.getLang());
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getLangCode() {
return langCode;
}
public void setLangCode(String langCode) {
this.langCode = langCode;
}
@Override
public String toString() {
return lang;
}
}
|
/*******************************************************************************
* Copyright (c) 2014 Chaupal.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0.html
*******************************************************************************/
package net.jp2p.container.factory.filter;
import net.jp2p.container.factory.ComponentBuilderEvent;
import net.jp2p.container.factory.IComponentFactory;
public abstract class AbstractComponentFactoryFilter<M extends Object>
implements IComponentFactoryFilter {
private IComponentFactory<M> factory;
private boolean accept;
protected AbstractComponentFactoryFilter( IComponentFactory<M> factory ) {
this.factory = factory;
}
protected IComponentFactory<M> getFactory() {
return factory;
}
/**
* Provide the conditions on which the filter will accept the event
* @param event
* @return
*/
protected abstract boolean onAccept( ComponentBuilderEvent event );
@Override
public boolean accept(ComponentBuilderEvent event) {
this.accept = this.onAccept(event);
return accept;
}
@Override
public boolean hasAccepted() {
return accept;
}
}
|
package server;
import java.sql.Date;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import server.dao.MsgDao;
import server.dao.UserDao;
import server.entity.Msg;
import server.entity.Users;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCP;
import com.socket.TCPServer;
/**
* @author LXA 服务端
*/
public class QQServer extends TCPServer
{
UserDao userDao;
MsgDao msgDao;
public QQServer(int serverPort)
{
super(serverPort);
userDao=new UserDao();
msgDao=new MsgDao();
}
/**
* 主函数
* @param args
*/
// public static void main(String[] args)
// {
// new QQServer(MyTools.QQServerPort);
// }
/**
* 处理客户端发来的各种信息
* @param flag 信息标志
* @param message 消息内容
* @param tcp TCP连接
*/
@Override
public void dealWithMessage(Flag flag, String message,TCP tcp)
{
switch(flag)
{
case LOGIN:doLogin(message,tcp);break;//如果是登录
case GET_FRIEND_INFO:doGetFriendInfo(message,tcp);break;//处理用户发来的请求好友资料的事件
case REGISTER:doRegister(message,tcp);break;
case QUN_CHAT:doQunChat(message,tcp);break;
case UNDERLINE_MESSAGE:doUnderlineMessage(message,tcp);break;//处理用户发来的离线消息
default:break;
}
}
/**
* 处理客户端退出的相关事件
* @param tcp TCP连接
*/
@Override
public void dealWithExit(TCP tcp)
{
refreshAllUserFriendList();
userDao.updateUserState(tcp.getClientName(), -1+"");//将用户的状态更新到数据库中去
userDao.setLastExit(tcp.getClientName());
System.out.println("用户"+tcp.getClientName()+"已退出!");
showOnlineNumber();
}
/*
* 服务端启动后要做的事情
*/
@Override
public void afterServerStart()
{
System.out.println("QQ服务器已启动!");
showOnlineNumber();
}
/**
* 处理客户端登录
* @param message
*/
public void doLogin(String message,TCP tcp)
{
System.out.println("客户端"+tcp.getClientIP()+"尝试登录……");
String[] temp=message.split(MyTools.SPLIT1);
String name=temp[0];//用户名
String password=temp[1];//用户密码
int port=Integer.parseInt(temp[2]);//用户端口号
int userState=Integer.parseInt(temp[3]);//用户状态
System.out.println("nihao");
if(checkNameAndPwd(name, password))//如果用户名和密码都正确
{
if(checkIsLoginAgain(name))//如果重复登录
tcp.sendMessage(Flag.LOGIN+MyTools.FLAGEND+Flag.FAILED+MyTools.SPLIT1+"您不能重复登录!");
else
{
tcp.setClientName(name);//设置登录用户的名字到TCP中保存
tcp.setClientServerPort(port);//保存当前登录用户的端口
tcp.setUserState(userState);//保存当前登录用户的状态
userDao.updateUserState(name, userState+"");//将用户的状态保存到数据库中去
userDao.setLastLogin(name);
userDao.setIP(tcp.getClientIP(), name);//将用户的IP存往数据库
tcp.sendMessage(Flag.LOGIN+MyTools.FLAGEND+Flag.SUCCESS+MyTools.SPLIT1+getCurrentUserInfo(tcp));//发送一个消息给用户提示登录成功
try
{
Thread.sleep(50);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
refreshAllUserFriendList();//刷新所有用户的好友列表,但不包括当前登录用户
try
{
Thread.sleep(50);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
sendUnreadMessage(tcp);//发送用户未读消息
showOnlineNumber();//显示当前在线人数
}
}
else//如果登录失败
{
tcp.sendMessage(Flag.LOGIN+MyTools.FLAGEND+Flag.FAILED+MyTools.SPLIT1+"用户名或密码错误!");
}
}
/**
* 处理用户发来的请求好友资料的事件
* @param message
* @param tcp
*/
public void doGetFriendInfo(String message,TCP tcp)
{
Users users = userDao.queryByName(tcp.getClientName());
StringBuffer sb=new StringBuffer();
sb.append("用户ID:"+users.getId()+"\n");
sb.append("用户名:"+users.getName()+"\n");
sb.append("性别:"+users.getGender()+"\n");
sb.append("电子邮件:"+users.getEmail()+"\n");
sb.append("最后一次登录:"+users.getLastLogin()+"\n");
sb.append("最后一次退出:"+users.getLastExit()+"\n");
sb.append("个性签名:"+users.getSignature()+"\n");
sb.append("生日:"+users.getBirthday()+"\n");
String userInfo=new String(sb);
tcp.sendMessage(Flag.GET_FRIEND_INFO+MyTools.FLAGEND+userInfo);
}
/**
* 处理用户发来的注册请求
* @param message
* @param tcp
*/
public void doRegister(String message,TCP tcp)
{
String[] temp=message.split(MyTools.SPLIT1);
String name=temp[0];//姓名
String password=temp[1];//密码
String sex=temp[2];//性别
String email=temp[3];//电子邮件
Date birthday;//生日
String repost="恭喜你,注册成功!";//给用户的回复
try
{
System.out.println("生日:"+temp[4]);
birthday=Date.valueOf(temp[4]);
System.out.println(birthday);
}
catch (Exception e)
{
birthday=Date.valueOf("1992-07-28");
repost+="\n但是您的生日日期格式不正确,系统已给您设置成默认的生日:1992-07-28!";
}
String signature=temp[5];//个性签名
String headImageIdx=temp[6];//头像索引
Users users=new Users(name, password, sex, email, signature, headImageIdx, birthday);
if(userDao.checkUserIsExit(name))
tcp.sendMessage(Flag.REGISTER+MyTools.FLAGEND+Flag.FAILED+MyTools.SPLIT1+"用户名已存在!");
else
{
try
{
userDao.add(users);
tcp.sendMessage(Flag.REGISTER+MyTools.FLAGEND+Flag.SUCCESS+MyTools.SPLIT1+repost);
}
catch (SQLException e)
{
e.printStackTrace();
tcp.sendMessage(Flag.REGISTER+MyTools.FLAGEND+Flag.FAILED+MyTools.SPLIT1+"由于某些原因,注册失败!");
}
}
}
/**
* 检查登录用户的用户名和密码是否正确
* @param name
* @param password
* @return
*/
public boolean checkNameAndPwd(String name,String password)
{
boolean success=false;
if(userDao.checkNameAndPwd(name, password))
success=true;
return success;
}
/**
* 检查用户是否重复登录
* @param name 用户名
* @return 返回的真假值
*/
public boolean checkIsLoginAgain(String name)
{
boolean res=false;
for(TCP tcp:tcpSockets)
if(tcp.getClientName().equals(name))
{
res=true;
break;
}
return res;
}
/**
* 初始化客户端信息
* @param tcp
*/
public void initClientInfo(TCP tcp)
{
tcp.sendMessage(Flag.USERINFO+MyTools.FLAGEND+getCurrentUserInfo(tcp));
}
/**
* 刷新所有在线用户的好友列表
*/
public void refreshAllUserFriendList()
{
for(TCP tcp:tcpSockets)
tcp.sendMessage(Flag.FRIENDS_LIST+MyTools.FLAGEND+getAllUsersInfo());
}
/**
* 获取当前用户的信息
* @param t
* @return
*/
public String getCurrentUserInfo(TCP tcp)
{
//示例:用户名;状态;个性签名;头像
StringBuffer sb=new StringBuffer();
String userName=tcp.getClientName();
Users users=userDao.queryByName(userName);//从数据库中查询用户信息
sb.append(userName+MyTools.SPLIT2//用户名
+tcp.getUserState()+MyTools.SPLIT2//状态
+users.getSignature()+MyTools.SPLIT2//签名
+users.getHeadImg());//头像
String userInfo=new String(sb);//返回当前登录用户自己的信息
return userInfo;
}
/**
* 将所有用户的信息转换成字符串
* @return
*/
public String getAllUsersInfo()
{
//示例:刘显安,192.168.1.1,8888;吴志强,192.168.1.2,6666
StringBuffer sb=new StringBuffer();
sb.append("所有在线用户"+MyTools.SPLIT2+"所有不在线用户"+MyTools.SPLIT2+"我的好友"+MyTools.SPLIT1);
for(TCP tcp:tcpSockets)
{
if(tcp.getUserState()!=4)//因为4表示隐身
{
System.out.println("客户端名"+tcp.getClientName());
sb.append(tcp.getClientName()+MyTools.SPLIT3//用户名
+tcp.getClientIP()+MyTools.SPLIT3//IP
+tcp.getClientServerPort()+MyTools.SPLIT3//端口号
+userDao.queryByName(tcp.getClientName()).getHeadImg()+MyTools.SPLIT3//头像
+tcp.getUserState()+MyTools.SPLIT2);//用户状态
}
}
String onlineUser=new String(sb);
onlineUser=onlineUser.substring(0,onlineUser.length()-1);//去掉最后一个逗号
onlineUser+=MyTools.SPLIT1;//加上一个分号
sb=new StringBuffer();
ArrayList<Users> userList=userDao.queryAll();
for(Users users:userList)
{
if(users.getState().equals("-1")||users.getState().equals("4")||users.getState()==null)
{
sb.append(users.getName()+MyTools.SPLIT3
+"下线或隐身"+MyTools.SPLIT3
+"0"+MyTools.SPLIT3
+users.getHeadImg()+MyTools.SPLIT3
+"-1"+MyTools.SPLIT2);
}
}
String underlineUser=new String(sb);
if(!underlineUser.equals(""))
underlineUser=underlineUser.substring(0,underlineUser.length()-1);//去掉最后一个逗号
underlineUser+=MyTools.SPLIT1;//加上一个分号
String myfriend="无";
return onlineUser+underlineUser+myfriend;
}
/**
* 显示当前在线人数
*/
public void showOnlineNumber()
{
System.out.println("当前总在线人数:"+tcpSockets.size());
}
public void doQunChat(String message,TCP tcp)
{
for(TCP t:tcpSockets)
t.sendMessage(Flag.QUN_CHAT+MyTools.FLAGEND+message);
}
/**
* 处理用户发来的离线消息
* @param message
* @param tcp
*/
public void doUnderlineMessage(String message,TCP tcp)
{
int sendFrom=userDao.queryByName(tcp.getClientName()).getId();
int sendTo=userDao.queryByName(message.split(MyTools.SPLIT1)[0]).getId();
Msg msg=new Msg(message.split(MyTools.SPLIT1)[1],sendFrom,sendTo,"", "");
try
{
msgDao.insertMsg(msg);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
/**
* 给用户发送未读消息
*/
public void sendUnreadMessage(TCP tcp)
{
String userName=tcp.getClientName();
int userID=userDao.queryByName(userName).getId();
ArrayList<Msg> msgs=(ArrayList<Msg>) msgDao.selectMsgBySendTo(userID);
StringBuffer sb=new StringBuffer();
sb.append(Flag.UNDERLINE_MESSAGE+MyTools.FLAGEND);
if(msgs.size()>0)
{
for(Msg msg:msgs)
{
sb.append(userDao.queryById(msg.getSendFrom()).getName()+"("
+msg.getSendTime()+"):\n"
+msg.getMsgContent()+"\n");
}
String unreadMessage=new String(sb);
tcp.sendMessage(unreadMessage);
System.out.println("给用户发送未读离线消息成功!");
msgDao.deleteMsgBySendTO(userID);
System.out.println("删除用户未读消息成功!");
}
}
/**
* 发送聊天室公告
* @param message
*/
public void sendPublicMessage(String message)
{
for(TCP t:tcpSockets)
t.sendMessage(Flag.PUBLIC_MESSAGE+MyTools.FLAGEND+message);
JOptionPane.showMessageDialog(null, "公告发布成功!","恭喜",JOptionPane.INFORMATION_MESSAGE);
}
/**
* 发送弹窗公告
* @param message
*/
public void sendShowWindow(String message)
{
for(TCP t:tcpSockets)
t.sendMessage(Flag.SHOW_WINDOW+MyTools.FLAGEND+message);
JOptionPane.showMessageDialog(null, "弹窗公告发布成功!","恭喜",JOptionPane.INFORMATION_MESSAGE);
}
}
|
/*
* Copyright (C) 2020 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.tools.idea.run.deployment;
import com.intellij.openapi.project.Project;
import java.nio.file.Path;
import java.util.Optional;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
final class BootWithSnapshotTarget extends Target {
private final @NotNull Path mySnapshotKey;
BootWithSnapshotTarget(@NotNull Key deviceKey, @NotNull Path snapshotKey) {
super(deviceKey);
mySnapshotKey = snapshotKey;
}
@NotNull Path getSnapshotKey() {
return mySnapshotKey;
}
@Override
boolean matches(@NotNull Device device) {
if (!device.getKey().equals(getDeviceKey())) {
return false;
}
return device.getSnapshots().stream()
.map(Snapshot::getDirectory)
.anyMatch(snapshotKey -> snapshotKey.equals(mySnapshotKey));
}
@Override
@NotNull String getText(@NotNull Device device) {
Optional<String> text = device.getSnapshots().stream()
.filter(snapshot -> snapshot.getDirectory().equals(mySnapshotKey))
.map(Snapshot::toString)
.findFirst();
return text.orElseThrow(AssertionError::new);
}
@Override
void boot(@NotNull VirtualDevice device, @NotNull Project project) {
device.bootWithSnapshot(project, mySnapshotKey.getFileName());
}
@Override
public int hashCode() {
return 31 * getDeviceKey().hashCode() + mySnapshotKey.hashCode();
}
@Override
public boolean equals(@Nullable Object object) {
if (!(object instanceof BootWithSnapshotTarget)) {
return false;
}
BootWithSnapshotTarget target = (BootWithSnapshotTarget)object;
return getDeviceKey().equals(target.getDeviceKey()) && mySnapshotKey.equals(target.mySnapshotKey);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.analysis.solvers;
import org.apache.commons.math3.analysis.QuinticFunction;
import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.analysis.function.Sin;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.exception.NoBracketingException;
import org.apache.commons.math3.util.FastMath;
import org.junit.Assert;
import org.junit.Test;
/**
* @version $Id: UnivariateSolverUtilsTest.java 1578428 2014-03-17 15:14:07Z luc $
*/
public class UnivariateSolverUtilsTest {
protected UnivariateFunction sin = new Sin();
@Test(expected=MathIllegalArgumentException.class)
public void testSolveNull() {
UnivariateSolverUtils.solve(null, 0.0, 4.0);
}
@Test(expected=MathIllegalArgumentException.class)
public void testSolveBadEndpoints() {
double root = UnivariateSolverUtils.solve(sin, 4.0, -0.1, 1e-6);
System.out.println("root=" + root);
}
@Test
public void testSolveBadAccuracy() {
try { // bad accuracy
UnivariateSolverUtils.solve(sin, 0.0, 4.0, 0.0);
// Assert.fail("Expecting MathIllegalArgumentException"); // TODO needs rework since convergence behaviour was changed
} catch (MathIllegalArgumentException ex) {
// expected
}
}
@Test
public void testSolveSin() {
double x = UnivariateSolverUtils.solve(sin, 1.0, 4.0);
Assert.assertEquals(FastMath.PI, x, 1.0e-4);
}
@Test(expected=MathIllegalArgumentException.class)
public void testSolveAccuracyNull() {
double accuracy = 1.0e-6;
UnivariateSolverUtils.solve(null, 0.0, 4.0, accuracy);
}
@Test
public void testSolveAccuracySin() {
double accuracy = 1.0e-6;
double x = UnivariateSolverUtils.solve(sin, 1.0,
4.0, accuracy);
Assert.assertEquals(FastMath.PI, x, accuracy);
}
@Test(expected=MathIllegalArgumentException.class)
public void testSolveNoRoot() {
UnivariateSolverUtils.solve(sin, 1.0, 1.5);
}
@Test
public void testBracketSin() {
double[] result = UnivariateSolverUtils.bracket(sin,
0.0, -2.0, 2.0);
Assert.assertTrue(sin.value(result[0]) < 0);
Assert.assertTrue(sin.value(result[1]) > 0);
}
@Test
public void testBracketCentered() {
double initial = 0.1;
double[] result = UnivariateSolverUtils.bracket(sin, initial, -2.0, 2.0, 0.2, 1.0, 100);
Assert.assertTrue(result[0] < initial);
Assert.assertTrue(result[1] > initial);
Assert.assertTrue(sin.value(result[0]) < 0);
Assert.assertTrue(sin.value(result[1]) > 0);
}
@Test
public void testBracketLow() {
double initial = 0.5;
double[] result = UnivariateSolverUtils.bracket(sin, initial, -2.0, 2.0, 0.2, 1.0, 100);
Assert.assertTrue(result[0] < initial);
Assert.assertTrue(result[1] < initial);
Assert.assertTrue(sin.value(result[0]) < 0);
Assert.assertTrue(sin.value(result[1]) > 0);
}
@Test
public void testBracketHigh(){
double initial = -0.5;
double[] result = UnivariateSolverUtils.bracket(sin, initial, -2.0, 2.0, 0.2, 1.0, 100);
Assert.assertTrue(result[0] > initial);
Assert.assertTrue(result[1] > initial);
Assert.assertTrue(sin.value(result[0]) < 0);
Assert.assertTrue(sin.value(result[1]) > 0);
}
@Test(expected=NoBracketingException.class)
public void testBracketLinear(){
UnivariateSolverUtils.bracket(new UnivariateFunction() {
public double value(double x) {
return 1 - x;
}
}, 1000, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0, 1.0, 100);
}
@Test
public void testBracketExponential(){
double[] result = UnivariateSolverUtils.bracket(new UnivariateFunction() {
public double value(double x) {
return 1 - x;
}
}, 1000, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 1.0, 2.0, 10);
Assert.assertTrue(result[0] <= 1);
Assert.assertTrue(result[1] >= 1);
}
@Test
public void testBracketEndpointRoot() {
double[] result = UnivariateSolverUtils.bracket(sin, 1.5, 0, 2.0);
Assert.assertEquals(0.0, sin.value(result[0]), 1.0e-15);
Assert.assertTrue(sin.value(result[1]) > 0);
}
@Test(expected=MathIllegalArgumentException.class)
public void testNullFunction() {
UnivariateSolverUtils.bracket(null, 1.5, 0, 2.0);
}
@Test(expected=MathIllegalArgumentException.class)
public void testBadInitial() {
UnivariateSolverUtils.bracket(sin, 2.5, 0, 2.0);
}
@Test(expected=MathIllegalArgumentException.class)
public void testBadAdditive() {
UnivariateSolverUtils.bracket(sin, 1.0, -2.0, 3.0, -1.0, 1.0, 100);
}
@Test(expected=NoBracketingException.class)
public void testIterationExceeded() {
UnivariateSolverUtils.bracket(sin, 1.0, -2.0, 3.0, 1.0e-5, 1.0, 100);
}
@Test(expected=MathIllegalArgumentException.class)
public void testBadEndpoints() {
// endpoints not valid
UnivariateSolverUtils.bracket(sin, 1.5, 2.0, 1.0);
}
@Test(expected=MathIllegalArgumentException.class)
public void testBadMaximumIterations() {
// bad maximum iterations
UnivariateSolverUtils.bracket(sin, 1.5, 0, 2.0, 0);
}
@Test
public void testMisc() {
UnivariateFunction f = new QuinticFunction();
double result;
// Static solve method
result = UnivariateSolverUtils.solve(f, -0.2, 0.2);
Assert.assertEquals(result, 0, 1E-8);
result = UnivariateSolverUtils.solve(f, -0.1, 0.3);
Assert.assertEquals(result, 0, 1E-8);
result = UnivariateSolverUtils.solve(f, -0.3, 0.45);
Assert.assertEquals(result, 0, 1E-6);
result = UnivariateSolverUtils.solve(f, 0.3, 0.7);
Assert.assertEquals(result, 0.5, 1E-6);
result = UnivariateSolverUtils.solve(f, 0.2, 0.6);
Assert.assertEquals(result, 0.5, 1E-6);
result = UnivariateSolverUtils.solve(f, 0.05, 0.95);
Assert.assertEquals(result, 0.5, 1E-6);
result = UnivariateSolverUtils.solve(f, 0.85, 1.25);
Assert.assertEquals(result, 1.0, 1E-6);
result = UnivariateSolverUtils.solve(f, 0.8, 1.2);
Assert.assertEquals(result, 1.0, 1E-6);
result = UnivariateSolverUtils.solve(f, 0.85, 1.75);
Assert.assertEquals(result, 1.0, 1E-6);
result = UnivariateSolverUtils.solve(f, 0.55, 1.45);
Assert.assertEquals(result, 1.0, 1E-6);
result = UnivariateSolverUtils.solve(f, 0.85, 5);
Assert.assertEquals(result, 1.0, 1E-6);
}
}
|
package com.hsdc.dp.web;
import java.util.Calendar;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hsdc.dp.service.singleton.IDGeneratorSingleton;
import com.hsdc.dp.web.dto.SingletonStringResponse;
@Controller
public class SingletonController {
@RequestMapping(value = "/sg", method = RequestMethod.GET)
public String index(Model model) {
return "sgindex";
}
@RequestMapping(value = "/sg/genid/{formType}", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody SingletonStringResponse genId(@PathVariable String formType) {
return new SingletonStringResponse(IDGeneratorSingleton.getInstance().getNextID(formType, Calendar.getInstance().getTime()));
}
}
|
/**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Tue Nov 10 00:33:25 GMT 2020
*/
package net.sourceforge.squirrel_sql.client.session;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.junit.AfterClass;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
import static org.evosuite.shaded.org.mockito.Mockito.*;
@EvoSuiteClassExclude
public class Session_ESTest_scaffolding {
@org.junit.Rule
public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule();
private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone();
private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000);
@BeforeClass
public static void initEvoSuiteFramework() {
org.evosuite.runtime.RuntimeSettings.className = "net.sourceforge.squirrel_sql.client.session.Session";
org.evosuite.runtime.GuiSupport.initialize();
org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100;
org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000;
org.evosuite.runtime.RuntimeSettings.mockSystemIn = true;
org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED;
org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT();
org.evosuite.runtime.classhandling.JDKClassResetter.init();
setSystemProperties();
initializeClasses();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
try { initMocksToAvoidTimeoutsInTheTests(); } catch(ClassNotFoundException e) {}
}
@AfterClass
public static void clearEvoSuiteFramework(){
Sandbox.resetDefaultSecurityManager();
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
}
@Before
public void initTestCase(){
threadStopper.storeCurrentThreads();
threadStopper.startRecordingTime();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler();
org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode();
setSystemProperties();
org.evosuite.runtime.GuiSupport.setHeadless();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
org.evosuite.runtime.agent.InstrumentingAgent.activate();
}
@After
public void doneWithTestCase(){
threadStopper.killAndJoinClientThreads();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks();
org.evosuite.runtime.classhandling.JDKClassResetter.reset();
resetClasses();
org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode();
org.evosuite.runtime.agent.InstrumentingAgent.deactivate();
org.evosuite.runtime.GuiSupport.restoreHeadlessMode();
}
public static void setSystemProperties() {
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
java.lang.System.setProperty("file.encoding", "UTF-8");
java.lang.System.setProperty("java.awt.headless", "true");
java.lang.System.setProperty("java.io.tmpdir", "/tmp");
java.lang.System.setProperty("user.dir", "/home/ubuntu/replication/scripts/projects/102_squirrel-sql");
java.lang.System.setProperty("user.home", "/home/ubuntu");
java.lang.System.setProperty("user.language", "en");
java.lang.System.setProperty("user.name", "ubuntu");
java.lang.System.setProperty("user.timezone", "Etc/UTC");
java.lang.System.setProperty("log4j.configuration", "SUT.log4j.properties");
}
private static void initializeClasses() {
org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(Session_ESTest_scaffolding.class.getClassLoader() ,
"org.apache.commons.lang.StringUtils",
"org.fest.swing.edt.GuiQuery",
"org.apache.log4j.helpers.PatternConverter",
"net.sourceforge.squirrel_sql.client.gui.db.IBaseList",
"net.sourceforge.squirrel_sql.fw.util.FileExtensionFilter",
"org.hibernate.engine.EntityKey",
"net.sourceforge.squirrel_sql.client.gui.session.ObjectTreeInternalFrame",
"org.apache.log4j.AppenderSkeleton",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ISQLExecutionHandlerListener",
"org.jfree.data.time.Minute",
"org.apache.commons.httpclient.Header",
"org.hibernate.Transaction",
"net.sourceforge.squirrel_sql.client.gui.db.DataCache",
"org.hibernate.dialect.function.StandardSQLFunction",
"net.sourceforge.squirrel_sql.client.session.event.ISQLResultExecuterTabListener",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAliasConnectionProperties",
"net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.tabs.IObjectTab",
"org.hibernate.sql.CaseFragment",
"net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.FindInObjectTreeController",
"net.sourceforge.squirrel_sql.fw.dialects.MySQLDialectExt$MySQLDialectHelper",
"org.jfree.data.general.AbstractSeriesDataset",
"net.sourceforge.squirrel_sql.client.session.event.SimpleSessionListener",
"org.jfree.data.general.CombinedDataset",
"org.apache.commons.cli.UnrecognizedOptionException",
"net.sourceforge.squirrel_sql.fw.dialects.GenericDialectExt",
"org.hibernate.ScrollableResults",
"org.dom4j.Namespace",
"net.sourceforge.squirrel_sql.fw.sql.SQLDatabaseMetaData",
"org.hibernate.type.DoubleType",
"org.apache.log4j.spi.Filter",
"net.sourceforge.squirrel_sql.fw.sql.IUDTInfo",
"org.hibernate.CacheMode",
"net.sourceforge.squirrel_sql.fw.dialects.HADBDialectExt$HADBDialectHelper",
"org.hibernate.type.ForeignKeyDirection$2",
"net.sourceforge.squirrel_sql.client.action.ActionKeys",
"net.sourceforge.squirrel_sql.client.session.ISQLEntryPanelFactory",
"org.hibernate.dialect.function.NoArgSQLFunction",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAlias$IStrings",
"org.hibernate.dialect.Dialect",
"org.hibernate.type.ForeignKeyDirection$1",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ObjectTreeTab",
"org.hibernate.ScrollMode",
"org.hibernate.FetchMode",
"org.hibernate.cache.QueryCache",
"net.sourceforge.squirrel_sql.fw.dialects.ProgressDialectExt$ProgressDialectHelper",
"net.sourceforge.squirrel_sql.client.gui.db.SchemaLoadInfo",
"net.sourceforge.squirrel_sql.fw.dialects.TimesTenDialectExt$TimesTenDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.AxionDialectExt",
"org.hibernate.type.CurrencyType",
"net.sourceforge.squirrel_sql.fw.dialects.SybaseDialectExt$SybaseDialectHelper",
"org.hibernate.persister.collection.CollectionPersister",
"net.sourceforge.squirrel_sql.fw.gui.BasePopupMenu",
"net.sourceforge.squirrel_sql.fw.dialects.FrontBaseDialectExt$FrontBaseDialectHelper",
"net.sourceforge.squirrel_sql.client.gui.db.DriversListInternalFrame",
"org.hibernate.AssertionFailure",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ErrorPanel$TabButton",
"net.sourceforge.squirrel_sql.client.preferences.IGlobalPreferencesPanel",
"org.hibernate.StatelessSession",
"net.sourceforge.squirrel_sql.fw.dialects.MAXDBDialectExt$MAXDBDialectHelper",
"net.sourceforge.squirrel_sql.client.gui.mainframe.MainFrameWindowState",
"org.apache.log4j.Hierarchy",
"net.sourceforge.squirrel_sql.client.FontInfoStore",
"net.sourceforge.squirrel_sql.fw.util.IObjectCacheChangeListener",
"net.sourceforge.squirrel_sql.fw.util.log.ILogger",
"org.apache.commons.httpclient.HostConfiguration",
"net.sourceforge.squirrel_sql.fw.gui.MemoryComboBox",
"net.sourceforge.squirrel_sql.client.plugin.IPlugin",
"net.sourceforge.squirrel_sql.fw.util.log.LoggerController",
"org.hibernate.dialect.InformixDialect$1",
"net.sourceforge.squirrel_sql.fw.datasetviewer.IDataModelImplementationDetails",
"net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.INodeExpander",
"org.apache.log4j.spi.OptionHandler",
"org.hibernate.engine.ValueInclusion",
"org.hibernate.dialect.function.ConditionalParenthesisFunction",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ResultTabFactory",
"org.hibernate.engine.CascadeStyle$12",
"org.hibernate.engine.CascadeStyle$11",
"org.hibernate.engine.CascadeStyle$10",
"org.hibernate.type.BlobType",
"org.hibernate.dialect.function.NvlFunction",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLHistoryComboBox",
"net.sourceforge.squirrel_sql.fw.util.Utilities$1",
"net.sourceforge.squirrel_sql.fw.id.IHasIdentifier",
"org.hibernate.type.CharacterArrayType",
"org.apache.log4j.helpers.OptionConverter",
"org.apache.log4j.helpers.FormattingInfo",
"net.sourceforge.squirrel_sql.fw.util.ITaskThreadPoolCallback",
"org.hibernate.dialect.SAPDBDialect",
"org.apache.commons.httpclient.auth.AuthState",
"net.sourceforge.squirrel_sql.fw.sql.TokenizerSessPropsInteractions",
"net.sourceforge.squirrel_sql.client.gui.session.RowColumnLabel",
"net.sourceforge.squirrel_sql.fw.dialects.UserCancelledOperationException",
"org.hibernate.exception.Nestable",
"net.sourceforge.squirrel_sql.fw.sql.DatabaseObjectInfo",
"net.sourceforge.squirrel_sql.fw.util.log.ILoggerFactory",
"net.sourceforge.squirrel_sql.fw.dialects.InformixDialectExt$InformixDialectHelper",
"net.sourceforge.squirrel_sql.fw.datasetviewer.DataSetUpdateableTableModelListener",
"org.hibernate.dialect.HSQLDialect$1",
"org.hibernate.type.AnyType",
"net.sourceforge.squirrel_sql.client.session.schemainfo.SchemaInfoUpdateListener",
"net.sourceforge.squirrel_sql.fw.id.IntegerIdentifierFactory",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.ITabDelegate",
"net.sourceforge.squirrel_sql.fw.datasetviewer.IDataSetUpdateableTableModel",
"net.sourceforge.squirrel_sql.fw.resources.LibraryResources",
"net.sourceforge.squirrel_sql.fw.gui.DialogUtils",
"net.sourceforge.squirrel_sql.fw.util.NullMessageHandler",
"net.sourceforge.squirrel_sql.client.session.mainpanel.IMainPanelTab",
"net.sourceforge.squirrel_sql.fw.datasetviewer.IDataSet",
"org.hibernate.dialect.function.PositionSubstringFunction",
"org.jfree.data.general.DatasetChangeListener",
"org.hibernate.type.IntegerType",
"net.sourceforge.squirrel_sql.client.gui.db.IDriversList",
"org.apache.log4j.helpers.PatternParser",
"org.hibernate.stat.Statistics",
"net.sourceforge.squirrel_sql.fw.sql.SQLDriverClassLoader",
"net.sourceforge.squirrel_sql.client.gui.session.SessionPanel$MyToolBar",
"org.hibernate.proxy.EntityNotFoundDelegate",
"org.apache.log4j.Category",
"net.sourceforge.squirrel_sql.fw.datasetviewer.ResultSetDataSet",
"net.sourceforge.squirrel_sql.fw.gui.TextPopupMenu",
"net.sourceforge.squirrel_sql.fw.sql.PrimaryKeyInfo",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.WidgetEvent",
"org.hibernate.StaleObjectStateException",
"net.sourceforge.squirrel_sql.fw.dialects.FirebirdDialectExt",
"net.sourceforge.squirrel_sql.fw.util.TaskThreadPool",
"org.hibernate.dialect.Oracle9Dialect",
"net.sourceforge.squirrel_sql.client.session.mainpanel.CancelPanel",
"net.sourceforge.squirrel_sql.client.plugin.PluginException",
"net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.ObjectTreePanel$LeftPanel",
"org.apache.commons.httpclient.params.HttpClientParams",
"net.sourceforge.squirrel_sql.fw.sql.TableColumnInfo",
"org.hibernate.persister.entity.Lockable",
"org.hibernate.TransientObjectException",
"org.fest.swing.edt.GuiTask",
"org.apache.log4j.ConsoleAppender",
"org.jfree.data.general.SeriesChangeEvent",
"net.sourceforge.squirrel_sql.fw.gui.ToolBar",
"net.sourceforge.squirrel_sql.client.gui.session.SessionPanel",
"org.hibernate.type.ByteType",
"net.sourceforge.squirrel_sql.client.session.MessagePanel",
"net.sourceforge.squirrel_sql.client.DummyAppPlugin",
"net.sourceforge.squirrel_sql.fw.dialects.ProgressDialectExt",
"net.sourceforge.squirrel_sql.client.session.event.SQLPanelEvent",
"org.hibernate.property.BasicPropertyAccessor",
"net.sourceforge.squirrel_sql.fw.dialects.NetezzaDialextExt$NetezzaDialectHelper",
"org.apache.log4j.helpers.PatternParser$NamedPatternConverter",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.SessionDialogWidget",
"net.sourceforge.squirrel_sql.fw.sql.SQLDriverProperty",
"org.apache.commons.cli.CommandLine",
"org.hibernate.dialect.PointbaseDialect",
"org.hibernate.dialect.lock.LockingStrategy",
"org.hibernate.dialect.TimesTenDialect",
"net.sourceforge.squirrel_sql.client.session.ExtendedColumnInfo",
"net.sourceforge.squirrel_sql.client.session.Session$SQLConnectionListener",
"net.sourceforge.squirrel_sql.client.session.parser.kernel.TableAliasInfo",
"org.dom4j.Branch",
"net.sourceforge.squirrel_sql.fw.util.Utilities",
"org.apache.log4j.spi.AppenderAttachable",
"net.sourceforge.squirrel_sql.client.IApplication",
"org.hibernate.type.ShortType",
"org.apache.log4j.helpers.PatternParser$DatePatternConverter",
"net.sourceforge.squirrel_sql.client.session.DefaultSQLEntryPanel$MyTextArea",
"org.hibernate.dialect.function.VarArgsSQLFunction",
"org.hibernate.engine.Mapping",
"org.dom4j.XPath",
"org.hibernate.type.VersionType",
"org.hibernate.event.EventListeners",
"org.hibernate.util.ReflectHelper",
"org.jfree.date.SerialDate",
"net.sourceforge.squirrel_sql.fw.xml.XMLException",
"org.hibernate.type.BinaryType",
"net.sourceforge.squirrel_sql.client.session.SessionManager",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel",
"org.hibernate.type.AbstractBynaryType",
"org.hibernate.dialect.function.CharIndexFunction",
"net.sourceforge.squirrel_sql.fw.sql.DatabaseObjectType",
"org.apache.commons.httpclient.params.HttpMethodParams",
"net.sourceforge.squirrel_sql.client.util.ApplicationFileWrappersImpl",
"org.jfree.data.DomainOrder",
"org.dom4j.InvalidXPathException",
"net.sourceforge.squirrel_sql.fw.util.FileWrapperImpl",
"net.sourceforge.squirrel_sql.client.gui.db.AliasesListInternalFrame",
"net.sourceforge.squirrel_sql.client.gui.db.ISQLAliasExt",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.WidgetListener",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLHistoryItem",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.docktabdesktop.DockTabDesktopPane",
"net.sourceforge.squirrel_sql.client.session.ISQLEntryPanel",
"net.sourceforge.squirrel_sql.fw.dialects.MySQL5DialectExt",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLHistory",
"org.hibernate.cache.entry.CacheEntryStructure",
"org.hibernate.exception.SQLExceptionConverter",
"org.apache.commons.httpclient.HttpState",
"net.sourceforge.squirrel_sql.fw.dialects.NetezzaDialextExt",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.TabWidget",
"org.hibernate.PropertyAccessException",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.DockWidget",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.IDialogDelegate",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.docktabdesktop.SmallTabButton$1",
"com.gargoylesoftware.base.resource.jdbc.DatabaseMetaDataWrapper",
"net.sourceforge.squirrel_sql.client.session.properties.EditWhereColsSheet",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel$CopyLastButton",
"net.sourceforge.squirrel_sql.client.plugin.DefaultPlugin",
"org.jfree.data.time.Day",
"net.sourceforge.squirrel_sql.fw.gui.TimePanel",
"org.jfree.data.general.SeriesDataset",
"org.jfree.data.xy.XYDataset",
"org.hibernate.cache.Cache",
"org.apache.log4j.WriterAppender",
"org.hibernate.dialect.FirebirdDialect",
"org.fest.swing.exception.ActionFailedException",
"org.dom4j.Attribute",
"org.apache.commons.cli.Util",
"net.sourceforge.squirrel_sql.fw.sql.ITokenizerFactory",
"org.apache.commons.httpclient.params.HttpParams",
"org.dom4j.Document",
"net.sourceforge.squirrel_sql.fw.dialects.GenericDialectExt$GenericDialectHelper",
"org.hibernate.Criteria",
"org.hibernate.dialect.Dialect$3",
"net.sourceforge.squirrel_sql.fw.dialects.CreateScriptPreferences",
"org.hibernate.dialect.Dialect$2",
"org.hibernate.dialect.Dialect$1",
"net.sourceforge.squirrel_sql.client.session.IObjectTreeAPI",
"net.sourceforge.squirrel_sql.client.gui.db.aliasproperties.IAliasPropertiesPanelController",
"net.sourceforge.squirrel_sql.client.gui.mainframe.SquirrelDesktopManager",
"net.sourceforge.squirrel_sql.client.session.sqlfilter.SQLFilterSheet",
"org.hibernate.dialect.Dialect$4",
"net.sourceforge.squirrel_sql.fw.util.BaseException",
"org.apache.log4j.helpers.Loader",
"org.jfree.data.time.RegularTimePeriod",
"org.jfree.date.SpreadsheetDate",
"org.hibernate.sql.DecodeCaseFragment",
"net.sourceforge.squirrel_sql.fw.dialects.DaffodilDialectExt",
"org.apache.log4j.helpers.FileWatchdog",
"org.fest.util.CollectionFilter",
"org.hibernate.dialect.function.SQLFunctionRegistry",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.IWidget",
"net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.ObjectTree",
"net.sourceforge.squirrel_sql.client.session.schemainfo.CaseInsensitiveString",
"org.dom4j.CDATA",
"net.sourceforge.squirrel_sql.fw.dialects.IngresDialectExt$IngresDialectHelper",
"net.sourceforge.squirrel_sql.fw.sql.ISQLDriver",
"org.jfree.data.general.CombinationDataset",
"net.sourceforge.squirrel_sql.fw.dialects.McKoiDialectExt",
"net.sourceforge.squirrel_sql.client.session.FileManager",
"net.sourceforge.squirrel_sql.fw.datasetviewer.ResultSetMetaDataDataSet",
"net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.ObjectTreeTabbedPane",
"org.jfree.data.xy.IntervalXYDataset",
"org.fest.util.Throwables",
"net.sourceforge.squirrel_sql.fw.sql.SQLDriver$IStrings",
"net.sourceforge.squirrel_sql.fw.util.DefaultExceptionFormatter",
"org.apache.commons.cli.MissingOptionException",
"org.hibernate.type.PrimitiveType",
"org.apache.commons.httpclient.HttpMethod",
"org.hibernate.cache.OptimisticCacheSource",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.docktabdesktop.DockTabDesktopPaneHolder",
"org.apache.commons.cli.AlreadySelectedException",
"org.hibernate.engine.NamedSQLQueryDefinition",
"net.sourceforge.squirrel_sql.client.action.ActionCollection",
"org.hibernate.type.TimeType",
"net.sourceforge.squirrel_sql.client.session.SQLExecutionInfo",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ResultTab$QueryInfoPanel",
"net.sourceforge.squirrel_sql.fw.sql.IQueryTokenizer",
"org.fest.swing.exception.UnexpectedException",
"net.sourceforge.squirrel_sql.fw.dialects.DaffodilDialectExt$DaffodilDialectHelper",
"net.sourceforge.squirrel_sql.fw.sql.SQLDriverManager",
"net.sourceforge.squirrel_sql.client.plugin.PluginStatus",
"org.hibernate.ConnectionReleaseMode",
"net.sourceforge.squirrel_sql.fw.sql.ISQLConnection",
"org.hibernate.type.ForeignKeyDirection",
"org.hibernate.persister.entity.Joinable",
"org.hibernate.type.BigDecimalType",
"org.hibernate.type.WrapperBinaryType",
"org.fest.swing.applet.BasicAppletContext$EmptyAppletEnumeration",
"org.hibernate.sql.ANSICaseFragment",
"org.hibernate.type.AbstractComponentType",
"net.sourceforge.squirrel_sql.fw.datasetviewer.IDataSetUpdateableModel",
"org.hibernate.loader.custom.CustomQuery",
"net.sourceforge.squirrel_sql.fw.gui.action.wikiTable.IWikiTableConfigurationFactory",
"net.sourceforge.squirrel_sql.fw.gui.IToggleAction",
"net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.ObjectTreePanel",
"net.sourceforge.squirrel_sql.fw.sql.ISQLDatabaseMetaData",
"org.hibernate.type.SerializationException",
"net.sourceforge.squirrel_sql.client.gui.mainframe.MainFrame$3",
"net.sourceforge.squirrel_sql.client.gui.session.CatalogsPanel",
"org.hibernate.type.BooleanType",
"net.sourceforge.squirrel_sql.fw.util.DuplicateObjectException",
"com.gargoylesoftware.base.resource.jdbc.ConnectionWrapper",
"net.sourceforge.squirrel_sql.fw.gui.FontInfo",
"net.sourceforge.squirrel_sql.fw.sql.ISQLAlias",
"net.sourceforge.squirrel_sql.fw.dialects.DialectType",
"org.apache.commons.cli.ParseException",
"net.sourceforge.squirrel_sql.client.session.parser.IParserEventsProcessor",
"net.sourceforge.squirrel_sql.fw.dialects.InterbaseDialectExt",
"org.apache.commons.httpclient.URI",
"net.sourceforge.squirrel_sql.client.gui.mainframe.MainFrameStatusBar",
"org.hibernate.type.FloatType",
"org.hibernate.type.CharacterType",
"net.sourceforge.squirrel_sql.fw.util.IOUtilities",
"org.jfree.date.MonthConstants",
"net.sourceforge.squirrel_sql.client.preferences.IUpdateSettings",
"net.sourceforge.squirrel_sql.fw.util.IMessageHandler",
"net.sourceforge.squirrel_sql.fw.dialects.SQLServerDialectExt",
"org.apache.log4j.PropertyConfigurator",
"net.sourceforge.squirrel_sql.client.session.event.SessionAdapter",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.IDelegateBase",
"net.sourceforge.squirrel_sql.fw.util.IOUtilitiesImpl",
"net.sourceforge.squirrel_sql.fw.dialects.DerbyDialectExt$DerbyDialectHelper",
"net.sourceforge.squirrel_sql.fw.util.MyURLClassLoader",
"org.apache.commons.cli.GnuParser",
"org.jfree.data.time.Hour",
"net.sourceforge.squirrel_sql.client.plugin.SessionPluginInfo",
"com.gargoylesoftware.base.resource.jdbc.PreparedStatementWrapper",
"org.hibernate.classic.Session",
"net.sourceforge.squirrel_sql.fw.util.Resources",
"org.hibernate.type.DiscriminatorType",
"org.apache.commons.cli.OptionValidator",
"org.dom4j.Comment",
"org.hibernate.jdbc.JDBCContext",
"org.hibernate.type.LongType",
"net.sourceforge.squirrel_sql.client.ApplicationArguments",
"org.hibernate.LockMode",
"net.sourceforge.squirrel_sql.client.gui.db.IAliasesList",
"org.hibernate.EntityMode",
"org.hibernate.dialect.HSQLDialect",
"net.sourceforge.squirrel_sql.fw.sql.SQLConnection",
"net.sourceforge.squirrel_sql.fw.util.IProxySettings",
"org.dom4j.Text",
"net.sourceforge.squirrel_sql.fw.sql.QueryTokenizer",
"net.sourceforge.squirrel_sql.fw.gui.IDialogUtils",
"net.sourceforge.squirrel_sql.fw.sql.SQLConnectionState",
"net.sourceforge.squirrel_sql.client.session.ISQLInternalFrame",
"org.hibernate.type.TimestampType",
"org.hibernate.impl.CriteriaImpl",
"net.sourceforge.squirrel_sql.fw.util.log.Log4jLoggerFactory",
"net.sourceforge.squirrel_sql.fw.util.IResources",
"net.sourceforge.squirrel_sql.fw.sql.ITableInfo",
"net.sourceforge.squirrel_sql.fw.gui.IntegerField$IntegerDocument",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SqlPanelListener",
"org.apache.log4j.PatternLayout",
"org.apache.log4j.spi.LoggerRepository",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLResultExecuterPanelFacade",
"net.sourceforge.squirrel_sql.fw.datasetviewer.IDataSetViewer",
"org.jfree.data.general.CombinedDataset$DatasetInfo",
"org.hibernate.type.Type",
"org.hibernate.Hibernate",
"org.hibernate.exception.NestableRuntimeException",
"net.sourceforge.squirrel_sql.fw.dialects.FrontBaseDialectExt",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.DesktopStyle",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLResultExecuterPanel$1",
"org.hibernate.sql.JoinFragment",
"net.sourceforge.squirrel_sql.fw.dialects.OracleDialectExt$OracleDialectHelper",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.WidgetAdapter",
"org.hibernate.type.NullableType",
"org.hibernate.metadata.ClassMetadata",
"org.dom4j.Entity",
"org.hibernate.sql.CacheJoinFragment",
"net.sourceforge.squirrel_sql.fw.sql.SQLConnection$1",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.TitleFilePathHandlerListener",
"org.apache.log4j.Level",
"org.apache.log4j.helpers.DateTimeDateFormat",
"net.sourceforge.squirrel_sql.fw.dialects.HSQLDialectExt",
"net.sourceforge.squirrel_sql.fw.datasetviewer.TableState",
"org.apache.log4j.helpers.QuietWriter",
"net.sourceforge.squirrel_sql.client.gui.session.IMainPanelFactory",
"org.dom4j.ProcessingInstruction",
"org.apache.log4j.ConsoleAppender$SystemOutStream",
"org.hibernate.id.IdentifierGenerator",
"org.jfree.data.xy.AbstractIntervalXYDataset",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel$LimitRowsCheckBoxListener",
"net.sourceforge.squirrel_sql.client.MultipleWindowsHandler",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAliasSchemaDetailProperties",
"org.hibernate.SessionFactory",
"org.hibernate.property.DirectPropertyAccessor",
"org.apache.log4j.helpers.ISO8601DateFormat",
"net.sourceforge.squirrel_sql.fw.dialects.IntersystemsCacheDialectExt",
"org.hibernate.type.BigIntegerType",
"net.sourceforge.squirrel_sql.client.session.DefaultSQLEntryPanel",
"org.jfree.data.xy.AbstractXYDataset",
"net.sourceforge.squirrel_sql.client.gui.session.MainPanel",
"net.sourceforge.squirrel_sql.fw.dialects.SequencePropertyMutability",
"net.sourceforge.squirrel_sql.fw.dialects.HADBDialectExt",
"net.sourceforge.squirrel_sql.client.plugin.IPluginManager",
"net.sourceforge.squirrel_sql.fw.dialects.OracleDialectExt",
"org.hibernate.dialect.SybaseDialect",
"org.apache.log4j.helpers.PatternParser$BasicPatternConverter",
"net.sourceforge.squirrel_sql.client.util.ApplicationFiles$1OldFileNameFilter",
"net.sourceforge.squirrel_sql.client.session.properties.SessionPropertiesSheet",
"org.hibernate.dialect.Oracle9Dialect$1",
"net.sourceforge.squirrel_sql.client.session.schemainfo.SchemaInfo$1",
"org.apache.log4j.Layout",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel$MyPropertiesListener",
"org.fest.swing.applet.AppletViewer$1",
"net.sourceforge.squirrel_sql.client.session.JdbcConnectionData",
"net.sourceforge.squirrel_sql.client.gui.db.BaseListInternalFrame",
"com.gargoylesoftware.base.resource.ManagedResource",
"net.sourceforge.squirrel_sql.fw.dialects.DB2DialectExt$DB2DialectHelper",
"net.sourceforge.squirrel_sql.fw.sql.SQLDriverPropertyCollection",
"org.jfree.data.xy.DefaultIntervalXYDataset",
"net.sourceforge.squirrel_sql.client.session.mainpanel.IUndoHandler",
"net.sourceforge.squirrel_sql.client.session.parser.kernel.ErrorInfo",
"net.sourceforge.squirrel_sql.fw.util.FileWrapperFactoryImpl",
"com.gargoylesoftware.base.resource.jdbc.CallableStatementWrapper",
"net.sourceforge.squirrel_sql.client.gui.mainframe.MainFrameMenuBar",
"org.hibernate.dialect.DB2Dialect",
"net.sourceforge.squirrel_sql.fw.id.UidIdentifier",
"org.hibernate.Session",
"org.hibernate.engine.query.QueryPlanCache",
"org.apache.commons.httpclient.HttpConnectionManager",
"org.hibernate.cache.UpdateTimestampsCache",
"org.apache.log4j.helpers.PatternParser$CategoryPatternConverter",
"net.sourceforge.squirrel_sql.fw.dialects.InterbaseDialectExt$InterbaseDialectHelper",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ResultFrame",
"org.apache.commons.cli.Option",
"org.fest.swing.applet.AppletViewer",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.DialogWidget",
"net.sourceforge.squirrel_sql.fw.gui.IntegerField",
"org.apache.log4j.spi.DefaultRepositorySelector",
"org.hibernate.type.LocaleType",
"org.dom4j.NodeFilter",
"net.sourceforge.squirrel_sql.fw.datasetviewer.DataSetDefinition",
"net.sourceforge.squirrel_sql.fw.util.FileWrapperFactory",
"org.hibernate.dialect.function.AnsiTrimEmulationFunction",
"net.sourceforge.squirrel_sql.client.session.schemainfo.SchemaInfoCache",
"net.sourceforge.squirrel_sql.fw.util.log.Log4jLoggerFactory$1",
"net.sourceforge.squirrel_sql.fw.util.PropertyChangeReporter",
"net.sourceforge.squirrel_sql.fw.sql.IDatabaseObjectInfo",
"net.sourceforge.squirrel_sql.fw.dialects.AxionDialectExt$AxionDialectHelper",
"com.gargoylesoftware.base.resource.jdbc.AlreadyClosedException",
"org.dom4j.QName",
"net.sourceforge.squirrel_sql.client.session.parser.ParserEventsListener",
"org.hibernate.type.AssociationType",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAliasSchemaProperties",
"org.apache.commons.cli.MissingArgumentException",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.SessionTabWidget",
"net.sourceforge.squirrel_sql.fw.util.ExceptionFormatter",
"org.hibernate.persister.entity.EntityPersister",
"org.hibernate.engine.CascadingAction",
"net.sourceforge.squirrel_sql.client.session.schemainfo.FilterMatcher",
"org.dom4j.Node",
"net.sourceforge.squirrel_sql.fw.id.IntegerIdentifier",
"net.sourceforge.squirrel_sql.fw.dialects.HibernateDialect",
"org.apache.log4j.or.ObjectRenderer",
"net.sourceforge.squirrel_sql.fw.dialects.IntersystemsCacheDialectExt$CacheHelper",
"net.sourceforge.squirrel_sql.client.preferences.SquirrelPreferences",
"net.sourceforge.squirrel_sql.fw.util.beanwrapper.StringWrapper",
"net.sourceforge.squirrel_sql.fw.dialects.SQLServerDialectExt$SQLServerDialectHelper",
"net.sourceforge.squirrel_sql.client.resources.SquirrelResources",
"org.hibernate.dialect.function.SQLFunction",
"net.sourceforge.squirrel_sql.fw.dialects.GreenplumDialectExt$GreenplumDialectHelper",
"net.sourceforge.squirrel_sql.client.session.IObjectTreeInternalFrame",
"org.hibernate.dialect.function.ConvertFunction",
"org.apache.log4j.helpers.PatternParser$ClassNamePatternConverter",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.ISessionWidget",
"net.sourceforge.squirrel_sql.fw.gui.StatusBar",
"org.hibernate.dialect.PostgreSQLDialect",
"org.hibernate.dialect.MySQLDialect",
"org.hibernate.engine.SessionImplementor",
"net.sourceforge.squirrel_sql.fw.dialects.InformixDialectExt",
"net.sourceforge.squirrel_sql.client.gui.mainframe.SplitPnResizeHandler",
"org.hibernate.type.IdentifierType",
"net.sourceforge.squirrel_sql.fw.datasetviewer.ColumnDisplayDefinition",
"org.fest.swing.edt.GuiAction",
"net.sourceforge.squirrel_sql.client.Version",
"org.jfree.data.general.DatasetGroup",
"net.sourceforge.squirrel_sql.client.session.event.ISessionListener",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ISQLResultExecuter",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.IDesktopContainer",
"org.hibernate.type.YesNoType",
"net.sourceforge.squirrel_sql.fw.dialects.SybaseDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.PointbaseDialectExt",
"org.jfree.data.xy.OHLCDataset",
"org.hibernate.collection.PersistentCollection",
"net.sourceforge.squirrel_sql.client.session.properties.SessionProperties",
"net.sourceforge.squirrel_sql.fw.dialects.PostgreSQLDialectExt",
"org.apache.commons.httpclient.params.DefaultHttpParams",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLResultExecuterPanel",
"org.apache.commons.httpclient.HttpClient",
"org.apache.log4j.spi.LoggerFactory",
"org.apache.log4j.spi.Configurator",
"net.sourceforge.squirrel_sql.fw.util.ListMessageHandler",
"net.sourceforge.squirrel_sql.client.session.mainpanel.CancelPanelCtrl",
"org.hibernate.type.ImmutableType",
"net.sourceforge.squirrel_sql.client.IApplicationArguments",
"net.sourceforge.squirrel_sql.fw.sql.IProcedureInfo",
"net.sourceforge.squirrel_sql.client.session.schemainfo.SchemaInfo",
"org.hibernate.dialect.function.CastFunction",
"org.apache.log4j.spi.LocationInfo",
"net.sourceforge.squirrel_sql.fw.util.FileWrapper",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.docktabdesktop.SmallTabButton",
"org.apache.log4j.PropertyWatchdog",
"net.sourceforge.squirrel_sql.client.session.IAllowedSchemaChecker",
"org.hibernate.dialect.InformixDialect",
"org.apache.commons.cli.Options",
"org.hibernate.dialect.PostgreSQLDialect$1",
"org.jfree.data.general.Dataset",
"net.sourceforge.squirrel_sql.client.preferences.PreferenceType",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ErrorPanelListener",
"org.hibernate.type.CharBooleanType",
"net.sourceforge.squirrel_sql.client.gui.session.SQLInternalFrame",
"org.hibernate.jdbc.ConnectionManager$Callback",
"net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommandListener",
"org.apache.commons.cli.OptionBuilder",
"net.sourceforge.squirrel_sql.client.session.SQLTokenListener",
"org.apache.commons.httpclient.HttpException",
"net.sourceforge.squirrel_sql.client.gui.WindowManager",
"net.sourceforge.squirrel_sql.fw.datasetviewer.IMainFrame",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAlias",
"org.apache.commons.cli.CommandLineParser",
"org.fest.util.StackTraces",
"org.hibernate.dialect.function.StandardJDBCEscapeFunction",
"net.sourceforge.squirrel_sql.client.session.event.SQLResultExecuterTabEvent",
"org.hibernate.tuple.entity.EntityMetamodel",
"org.apache.log4j.helpers.PatternParser$MDCPatternConverter",
"org.hibernate.property.BasicPropertyAccessor$BasicSetter",
"net.sourceforge.squirrel_sql.fw.gui.ChooserPreviewer",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel$SqlComboListener",
"org.apache.log4j.Priority",
"org.hibernate.type.CalendarType",
"org.hibernate.exception.TemplatedViolatedConstraintNameExtracter",
"org.hibernate.property.BasicPropertyAccessor$BasicGetter",
"org.dom4j.Element",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.IDockDelegate",
"org.apache.log4j.LogManager",
"net.sourceforge.squirrel_sql.client.session.Session",
"org.hibernate.dialect.FrontBaseDialect",
"net.sourceforge.squirrel_sql.fw.dialects.GreenplumDialectExt",
"net.sourceforge.squirrel_sql.client.plugin.PluginInfo",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ErrorPanel",
"net.sourceforge.squirrel_sql.client.gui.db.SchemaNameLoadInfo",
"org.jfree.util.PublicCloneable",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel$SQLExecutorHistoryListener",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ResultTab$TabButton",
"net.sourceforge.squirrel_sql.fw.sql.ForeignKeyInfo",
"net.sourceforge.squirrel_sql.fw.dialects.DialectFactory",
"org.apache.log4j.DefaultCategoryFactory",
"org.apache.commons.httpclient.URIException",
"org.apache.log4j.or.RendererMap",
"net.sourceforge.squirrel_sql.client.gui.session.ObjectTreeInternalFrame$ObjectTreeToolBar",
"net.sourceforge.squirrel_sql.fw.persist.IValidatable",
"net.sourceforge.squirrel_sql.fw.dialects.SqlGenerationPreferences",
"net.sourceforge.squirrel_sql.client.session.MessagePanel$MessagePanelPopupMenu",
"org.hibernate.engine.NamedQueryDefinition",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLHistoryComboBoxModel",
"org.apache.log4j.ConsoleAppender$SystemErrStream",
"org.hibernate.type.TimeZoneType",
"org.fest.swing.applet.BasicAppletContext",
"org.jfree.data.general.AbstractDataset",
"net.sourceforge.squirrel_sql.client.util.IOptionPanel",
"org.hibernate.Query",
"net.sourceforge.squirrel_sql.fw.id.IIdentifier",
"net.sourceforge.squirrel_sql.client.session.event.ISQLExecutionListener",
"net.sourceforge.squirrel_sql.client.gui.LogPanel",
"org.hibernate.StaleStateException",
"org.hibernate.dialect.TypeNames",
"org.hibernate.dialect.Cache71Dialect$1",
"net.sourceforge.squirrel_sql.client.session.SQLPanelAPI",
"org.apache.commons.cli.Parser",
"org.hibernate.jdbc.Batcher",
"org.hibernate.type.ClobType",
"net.sourceforge.squirrel_sql.fw.sql.QueryTokenizer$1",
"org.apache.log4j.helpers.PatternParser$LocationPatternConverter",
"org.apache.log4j.CategoryKey",
"net.sourceforge.squirrel_sql.client.gui.MemoryPanel",
"net.sourceforge.squirrel_sql.fw.gui.action.wikiTable.IWikiTableConfiguration",
"net.sourceforge.squirrel_sql.client.session.event.ISQLPanelListener",
"net.sourceforge.squirrel_sql.fw.dialects.MySQLDialectExt",
"org.hibernate.HibernateException",
"org.hibernate.QueryException",
"org.jfree.data.time.TimePeriod",
"org.apache.log4j.helpers.OnlyOnceErrorHandler",
"org.hibernate.exception.ViolatedConstraintNameExtracter",
"org.hibernate.util.Cloneable",
"org.hibernate.dialect.IngresDialect",
"net.jcip.annotations.ThreadSafe",
"net.sourceforge.squirrel_sql.fw.sql.DataTypeInfo",
"net.sourceforge.squirrel_sql.client.session.schemainfo.ObjFilterMatcher",
"org.apache.log4j.ProvisionNode",
"net.sourceforge.squirrel_sql.fw.util.StringManager",
"com.gargoylesoftware.base.resource.jdbc.StatementWrapper",
"org.hibernate.PropertyNotFoundException",
"net.sourceforge.squirrel_sql.client.session.mainpanel.IResultTab",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ResultTab",
"net.sourceforge.squirrel_sql.fw.util.ProxySettings",
"org.apache.commons.httpclient.NameValuePair",
"net.sourceforge.squirrel_sql.client.session.Session$1",
"net.sourceforge.squirrel_sql.fw.dialects.FirebirdDialectExt$FirebirdDialectHelper",
"net.sourceforge.squirrel_sql.fw.gui.WindowState",
"org.dom4j.tree.AbstractNode",
"org.dom4j.Visitor",
"net.sourceforge.squirrel_sql.fw.util.log.ILoggerListener",
"net.sourceforge.squirrel_sql.client.gui.session.SessionInternalFrame",
"net.sourceforge.squirrel_sql.client.session.Session$2",
"net.sourceforge.squirrel_sql.fw.dialects.StringTemplateConstants",
"org.dom4j.CharacterData",
"net.sourceforge.squirrel_sql.client.session.Session$3",
"org.apache.log4j.helpers.PatternParser$LiteralPatternConverter",
"org.hibernate.engine.SessionFactoryImplementor",
"org.apache.log4j.spi.RootLogger",
"net.sourceforge.squirrel_sql.client.gui.db.SchemaTableTypeCombination",
"net.sourceforge.squirrel_sql.fw.preferences.BaseQueryTokenizerPreferenceBean",
"org.hibernate.engine.PersistenceContext",
"org.apache.log4j.spi.ErrorHandler",
"net.sourceforge.squirrel_sql.fw.id.IIdentifierFactory",
"net.sourceforge.squirrel_sql.fw.preferences.IQueryTokenizerPreferenceBean",
"org.hibernate.connection.ConnectionProvider",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel$LimitRowsTextBoxListener",
"org.hibernate.type.DateType",
"net.sourceforge.squirrel_sql.fw.dialects.PostgreSQLDialectExt$PostgreSQLDialectHelper",
"org.apache.log4j.spi.RendererSupport",
"org.hibernate.type.SerializableType",
"org.hibernate.engine.CascadeStyle$6",
"org.apache.commons.httpclient.Credentials",
"org.hibernate.engine.CascadeStyle$5",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ResultFrameListener",
"org.fest.util.Collections",
"org.hibernate.engine.CascadeStyle$8",
"org.hibernate.engine.CascadeStyle$7",
"org.hibernate.engine.CascadeStyle$2",
"org.hibernate.property.PropertyAccessor",
"org.hibernate.engine.CascadeStyle$1",
"net.sourceforge.squirrel_sql.client.session.event.SQLExecutionAdapter",
"org.hibernate.engine.CascadeStyle$4",
"org.hibernate.engine.CascadeStyle$3",
"org.apache.commons.cli.OptionGroup",
"org.apache.log4j.helpers.AppenderAttachableImpl",
"net.sourceforge.squirrel_sql.fw.dialects.DB2DialectExt",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAliasColorProperties",
"net.sourceforge.squirrel_sql.client.preferences.INewSessionPropertiesPanel",
"org.hibernate.engine.CascadeStyle$9",
"org.hibernate.sql.ANSIJoinFragment",
"net.sourceforge.squirrel_sql.client.gui.mainframe.MainFrameToolBar$AliasesDropDown",
"net.sourceforge.squirrel_sql.fw.dialects.IngresDialectExt",
"net.sourceforge.squirrel_sql.client.ApplicationArguments$IOptions",
"org.apache.log4j.BasicConfigurator",
"org.hibernate.Interceptor",
"org.apache.log4j.helpers.AbsoluteTimeDateFormat",
"net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.ObjectTreeNode",
"net.sourceforge.squirrel_sql.client.session.mainpanel.BaseMainPanelTab",
"net.sourceforge.squirrel_sql.fw.sql.ForeignKeyColumnInfo",
"org.apache.log4j.Logger",
"net.sourceforge.squirrel_sql.client.gui.SessionWindowsHolder",
"org.hibernate.engine.CascadeStyle",
"org.hibernate.JDBCException",
"net.sourceforge.squirrel_sql.fw.sql.ProgressCallBack",
"net.sourceforge.squirrel_sql.client.mainframe.action.OpenConnectionCommand",
"net.sourceforge.squirrel_sql.client.util.ApplicationFileWrappers",
"org.hibernate.type.TextType",
"org.fest.swing.edt.GuiActionRunner",
"org.hibernate.type.MutableType",
"net.sourceforge.squirrel_sql.client.session.ISQLPanelAPI",
"org.apache.log4j.helpers.LogLog",
"net.sourceforge.squirrel_sql.fw.dialects.DerbyDialectExt",
"net.sourceforge.squirrel_sql.fw.util.StringManagerFactory",
"org.hibernate.type.LiteralType",
"net.sourceforge.squirrel_sql.fw.dialects.H2DialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.TimesTenDialectExt",
"org.fest.swing.applet.StatusDisplay",
"net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.IObjectTreeListener",
"org.hibernate.type.ClassType",
"org.apache.log4j.spi.RepositorySelector",
"org.hibernate.metadata.CollectionMetadata",
"net.sourceforge.squirrel_sql.client.gui.mainframe.MainFrame",
"org.hibernate.criterion.CriteriaSpecification",
"org.hibernate.type.CharArrayType",
"net.sourceforge.squirrel_sql.fw.dialects.MAXDBDialectExt",
"org.hibernate.sql.OracleJoinFragment",
"org.hibernate.MappingException",
"net.sourceforge.squirrel_sql.client.gui.mainframe.MainFrameToolBar$SessionDropDown",
"org.hibernate.type.AbstractType",
"net.sourceforge.squirrel_sql.fw.util.ISessionProperties",
"org.apache.log4j.or.DefaultRenderer",
"org.hibernate.dialect.InterbaseDialect",
"org.jfree.data.general.DatasetChangeEvent",
"org.hibernate.type.TrueFalseType",
"org.jfree.data.general.SeriesChangeListener",
"net.sourceforge.squirrel_sql.fw.util.log.Log4jLogger",
"net.sourceforge.squirrel_sql.fw.dialects.DatabaseObjectQualifier",
"net.sourceforge.squirrel_sql.fw.dialects.PointbaseDialectExt$PointbaseDialectHelper",
"org.hibernate.dialect.Cache71Dialect",
"org.apache.commons.httpclient.HttpConnection",
"net.sourceforge.squirrel_sql.fw.dialects.CommonHibernateDialect",
"net.sourceforge.squirrel_sql.fw.sql.SQLDriver",
"net.sourceforge.squirrel_sql.client.gui.util.ThreadCheckingRepaintManager",
"net.sourceforge.squirrel_sql.fw.dialects.H2DialectExt$H2DialectHelper",
"net.sourceforge.squirrel_sql.client.session.ISession",
"org.apache.commons.logging.impl.Log4JLogger",
"org.hibernate.cfg.Settings",
"net.sourceforge.squirrel_sql.client.ApplicationListener",
"net.sourceforge.squirrel_sql.client.session.BaseSQLEntryPanel",
"org.hibernate.property.Setter",
"org.hibernate.engine.query.sql.NativeSQLQuerySpecification",
"org.apache.log4j.Appender",
"net.sourceforge.squirrel_sql.fw.datasetviewer.DataSetException",
"net.sourceforge.squirrel_sql.fw.sql.dbobj.BestRowIdentifier",
"net.sourceforge.squirrel_sql.client.util.ApplicationFiles",
"org.hibernate.util.StringHelper",
"org.hibernate.stat.StatisticsImplementor",
"org.hibernate.engine.FilterDefinition",
"org.hibernate.type.CalendarDateType",
"org.hibernate.property.Getter",
"org.hibernate.type.StringType",
"net.sourceforge.squirrel_sql.client.plugin.IPluginDatabaseObjectType",
"org.apache.log4j.spi.HierarchyEventListener",
"net.sourceforge.squirrel_sql.client.gui.db.IToogleableAliasesList",
"net.sourceforge.squirrel_sql.fw.dialects.HSQLDialectExt$HSQLDialectHelper",
"net.sourceforge.squirrel_sql.fw.util.ClassLoaderListener",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel$ShowHistoryButton",
"org.apache.log4j.spi.LoggingEvent",
"net.sourceforge.squirrel_sql.fw.persist.ValidationException",
"org.hibernate.FlushMode",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.DesktopContainerFactory",
"org.hibernate.engine.ResultSetMappingDefinition",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ResultTabListener",
"org.apache.log4j.spi.ThrowableInformation",
"org.hibernate.cache.CacheConcurrencyStrategy",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLTab",
"org.hibernate.engine.QueryParameters",
"net.sourceforge.squirrel_sql.fw.dialects.McKoiDialectExt$McKoiDialectHelper",
"org.hibernate.dialect.function.SQLFunctionTemplate",
"net.sourceforge.squirrel_sql.client.session.mainpanel.objecttree.ObjectTreePanel$1",
"net.sourceforge.squirrel_sql.fw.xml.IXMLAboutToBeWritten",
"net.sourceforge.squirrel_sql.client.gui.session.SQLInternalFrame$SQLToolBar",
"org.apache.commons.httpclient.StatusLine",
"org.hibernate.type.AbstractCharArrayType",
"net.sourceforge.squirrel_sql.client.gui.mainframe.MainFrameToolBar"
);
}
private static void initMocksToAvoidTimeoutsInTheTests() throws ClassNotFoundException {
mock(Class.forName("java.sql.Connection", false, Session_ESTest_scaffolding.class.getClassLoader()));
}
private static void resetClasses() {
org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(Session_ESTest_scaffolding.class.getClassLoader());
org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses(
"net.sourceforge.squirrel_sql.fw.util.log.Log4jLoggerFactory",
"net.sourceforge.squirrel_sql.fw.util.log.Log4jLoggerFactory$1",
"org.apache.log4j.BasicConfigurator",
"org.apache.log4j.Category",
"org.apache.log4j.Logger",
"org.apache.log4j.Hierarchy",
"org.apache.log4j.spi.RootLogger",
"org.apache.log4j.Priority",
"org.apache.log4j.Level",
"org.apache.log4j.or.DefaultRenderer",
"org.apache.log4j.or.RendererMap",
"org.apache.log4j.DefaultCategoryFactory",
"org.apache.log4j.spi.DefaultRepositorySelector",
"org.apache.log4j.helpers.OptionConverter",
"org.apache.log4j.helpers.Loader",
"org.apache.log4j.helpers.LogLog",
"org.apache.log4j.PropertyConfigurator",
"org.apache.log4j.LogManager",
"org.apache.log4j.AppenderSkeleton",
"org.apache.log4j.WriterAppender",
"org.apache.log4j.ConsoleAppender",
"org.apache.log4j.Layout",
"org.apache.log4j.PatternLayout",
"org.apache.log4j.helpers.PatternParser",
"org.apache.log4j.helpers.FormattingInfo",
"org.apache.log4j.helpers.PatternConverter",
"org.apache.log4j.helpers.PatternParser$BasicPatternConverter",
"org.apache.log4j.helpers.PatternParser$LiteralPatternConverter",
"org.apache.log4j.helpers.PatternParser$NamedPatternConverter",
"org.apache.log4j.helpers.PatternParser$CategoryPatternConverter",
"org.apache.log4j.helpers.OnlyOnceErrorHandler",
"org.apache.log4j.helpers.QuietWriter",
"org.apache.log4j.helpers.AppenderAttachableImpl",
"net.sourceforge.squirrel_sql.fw.util.log.LoggerController",
"net.sourceforge.squirrel_sql.fw.util.log.Log4jLogger",
"org.apache.log4j.CategoryKey",
"org.apache.log4j.ProvisionNode",
"net.sourceforge.squirrel_sql.fw.util.Utilities",
"net.sourceforge.squirrel_sql.fw.util.StringManagerFactory",
"net.sourceforge.squirrel_sql.fw.util.StringManager",
"net.sourceforge.squirrel_sql.client.session.Session",
"net.sourceforge.squirrel_sql.client.session.Session$SQLConnectionListener",
"net.sourceforge.squirrel_sql.client.session.Session$3",
"net.sourceforge.squirrel_sql.client.session.Session$1",
"net.sourceforge.squirrel_sql.client.session.Session$2",
"net.sourceforge.squirrel_sql.fw.util.NullMessageHandler",
"net.sourceforge.squirrel_sql.client.plugin.DefaultPlugin",
"net.sourceforge.squirrel_sql.client.DummyAppPlugin",
"net.sourceforge.squirrel_sql.client.util.ApplicationFileWrappersImpl",
"net.sourceforge.squirrel_sql.fw.util.FileWrapperFactoryImpl",
"net.sourceforge.squirrel_sql.client.util.ApplicationFiles",
"net.sourceforge.squirrel_sql.client.ApplicationArguments",
"org.apache.commons.cli.Options",
"net.sourceforge.squirrel_sql.client.ApplicationArguments$IOptions",
"org.apache.commons.cli.Option",
"org.apache.commons.cli.OptionValidator",
"org.apache.commons.cli.OptionBuilder",
"org.apache.commons.cli.Parser",
"org.apache.commons.cli.GnuParser",
"org.apache.commons.cli.CommandLine",
"org.apache.commons.cli.Util",
"net.sourceforge.squirrel_sql.client.util.ApplicationFiles$1OldFileNameFilter",
"net.sourceforge.squirrel_sql.fw.id.UidIdentifier",
"net.sourceforge.squirrel_sql.fw.sql.SQLDriver",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAlias",
"net.sourceforge.squirrel_sql.fw.sql.SQLDriverPropertyCollection",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAliasSchemaProperties",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAliasColorProperties",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAliasConnectionProperties",
"net.sourceforge.squirrel_sql.fw.util.DefaultExceptionFormatter",
"net.sourceforge.squirrel_sql.fw.id.IntegerIdentifier",
"com.gargoylesoftware.base.resource.jdbc.ConnectionWrapper",
"net.sourceforge.squirrel_sql.fw.sql.SQLConnection",
"net.sourceforge.squirrel_sql.fw.sql.SQLDatabaseMetaData",
"net.sourceforge.squirrel_sql.fw.util.FileWrapperImpl",
"net.sourceforge.squirrel_sql.fw.util.BaseException",
"net.sourceforge.squirrel_sql.fw.persist.ValidationException",
"net.sourceforge.squirrel_sql.fw.sql.SQLDriver$IStrings",
"net.sourceforge.squirrel_sql.client.Version",
"net.sourceforge.squirrel_sql.client.session.mainpanel.BaseMainPanelTab",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ObjectTreeTab",
"net.sourceforge.squirrel_sql.fw.id.IntegerIdentifierFactory",
"net.sourceforge.squirrel_sql.client.session.BaseSQLEntryPanel",
"net.sourceforge.squirrel_sql.client.session.DefaultSQLEntryPanel",
"net.sourceforge.squirrel_sql.fw.util.PropertyChangeReporter",
"com.gargoylesoftware.base.resource.jdbc.StatementWrapper",
"com.gargoylesoftware.base.resource.jdbc.PreparedStatementWrapper",
"com.gargoylesoftware.base.resource.jdbc.CallableStatementWrapper",
"net.sourceforge.squirrel_sql.fw.sql.SQLDriverProperty",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAlias$IStrings",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLTab",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.TabWidget",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.SessionTabWidget",
"net.sourceforge.squirrel_sql.client.gui.session.SessionInternalFrame",
"net.sourceforge.squirrel_sql.fw.util.beanwrapper.StringWrapper",
"net.sourceforge.squirrel_sql.fw.util.ListMessageHandler",
"net.sourceforge.squirrel_sql.fw.preferences.BaseQueryTokenizerPreferenceBean",
"net.sourceforge.squirrel_sql.fw.sql.QueryTokenizer",
"net.sourceforge.squirrel_sql.fw.sql.QueryTokenizer$1",
"net.sourceforge.squirrel_sql.fw.dialects.CommonHibernateDialect",
"net.sourceforge.squirrel_sql.fw.dialects.AxionDialectExt",
"org.apache.commons.logging.impl.Log4JLogger",
"org.hibernate.dialect.function.StandardSQLFunction",
"org.hibernate.dialect.Dialect$1",
"org.hibernate.dialect.Dialect$2",
"org.hibernate.dialect.Dialect$3",
"org.hibernate.dialect.Dialect$4",
"org.hibernate.dialect.Dialect",
"net.sourceforge.squirrel_sql.fw.dialects.AxionDialectExt$AxionDialectHelper",
"org.hibernate.dialect.TypeNames",
"org.hibernate.dialect.function.SQLFunctionTemplate",
"org.hibernate.type.AbstractType",
"org.hibernate.util.StringHelper",
"org.hibernate.type.NullableType",
"org.hibernate.type.ImmutableType",
"org.hibernate.type.PrimitiveType",
"org.hibernate.type.LongType",
"org.hibernate.type.ShortType",
"org.hibernate.type.IntegerType",
"org.hibernate.type.ByteType",
"org.hibernate.type.FloatType",
"org.hibernate.type.DoubleType",
"org.hibernate.type.CharacterType",
"org.hibernate.type.StringType",
"org.hibernate.type.MutableType",
"org.hibernate.type.TimeType",
"org.hibernate.type.DateType",
"org.hibernate.type.TimestampType",
"org.hibernate.type.BooleanType",
"org.hibernate.type.CharBooleanType",
"org.hibernate.type.TrueFalseType",
"org.hibernate.type.YesNoType",
"org.hibernate.type.BigDecimalType",
"org.hibernate.type.BigIntegerType",
"org.hibernate.type.AbstractBynaryType",
"org.hibernate.type.BinaryType",
"org.hibernate.type.WrapperBinaryType",
"org.hibernate.type.AbstractCharArrayType",
"org.hibernate.type.CharArrayType",
"org.hibernate.type.CharacterArrayType",
"org.hibernate.type.TextType",
"org.hibernate.type.BlobType",
"org.hibernate.type.ClobType",
"org.hibernate.type.CalendarType",
"org.hibernate.type.CalendarDateType",
"org.hibernate.type.LocaleType",
"org.hibernate.type.CurrencyType",
"org.hibernate.type.TimeZoneType",
"org.hibernate.type.ClassType",
"org.hibernate.type.SerializableType",
"org.hibernate.type.AnyType",
"org.hibernate.Hibernate",
"org.hibernate.dialect.function.CastFunction",
"net.sourceforge.squirrel_sql.fw.dialects.DB2DialectExt",
"org.hibernate.dialect.DB2Dialect",
"net.sourceforge.squirrel_sql.fw.dialects.DB2DialectExt$DB2DialectHelper",
"org.hibernate.dialect.function.NoArgSQLFunction",
"org.hibernate.dialect.function.AnsiTrimEmulationFunction",
"org.hibernate.dialect.function.VarArgsSQLFunction",
"net.sourceforge.squirrel_sql.fw.dialects.DaffodilDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.DaffodilDialectExt$DaffodilDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.DerbyDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.DerbyDialectExt$DerbyDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.FirebirdDialectExt",
"org.hibernate.dialect.InterbaseDialect",
"org.hibernate.dialect.FirebirdDialect",
"net.sourceforge.squirrel_sql.fw.dialects.FirebirdDialectExt$FirebirdDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.FrontBaseDialectExt",
"org.hibernate.dialect.FrontBaseDialect",
"net.sourceforge.squirrel_sql.fw.dialects.FrontBaseDialectExt$FrontBaseDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.GenericDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.GenericDialectExt$GenericDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.HADBDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.HADBDialectExt$HADBDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.H2DialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.H2DialectExt$H2DialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.HSQLDialectExt",
"org.hibernate.exception.TemplatedViolatedConstraintNameExtracter",
"org.hibernate.dialect.HSQLDialect$1",
"org.hibernate.dialect.HSQLDialect",
"net.sourceforge.squirrel_sql.fw.dialects.HSQLDialectExt$HSQLDialectHelper",
"org.hibernate.property.BasicPropertyAccessor",
"org.hibernate.property.DirectPropertyAccessor",
"org.hibernate.util.ReflectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.InformixDialectExt",
"org.hibernate.dialect.InformixDialect$1",
"org.hibernate.dialect.InformixDialect",
"net.sourceforge.squirrel_sql.fw.dialects.InformixDialectExt$InformixDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.InterbaseDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.InterbaseDialectExt$InterbaseDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.IngresDialectExt",
"org.hibernate.dialect.IngresDialect",
"net.sourceforge.squirrel_sql.fw.dialects.IngresDialectExt$IngresDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.MAXDBDialectExt",
"org.hibernate.dialect.SAPDBDialect",
"net.sourceforge.squirrel_sql.fw.dialects.MAXDBDialectExt$MAXDBDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.McKoiDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.McKoiDialectExt$McKoiDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.MySQLDialectExt",
"org.hibernate.dialect.MySQLDialect",
"net.sourceforge.squirrel_sql.fw.dialects.MySQLDialectExt$MySQLDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.MySQL5DialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.NetezzaDialextExt",
"org.hibernate.dialect.PostgreSQLDialect$1",
"org.hibernate.dialect.PostgreSQLDialect",
"net.sourceforge.squirrel_sql.fw.dialects.NetezzaDialextExt$NetezzaDialectHelper",
"org.hibernate.dialect.function.PositionSubstringFunction",
"net.sourceforge.squirrel_sql.fw.dialects.GreenplumDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.GreenplumDialectExt$GreenplumDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.OracleDialectExt",
"org.hibernate.dialect.Oracle9Dialect$1",
"org.hibernate.dialect.Oracle9Dialect",
"net.sourceforge.squirrel_sql.fw.dialects.OracleDialectExt$OracleDialectHelper",
"org.hibernate.dialect.function.NvlFunction",
"net.sourceforge.squirrel_sql.fw.dialects.PointbaseDialectExt",
"org.hibernate.dialect.PointbaseDialect",
"net.sourceforge.squirrel_sql.fw.dialects.PointbaseDialectExt$PointbaseDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.PostgreSQLDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.PostgreSQLDialectExt$PostgreSQLDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.ProgressDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.ProgressDialectExt$ProgressDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.SybaseDialectExt",
"org.hibernate.dialect.SybaseDialect",
"net.sourceforge.squirrel_sql.fw.dialects.SybaseDialectExt$SybaseDialectHelper",
"org.hibernate.dialect.function.CharIndexFunction",
"net.sourceforge.squirrel_sql.fw.dialects.SQLServerDialectExt",
"net.sourceforge.squirrel_sql.fw.dialects.SQLServerDialectExt$SQLServerDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.TimesTenDialectExt",
"org.hibernate.dialect.TimesTenDialect",
"net.sourceforge.squirrel_sql.fw.dialects.TimesTenDialectExt$TimesTenDialectHelper",
"net.sourceforge.squirrel_sql.fw.dialects.IntersystemsCacheDialectExt",
"org.hibernate.dialect.Cache71Dialect$1",
"org.hibernate.dialect.Cache71Dialect",
"net.sourceforge.squirrel_sql.fw.dialects.IntersystemsCacheDialectExt$CacheHelper",
"org.hibernate.dialect.function.StandardJDBCEscapeFunction",
"org.hibernate.dialect.function.ConvertFunction",
"org.hibernate.dialect.function.ConditionalParenthesisFunction",
"net.sourceforge.squirrel_sql.fw.gui.DialogUtils",
"net.sourceforge.squirrel_sql.fw.dialects.DialectFactory",
"com.gargoylesoftware.base.resource.jdbc.DatabaseMetaDataWrapper",
"net.sourceforge.squirrel_sql.fw.dialects.DialectType",
"org.apache.commons.lang.StringUtils",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel",
"net.sourceforge.squirrel_sql.fw.gui.IntegerField",
"net.sourceforge.squirrel_sql.fw.gui.IntegerField$IntegerDocument",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel$SqlComboListener",
"net.sourceforge.squirrel_sql.client.session.event.SQLExecutionAdapter",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLPanel$SQLExecutorHistoryListener",
"net.sourceforge.squirrel_sql.client.session.SQLPanelAPI",
"net.sourceforge.squirrel_sql.client.session.FileManager",
"net.sourceforge.squirrel_sql.fw.util.IOUtilitiesImpl",
"org.fest.swing.applet.BasicAppletContext$EmptyAppletEnumeration",
"org.fest.swing.applet.BasicAppletContext",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLResultExecuterPanel",
"net.sourceforge.squirrel_sql.client.session.mainpanel.ResultTabFactory",
"net.sourceforge.squirrel_sql.client.session.mainpanel.SQLResultExecuterPanel$1",
"net.sourceforge.squirrel_sql.client.gui.session.ObjectTreeInternalFrame",
"org.fest.swing.applet.AppletViewer",
"org.fest.swing.edt.GuiAction",
"org.fest.swing.edt.GuiQuery",
"org.fest.swing.applet.AppletViewer$1",
"org.fest.swing.edt.GuiActionRunner",
"org.fest.util.Throwables",
"org.fest.util.Collections",
"org.fest.util.StackTraces",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.DockWidget",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.DesktopContainerFactory",
"net.sourceforge.squirrel_sql.client.gui.db.SQLAliasSchemaDetailProperties",
"net.sourceforge.squirrel_sql.client.gui.session.SQLInternalFrame",
"org.jfree.data.general.AbstractDataset",
"org.jfree.data.general.AbstractSeriesDataset",
"org.jfree.data.xy.AbstractXYDataset",
"org.jfree.data.xy.AbstractIntervalXYDataset",
"org.jfree.data.xy.DefaultIntervalXYDataset",
"org.jfree.data.general.DatasetGroup",
"net.sourceforge.squirrel_sql.client.gui.db.SchemaLoadInfo",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.docktabdesktop.SmallTabButton$1",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.docktabdesktop.SmallTabButton",
"net.sourceforge.squirrel_sql.fw.sql.SQLConnection$1",
"net.sourceforge.squirrel_sql.client.gui.db.SchemaNameLoadInfo",
"net.sourceforge.squirrel_sql.client.gui.desktopcontainer.DialogWidget",
"org.jfree.data.time.RegularTimePeriod",
"org.jfree.data.time.Minute",
"org.jfree.data.time.Day",
"org.jfree.data.general.CombinedDataset"
);
}
}
|
package io.reflectoring.testing.web;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.reflectoring.testing.domain.RegisterUseCase;
import io.reflectoring.testing.domain.User;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static io.reflectoring.testing.web.ResponseBodyMatchers.*;
import static org.assertj.core.api.Java6Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(controllers = RegisterRestController.class)
class RegisterRestControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private RegisterUseCase registerUseCase;
@Test
void whenValidUrlAndMethodAndContentType_thenReturns200() throws Exception {
UserResource user = new UserResource("Zaphod", "zaphod@galaxy.net");
mockMvc.perform(post("/forums/42/register")
.param("sendWelcomeMail", "true")
.content(objectMapper.writeValueAsString(user))
.contentType("application/json"))
.andExpect(status().isOk());
}
@Test
void whenValidInput_thenReturns200() throws Exception {
UserResource user = new UserResource("Zaphod", "zaphod@galaxy.net");
mockMvc.perform(post("/forums/{forumId}/register", 42L)
.contentType("application/json")
.param("sendWelcomeMail", "true")
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isOk());
}
@Test
void whenValidInput_thenMapsToBusinessModel() throws Exception {
UserResource user = new UserResource("Zaphod", "zaphod@galaxy.net");
mockMvc.perform(post("/forums/{forumId}/register", 42L)
.contentType("application/json")
.param("sendWelcomeMail", "true")
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isOk());
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
verify(registerUseCase, times(1)).registerUser(userCaptor.capture(), eq(true));
assertThat(userCaptor.getValue().getName()).isEqualTo("Zaphod");
assertThat(userCaptor.getValue().getEmail()).isEqualTo("zaphod@galaxy.net");
}
@Test
void whenValidInput_thenReturnsUserResource() throws Exception {
UserResource user = new UserResource("Zaphod", "zaphod@galaxy.net");
MvcResult mvcResult = mockMvc.perform(post("/forums/{forumId}/register", 42L)
.contentType("application/json")
.param("sendWelcomeMail", "true")
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isOk())
.andReturn();
UserResource expectedResponseBody = user;
String actualResponseBody = mvcResult.getResponse().getContentAsString();
assertThat(objectMapper.writeValueAsString(expectedResponseBody))
.isEqualToIgnoringWhitespace(actualResponseBody);
}
@Test
void whenValidInput_thenReturnsUserResource_withFluentApi() throws Exception {
UserResource user = new UserResource("Zaphod", "zaphod@galaxy.net");
UserResource expectedResponseBody = user;
mockMvc.perform(post("/forums/{forumId}/register", 42L)
.contentType("application/json")
.param("sendWelcomeMail", "true")
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isOk())
.andExpect(responseBody().containsObjectAsJson(expectedResponseBody, UserResource.class));
}
@Test
void whenValidInput_thenReturnsUserResource_withTypedAssertion() throws Exception {
UserResource user = new UserResource("Zaphod", "zaphod@galaxy.net");
MvcResult mvcResult = mockMvc.perform(post("/forums/{forumId}/register", 42L)
.contentType("application/json")
.param("sendWelcomeMail", "true")
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isOk())
.andReturn();
UserResource expected = user;
UserResource actualResponseBody = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), UserResource.class);
assertThat(expected.getName()).isEqualTo(actualResponseBody.getName());
assertThat(expected.getEmail()).isEqualTo(actualResponseBody.getEmail());
}
@Test
void whenNullValue_thenReturns400() throws Exception {
UserResource user = new UserResource(null, "zaphod@galaxy.net");
mockMvc.perform(post("/forums/{forumId}/register", 42L)
.contentType("application/json")
.param("sendWelcomeMail", "true")
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isBadRequest());
}
@Test
void whenNullValue_thenReturns400AndErrorResult() throws Exception {
UserResource user = new UserResource(null, "zaphod@galaxy.net");
MvcResult mvcResult = mockMvc.perform(post("/forums/{forumId}/register", 42L)
.contentType("application/json")
.param("sendWelcomeMail", "true")
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isBadRequest())
.andReturn();
ErrorResult expectedErrorResponse = new ErrorResult("name", "must not be null");
String actualResponseBody = mvcResult.getResponse().getContentAsString();
String expectedResponseBody = objectMapper.writeValueAsString(expectedErrorResponse);
assertThat(expectedResponseBody).isEqualToIgnoringWhitespace(actualResponseBody);
}
@Test
void whenNullValue_thenReturns400AndErrorResult_withFluentApi() throws Exception {
UserResource user = new UserResource(null, "zaphod@galaxy.net");
mockMvc.perform(post("/forums/{forumId}/register", 42L)
.contentType("application/json")
.param("sendWelcomeMail", "true")
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isBadRequest())
.andExpect(responseBody().containsError("name", "must not be null"));
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.data.input.avro;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import io.confluent.kafka.schemaregistry.ParsedSchema;
import io.confluent.kafka.schemaregistry.avro.AvroSchema;
import io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient;
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
import io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DecoderFactory;
import org.apache.druid.guice.annotations.Json;
import org.apache.druid.java.util.common.parsers.ParseException;
import org.apache.druid.utils.DynamicConfigProviderUtils;
import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class SchemaRegistryBasedAvroBytesDecoder implements AvroBytesDecoder
{
private final SchemaRegistryClient registry;
private final String url;
private final int capacity;
private final List<String> urls;
private final Map<String, Object> config;
private final Map<String, Object> headers;
private final ObjectMapper jsonMapper;
public static final String DRUID_DYNAMIC_CONFIG_PROVIDER_KEY = "druid.dynamic.config.provider";
@JsonCreator
public SchemaRegistryBasedAvroBytesDecoder(
@JsonProperty("url") @Deprecated String url,
@JsonProperty("capacity") Integer capacity,
@JsonProperty("urls") @Nullable List<String> urls,
@JsonProperty("config") @Nullable Map<String, Object> config,
@JsonProperty("headers") @Nullable Map<String, Object> headers,
@JacksonInject @Json ObjectMapper jsonMapper
)
{
this.url = url;
this.capacity = capacity == null ? Integer.MAX_VALUE : capacity;
this.urls = urls;
this.config = config;
this.headers = headers;
this.jsonMapper = jsonMapper;
if (url != null && !url.isEmpty()) {
this.registry = new CachedSchemaRegistryClient(this.url, this.capacity, DynamicConfigProviderUtils.extraConfigAndSetObjectMap(config, DRUID_DYNAMIC_CONFIG_PROVIDER_KEY, this.jsonMapper), DynamicConfigProviderUtils.extraConfigAndSetStringMap(headers, DRUID_DYNAMIC_CONFIG_PROVIDER_KEY, this.jsonMapper));
} else {
this.registry = new CachedSchemaRegistryClient(this.urls, this.capacity, DynamicConfigProviderUtils.extraConfigAndSetObjectMap(config, DRUID_DYNAMIC_CONFIG_PROVIDER_KEY, this.jsonMapper), DynamicConfigProviderUtils.extraConfigAndSetStringMap(headers, DRUID_DYNAMIC_CONFIG_PROVIDER_KEY, this.jsonMapper));
}
}
@JsonProperty
public String getUrl()
{
return url;
}
@JsonProperty
public int getCapacity()
{
return capacity;
}
@JsonProperty
public List<String> getUrls()
{
return urls;
}
@JsonProperty
public Map<String, Object> getConfig()
{
return config;
}
@JsonProperty
public Map<String, Object> getHeaders()
{
return headers;
}
//For UT only
@VisibleForTesting
SchemaRegistryBasedAvroBytesDecoder(SchemaRegistryClient registry)
{
this.url = null;
this.capacity = Integer.MAX_VALUE;
this.urls = null;
this.config = null;
this.headers = null;
this.registry = registry;
this.jsonMapper = new ObjectMapper();
}
@Override
public GenericRecord parse(ByteBuffer bytes)
{
int length = bytes.limit() - 1 - 4;
if (length < 0) {
throw new ParseException(null, "Failed to decode avro message, not enough bytes to decode (%s)", bytes.limit());
}
bytes.get(); // ignore first \0 byte
int id = bytes.getInt(); // extract schema registry id
int offset = bytes.position() + bytes.arrayOffset();
Schema schema;
try {
ParsedSchema parsedSchema = registry.getSchemaById(id);
schema = parsedSchema instanceof AvroSchema ? ((AvroSchema) parsedSchema).rawSchema() : null;
}
catch (IOException | RestClientException ex) {
throw new ParseException(null, "Failed to get Avro schema: %s", id);
}
if (schema == null) {
throw new ParseException(null, "Failed to find Avro schema: %s", id);
}
DatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
try {
return reader.read(null, DecoderFactory.get().binaryDecoder(bytes.array(), offset, length, null));
}
catch (Exception e) {
throw new ParseException(null, e, "Fail to decode Avro message for schema: %s!", id);
}
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SchemaRegistryBasedAvroBytesDecoder that = (SchemaRegistryBasedAvroBytesDecoder) o;
return capacity == that.capacity
&& Objects.equals(url, that.url)
&& Objects.equals(urls, that.urls)
&& Objects.equals(config, that.config)
&& Objects.equals(headers, that.headers);
}
@Override
public int hashCode()
{
return Objects.hash(registry, url, capacity, urls, config, headers, jsonMapper);
}
}
|
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.web;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.security.web.util.UrlUtils;
/**
* Holds objects associated with a HTTP filter.<P>Guarantees the request and response are instances of
* <code>HttpServletRequest</code> and <code>HttpServletResponse</code>, and that there are no <code>null</code>
* objects.
* <p>
* Required so that security system classes can obtain access to the filter environment, as well as the request
* and response.
*
* @author Ben Alex
* @author colin sampaleanu
* @author Luke Taylor
*/
public class FilterInvocation {
//~ Static fields ==================================================================================================
static final FilterChain DUMMY_CHAIN = new FilterChain() {
public void doFilter(ServletRequest req, ServletResponse res) throws IOException, ServletException {
throw new UnsupportedOperationException("Dummy filter chain");
}
};
//~ Instance fields ================================================================================================
private FilterChain chain;
private HttpServletRequest request;
private HttpServletResponse response;
//~ Constructors ===================================================================================================
public FilterInvocation(ServletRequest request, ServletResponse response, FilterChain chain) {
if ((request == null) || (response == null) || (chain == null)) {
throw new IllegalArgumentException("Cannot pass null values to constructor");
}
this.request = (HttpServletRequest) request;
this.response = (HttpServletResponse) response;
this.chain = chain;
}
public FilterInvocation(String servletPath, String method) {
this(null, servletPath, method);
}
public FilterInvocation(String contextPath, String servletPath, String method) {
this(contextPath, servletPath, null, null, method);
}
public FilterInvocation(String contextPath, String servletPath, String pathInfo, String query, String method) {
DummyRequest request = new DummyRequest();
if (contextPath == null) {
contextPath = "/cp";
}
request.setContextPath(contextPath);
request.setServletPath(servletPath);
request.setRequestURI(contextPath + servletPath + (pathInfo == null ? "" : pathInfo));
request.setPathInfo(pathInfo);
request.setQueryString(query);
request.setMethod(method);
this.request = request;
}
//~ Methods ========================================================================================================
public FilterChain getChain() {
return chain;
}
/**
* Indicates the URL that the user agent used for this request.
* <p>
* The returned URL does <b>not</b> reflect the port number determined from a
* {@link org.springframework.security.web.PortResolver}.
*
* @return the full URL of this request
*/
public String getFullRequestUrl() {
return UrlUtils.buildFullRequestUrl(request);
}
public HttpServletRequest getHttpRequest() {
return request;
}
public HttpServletResponse getHttpResponse() {
return response;
}
/**
* Obtains the web application-specific fragment of the URL.
*
* @return the URL, excluding any server name, context path or servlet path
*/
public String getRequestUrl() {
return UrlUtils.buildRequestUrl(request);
}
public HttpServletRequest getRequest() {
return getHttpRequest();
}
public HttpServletResponse getResponse() {
return getHttpResponse();
}
public String toString() {
return "FilterInvocation: URL: " + getRequestUrl();
}
}
@SuppressWarnings({"unchecked", "deprecation"})
class DummyRequest implements HttpServletRequest {
private String requestURI;
private String contextPath = "";
private String servletPath;
private String pathInfo;
private String queryString;
private String method;
public void setRequestURI(String requestURI) {
this.requestURI = requestURI;
}
public void setPathInfo(String pathInfo) {
this.pathInfo = pathInfo;
}
public String getRequestURI() {
return requestURI;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public String getContextPath() {
return contextPath;
}
public void setServletPath(String servletPath) {
this.servletPath = servletPath;
}
public String getServletPath() {
return servletPath;
}
public void setMethod(String method) {
this.method = method;
}
public String getMethod() {
return method;
}
public String getPathInfo() {
return pathInfo;
}
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public String getAuthType() {
throw new UnsupportedOperationException();
}
public Cookie[] getCookies() {
throw new UnsupportedOperationException();
}
public long getDateHeader(String name) {
throw new UnsupportedOperationException();
}
public String getHeader(String name) {
throw new UnsupportedOperationException();
}
public Enumeration getHeaderNames() {
throw new UnsupportedOperationException();
}
public Enumeration getHeaders(String name) {
throw new UnsupportedOperationException();
}
public int getIntHeader(String name) {
throw new UnsupportedOperationException();
}
public String getPathTranslated() {
throw new UnsupportedOperationException();
}
public String getRemoteUser() {
throw new UnsupportedOperationException();
}
public StringBuffer getRequestURL() {
throw new UnsupportedOperationException();
}
public String getRequestedSessionId() {
throw new UnsupportedOperationException();
}
public HttpSession getSession() {
throw new UnsupportedOperationException();
}
public HttpSession getSession(boolean create) {
throw new UnsupportedOperationException();
}
public Principal getUserPrincipal() {
throw new UnsupportedOperationException();
}
public boolean isRequestedSessionIdFromCookie() {
throw new UnsupportedOperationException();
}
public boolean isRequestedSessionIdFromURL() {
throw new UnsupportedOperationException();
}
public boolean isRequestedSessionIdFromUrl() {
throw new UnsupportedOperationException();
}
public boolean isRequestedSessionIdValid() {
throw new UnsupportedOperationException();
}
public boolean isUserInRole(String role) {
throw new UnsupportedOperationException();
}
public Object getAttribute(String name) {
throw new UnsupportedOperationException();
}
public Enumeration getAttributeNames() {
throw new UnsupportedOperationException();
}
public String getCharacterEncoding() {
throw new UnsupportedOperationException();
}
public int getContentLength() {
throw new UnsupportedOperationException();
}
public String getContentType() {
throw new UnsupportedOperationException();
}
public ServletInputStream getInputStream() throws IOException {
throw new UnsupportedOperationException();
}
public String getLocalAddr() {
throw new UnsupportedOperationException();
}
public String getLocalName() {
throw new UnsupportedOperationException();
}
public int getLocalPort() {
throw new UnsupportedOperationException();
}
public Locale getLocale() {
throw new UnsupportedOperationException();
}
public Enumeration getLocales() {
throw new UnsupportedOperationException();
}
public String getParameter(String name) {
throw new UnsupportedOperationException();
}
public Map getParameterMap() {
throw new UnsupportedOperationException();
}
public Enumeration getParameterNames() {
throw new UnsupportedOperationException();
}
public String[] getParameterValues(String name) {
throw new UnsupportedOperationException();
}
public String getProtocol() {
throw new UnsupportedOperationException();
}
public BufferedReader getReader() throws IOException {
throw new UnsupportedOperationException();
}
public String getRealPath(String path) {
throw new UnsupportedOperationException();
}
public String getRemoteAddr() {
throw new UnsupportedOperationException();
}
public String getRemoteHost() {
throw new UnsupportedOperationException();
}
public int getRemotePort() {
throw new UnsupportedOperationException();
}
public RequestDispatcher getRequestDispatcher(String path) {
throw new UnsupportedOperationException();
}
public String getScheme() {
throw new UnsupportedOperationException();
}
public String getServerName() {
throw new UnsupportedOperationException();
}
public int getServerPort() {
throw new UnsupportedOperationException();
}
public boolean isSecure() {
throw new UnsupportedOperationException();
}
public void removeAttribute(String name) {
throw new UnsupportedOperationException();
}
public void setAttribute(String name, Object o) {
throw new UnsupportedOperationException();
}
public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
throw new UnsupportedOperationException();
}
}
@SuppressWarnings({"deprecation"})
class DummyResponse implements HttpServletResponse {
public void addCookie(Cookie cookie) {
throw new UnsupportedOperationException();
}
public void addDateHeader(String name, long date) {
throw new UnsupportedOperationException();
}
public void addHeader(String name, String value) {
throw new UnsupportedOperationException();
}
public void addIntHeader(String name, int value) {
throw new UnsupportedOperationException();
}
public boolean containsHeader(String name) {
throw new UnsupportedOperationException();
}
public String encodeRedirectURL(String url) {
throw new UnsupportedOperationException();
}
public String encodeRedirectUrl(String url) {
throw new UnsupportedOperationException();
}
public String encodeURL(String url) {
throw new UnsupportedOperationException();
}
public String encodeUrl(String url) {
throw new UnsupportedOperationException();
}
public void sendError(int sc) throws IOException {
throw new UnsupportedOperationException();
}
public void sendError(int sc, String msg) throws IOException {
throw new UnsupportedOperationException();
}
public void sendRedirect(String location) throws IOException {
throw new UnsupportedOperationException();
}
public void setDateHeader(String name, long date) {
throw new UnsupportedOperationException();
}
public void setHeader(String name, String value) {
throw new UnsupportedOperationException();
}
public void setIntHeader(String name, int value) {
throw new UnsupportedOperationException();
}
public void setStatus(int sc) {
throw new UnsupportedOperationException();
}
public void setStatus(int sc, String sm) {
throw new UnsupportedOperationException();
}
public void flushBuffer() throws IOException {
throw new UnsupportedOperationException();
}
public int getBufferSize() {
throw new UnsupportedOperationException();
}
public String getCharacterEncoding() {
throw new UnsupportedOperationException();
}
public String getContentType() {
throw new UnsupportedOperationException();
}
public Locale getLocale() {
throw new UnsupportedOperationException();
}
public ServletOutputStream getOutputStream() throws IOException {
throw new UnsupportedOperationException();
}
public PrintWriter getWriter() throws IOException {
throw new UnsupportedOperationException();
}
public boolean isCommitted() {
throw new UnsupportedOperationException();
}
public void reset() {
throw new UnsupportedOperationException();
}
public void resetBuffer() {
throw new UnsupportedOperationException();
}
public void setBufferSize(int size) {
throw new UnsupportedOperationException();
}
public void setCharacterEncoding(String charset) {
throw new UnsupportedOperationException();
}
public void setContentLength(int len) {
throw new UnsupportedOperationException();
}
public void setContentType(String type) {
throw new UnsupportedOperationException();
}
public void setLocale(Locale loc) {
throw new UnsupportedOperationException();
}
}
|
package org.openstack4j.api.heat;
import java.util.List;
import org.openstack4j.model.heat.Event;
/**
* This interface defines all methods for the manipulation of events
*
* @author Octopus Zhang
*/
public interface EventsService {
/**
* Gets a list of currently existing {@link Event}s for a specified stack.
*
* @param stackId The unique identifier for a stack
* @param stackName The name of a stack
* @return the list of {@link Event}s
*/
List<? extends Event> list(String stackName, String stackId);
/**
* Gets a list of currently existing {@link Event}s for a specified stack resource.
*
* @param stackId The unique identifier for a stack
* @param stackName The name of a stack
* @param resourceName The name of a resource in the stack
* @return the list of {@link Event}s
*/
List<? extends Event> list(String stackName, String stackId, String resourceName);
/**
* Shows details for a specified event.
*
* @param stackId The unique identifier for a stack
* @param stackName The name of a stack
* @param resourceName The name of a resource in the stack
* @param eventId The unique identifier of an event related to the resource in the stack
* @return event details
*/
Event show(String stackName, String stackId, String resourceName, String eventId);
}
|
/*******************************************************************************
* Copyright 2017 The MITRE Corporation
* and the MIT Internet Trust Consortium
*
* 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.mitre.openid.connect;
import static org.mitre.util.JsonUtils.getAsArray;
import static org.mitre.util.JsonUtils.getAsDate;
import static org.mitre.util.JsonUtils.getAsJweAlgorithm;
import static org.mitre.util.JsonUtils.getAsJweEncryptionMethod;
import static org.mitre.util.JsonUtils.getAsJwsAlgorithm;
import static org.mitre.util.JsonUtils.getAsPkceAlgorithm;
import static org.mitre.util.JsonUtils.getAsString;
import static org.mitre.util.JsonUtils.getAsStringSet;
import java.text.ParseException;
import org.mitre.oauth2.model.ClientDetailsEntity;
import org.mitre.oauth2.model.ClientDetailsEntity.AppType;
import org.mitre.oauth2.model.ClientDetailsEntity.AuthMethod;
import org.mitre.oauth2.model.ClientDetailsEntity.SubjectType;
import org.mitre.oauth2.model.RegisteredClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTParser;
import static org.mitre.oauth2.model.RegisteredClientFields.APPLICATION_TYPE;
import static org.mitre.oauth2.model.RegisteredClientFields.CLAIMS_REDIRECT_URIS;
import static org.mitre.oauth2.model.RegisteredClientFields.CLIENT_ID;
import static org.mitre.oauth2.model.RegisteredClientFields.CLIENT_ID_ISSUED_AT;
import static org.mitre.oauth2.model.RegisteredClientFields.CLIENT_NAME;
import static org.mitre.oauth2.model.RegisteredClientFields.CLIENT_SECRET;
import static org.mitre.oauth2.model.RegisteredClientFields.CLIENT_SECRET_EXPIRES_AT;
import static org.mitre.oauth2.model.RegisteredClientFields.CLIENT_URI;
import static org.mitre.oauth2.model.RegisteredClientFields.CODE_CHALLENGE_METHOD;
import static org.mitre.oauth2.model.RegisteredClientFields.CONTACTS;
import static org.mitre.oauth2.model.RegisteredClientFields.DEFAULT_ACR_VALUES;
import static org.mitre.oauth2.model.RegisteredClientFields.DEFAULT_MAX_AGE;
import static org.mitre.oauth2.model.RegisteredClientFields.GRANT_TYPES;
import static org.mitre.oauth2.model.RegisteredClientFields.ID_TOKEN_ENCRYPTED_RESPONSE_ALG;
import static org.mitre.oauth2.model.RegisteredClientFields.ID_TOKEN_ENCRYPTED_RESPONSE_ENC;
import static org.mitre.oauth2.model.RegisteredClientFields.ID_TOKEN_SIGNED_RESPONSE_ALG;
import static org.mitre.oauth2.model.RegisteredClientFields.INITIATE_LOGIN_URI;
import static org.mitre.oauth2.model.RegisteredClientFields.JWKS;
import static org.mitre.oauth2.model.RegisteredClientFields.JWKS_URI;
import static org.mitre.oauth2.model.RegisteredClientFields.LOGO_URI;
import static org.mitre.oauth2.model.RegisteredClientFields.POLICY_URI;
import static org.mitre.oauth2.model.RegisteredClientFields.POST_LOGOUT_REDIRECT_URIS;
import static org.mitre.oauth2.model.RegisteredClientFields.REDIRECT_URIS;
import static org.mitre.oauth2.model.RegisteredClientFields.REGISTRATION_ACCESS_TOKEN;
import static org.mitre.oauth2.model.RegisteredClientFields.REGISTRATION_CLIENT_URI;
import static org.mitre.oauth2.model.RegisteredClientFields.REQUEST_OBJECT_SIGNING_ALG;
import static org.mitre.oauth2.model.RegisteredClientFields.REQUEST_URIS;
import static org.mitre.oauth2.model.RegisteredClientFields.REQUIRE_AUTH_TIME;
import static org.mitre.oauth2.model.RegisteredClientFields.RESPONSE_TYPES;
import static org.mitre.oauth2.model.RegisteredClientFields.SCOPE;
import static org.mitre.oauth2.model.RegisteredClientFields.SCOPE_SEPARATOR;
import static org.mitre.oauth2.model.RegisteredClientFields.SECTOR_IDENTIFIER_URI;
import static org.mitre.oauth2.model.RegisteredClientFields.SOFTWARE_ID;
import static org.mitre.oauth2.model.RegisteredClientFields.SOFTWARE_STATEMENT;
import static org.mitre.oauth2.model.RegisteredClientFields.SOFTWARE_VERSION;
import static org.mitre.oauth2.model.RegisteredClientFields.SUBJECT_TYPE;
import static org.mitre.oauth2.model.RegisteredClientFields.TOKEN_ENDPOINT_AUTH_METHOD;
import static org.mitre.oauth2.model.RegisteredClientFields.TOKEN_ENDPOINT_AUTH_SIGNING_ALG;
import static org.mitre.oauth2.model.RegisteredClientFields.TOS_URI;
import static org.mitre.oauth2.model.RegisteredClientFields.USERINFO_ENCRYPTED_RESPONSE_ALG;
import static org.mitre.oauth2.model.RegisteredClientFields.USERINFO_ENCRYPTED_RESPONSE_ENC;
import static org.mitre.oauth2.model.RegisteredClientFields.USERINFO_SIGNED_RESPONSE_ALG;
/**
* Utility class to handle the parsing and serialization of ClientDetails objects.
*
* @author jricher
*
*/
public class ClientDetailsEntityJsonProcessor {
private static Logger logger = LoggerFactory.getLogger(ClientDetailsEntityJsonProcessor.class);
private static JsonParser parser = new JsonParser();
/**
*
* Create an unbound ClientDetailsEntity from the given JSON string.
*
* @param jsonString
* @return the entity if successful, null otherwise
*/
public static ClientDetailsEntity parse(String jsonString) {
JsonElement jsonEl = parser.parse(jsonString);
return parse(jsonEl);
}
public static ClientDetailsEntity parse(JsonElement jsonEl) {
if (jsonEl.isJsonObject()) {
JsonObject o = jsonEl.getAsJsonObject();
ClientDetailsEntity c = new ClientDetailsEntity();
// these two fields should only be sent in the update request, and MUST match existing values
c.setClientId(getAsString(o, CLIENT_ID));
c.setClientSecret(getAsString(o, CLIENT_SECRET));
// OAuth DynReg
c.setRedirectUris(getAsStringSet(o, REDIRECT_URIS));
c.setClientName(getAsString(o, CLIENT_NAME));
c.setClientUri(getAsString(o, CLIENT_URI));
c.setLogoUri(getAsString(o, LOGO_URI));
c.setContacts(getAsStringSet(o, CONTACTS));
c.setTosUri(getAsString(o, TOS_URI));
String authMethod = getAsString(o, TOKEN_ENDPOINT_AUTH_METHOD);
if (authMethod != null) {
c.setTokenEndpointAuthMethod(AuthMethod.getByValue(authMethod));
}
// scope is a space-separated string
String scope = getAsString(o, SCOPE);
if (scope != null) {
c.setScope(Sets.newHashSet(Splitter.on(SCOPE_SEPARATOR).split(scope)));
}
c.setGrantTypes(getAsStringSet(o, GRANT_TYPES));
c.setResponseTypes(getAsStringSet(o, RESPONSE_TYPES));
c.setPolicyUri(getAsString(o, POLICY_URI));
c.setJwksUri(getAsString(o, JWKS_URI));
JsonElement jwksEl = o.get(JWKS);
if (jwksEl != null && jwksEl.isJsonObject()) {
try {
JWKSet jwks = JWKSet.parse(jwksEl.toString()); // we have to pass this through Nimbus's parser as a string
c.setJwks(jwks);
} catch (ParseException e) {
logger.error("Unable to parse JWK Set for client", e);
return null;
}
}
// OIDC Additions
String appType = getAsString(o, APPLICATION_TYPE);
if (appType != null) {
c.setApplicationType(AppType.getByValue(appType));
}
c.setSectorIdentifierUri(getAsString(o, SECTOR_IDENTIFIER_URI));
String subjectType = getAsString(o, SUBJECT_TYPE);
if (subjectType != null) {
c.setSubjectType(SubjectType.getByValue(subjectType));
}
c.setRequestObjectSigningAlg(getAsJwsAlgorithm(o, REQUEST_OBJECT_SIGNING_ALG));
c.setUserInfoSignedResponseAlg(getAsJwsAlgorithm(o, USERINFO_SIGNED_RESPONSE_ALG));
c.setUserInfoEncryptedResponseAlg(getAsJweAlgorithm(o, USERINFO_ENCRYPTED_RESPONSE_ALG));
c.setUserInfoEncryptedResponseEnc(getAsJweEncryptionMethod(o, USERINFO_ENCRYPTED_RESPONSE_ENC));
c.setIdTokenSignedResponseAlg(getAsJwsAlgorithm(o, ID_TOKEN_SIGNED_RESPONSE_ALG));
c.setIdTokenEncryptedResponseAlg(getAsJweAlgorithm(o, ID_TOKEN_ENCRYPTED_RESPONSE_ALG));
c.setIdTokenEncryptedResponseEnc(getAsJweEncryptionMethod(o, ID_TOKEN_ENCRYPTED_RESPONSE_ENC));
c.setTokenEndpointAuthSigningAlg(getAsJwsAlgorithm(o, TOKEN_ENDPOINT_AUTH_SIGNING_ALG));
if (o.has(DEFAULT_MAX_AGE)) {
if (o.get(DEFAULT_MAX_AGE).isJsonPrimitive()) {
c.setDefaultMaxAge(o.get(DEFAULT_MAX_AGE).getAsInt());
}
}
if (o.has(REQUIRE_AUTH_TIME)) {
if (o.get(REQUIRE_AUTH_TIME).isJsonPrimitive()) {
c.setRequireAuthTime(o.get(REQUIRE_AUTH_TIME).getAsBoolean());
}
}
c.setDefaultACRvalues(getAsStringSet(o, DEFAULT_ACR_VALUES));
c.setInitiateLoginUri(getAsString(o, INITIATE_LOGIN_URI));
c.setPostLogoutRedirectUris(getAsStringSet(o, POST_LOGOUT_REDIRECT_URIS));
c.setRequestUris(getAsStringSet(o, REQUEST_URIS));
c.setClaimsRedirectUris(getAsStringSet(o, CLAIMS_REDIRECT_URIS));
c.setCodeChallengeMethod(getAsPkceAlgorithm(o, CODE_CHALLENGE_METHOD));
c.setSoftwareId(getAsString(o, SOFTWARE_ID));
c.setSoftwareVersion(getAsString(o, SOFTWARE_VERSION));
// note that this does not process or validate the software statement, that's handled in other components
String softwareStatement = getAsString(o, SOFTWARE_STATEMENT);
if (!Strings.isNullOrEmpty(softwareStatement)) {
try {
JWT softwareStatementJwt = JWTParser.parse(softwareStatement);
c.setSoftwareStatement(softwareStatementJwt);
} catch (ParseException e) {
logger.warn("Error parsing software statement", e);
return null;
}
}
return c;
} else {
return null;
}
}
/**
* Parse the JSON as a RegisteredClient (useful in the dynamic client filter)
*/
public static RegisteredClient parseRegistered(String jsonString) {
JsonElement jsonEl = parser.parse(jsonString);
return parseRegistered(jsonEl);
}
public static RegisteredClient parseRegistered(JsonElement jsonEl) {
if (jsonEl.isJsonObject()) {
JsonObject o = jsonEl.getAsJsonObject();
ClientDetailsEntity c = parse(jsonEl);
RegisteredClient rc = new RegisteredClient(c);
// get any fields from the registration
rc.setRegistrationAccessToken(getAsString(o, REGISTRATION_ACCESS_TOKEN));
rc.setRegistrationClientUri(getAsString(o, REGISTRATION_CLIENT_URI));
rc.setClientIdIssuedAt(getAsDate(o, CLIENT_ID_ISSUED_AT));
rc.setClientSecretExpiresAt(getAsDate(o, CLIENT_SECRET_EXPIRES_AT));
rc.setSource(o);
return rc;
} else {
return null;
}
}
/**
* @param c
* @param token
* @param registrationUri
* @return
*/
public static JsonObject serialize(RegisteredClient c) {
if (c.getSource() != null) {
// if we have the original object, just use that
return c.getSource();
} else {
JsonObject o = new JsonObject();
o.addProperty(CLIENT_ID, c.getClientId());
if (c.getClientSecret() != null) {
o.addProperty(CLIENT_SECRET, c.getClientSecret());
if (c.getClientSecretExpiresAt() == null) {
o.addProperty(CLIENT_SECRET_EXPIRES_AT, 0); // TODO: do we want to let secrets expire?
} else {
o.addProperty(CLIENT_SECRET_EXPIRES_AT, c.getClientSecretExpiresAt().getTime() / 1000L);
}
}
if (c.getClientIdIssuedAt() != null) {
o.addProperty(CLIENT_ID_ISSUED_AT, c.getClientIdIssuedAt().getTime() / 1000L);
} else if (c.getCreatedAt() != null) {
o.addProperty(CLIENT_ID_ISSUED_AT, c.getCreatedAt().getTime() / 1000L);
}
if (c.getRegistrationAccessToken() != null) {
o.addProperty(REGISTRATION_ACCESS_TOKEN, c.getRegistrationAccessToken());
}
if (c.getRegistrationClientUri() != null) {
o.addProperty(REGISTRATION_CLIENT_URI, c.getRegistrationClientUri());
}
// add in all other client properties
// OAuth DynReg
o.add(REDIRECT_URIS, getAsArray(c.getRedirectUris()));
o.addProperty(CLIENT_NAME, c.getClientName());
o.addProperty(CLIENT_URI, c.getClientUri());
o.addProperty(LOGO_URI, c.getLogoUri());
o.add(CONTACTS, getAsArray(c.getContacts()));
o.addProperty(TOS_URI, c.getTosUri());
o.addProperty(TOKEN_ENDPOINT_AUTH_METHOD, c.getTokenEndpointAuthMethod() != null ? c.getTokenEndpointAuthMethod().getValue() : null);
o.addProperty(SCOPE, c.getScope() != null ? Joiner.on(SCOPE_SEPARATOR).join(c.getScope()) : null);
o.add(GRANT_TYPES, getAsArray(c.getGrantTypes()));
o.add(RESPONSE_TYPES, getAsArray(c.getResponseTypes()));
o.addProperty(POLICY_URI, c.getPolicyUri());
o.addProperty(JWKS_URI, c.getJwksUri());
// get the JWKS sub-object
if (c.getJwks() != null) {
// We have to re-parse it into GSON because Nimbus uses a different parser
JsonElement jwks = parser.parse(c.getJwks().toString());
o.add(JWKS, jwks);
} else {
o.add(JWKS, null);
}
// OIDC Registration
o.addProperty(APPLICATION_TYPE, c.getApplicationType() != null ? c.getApplicationType().getValue() : null);
o.addProperty(SECTOR_IDENTIFIER_URI, c.getSectorIdentifierUri());
o.addProperty(SUBJECT_TYPE, c.getSubjectType() != null ? c.getSubjectType().getValue() : null);
o.addProperty(REQUEST_OBJECT_SIGNING_ALG, c.getRequestObjectSigningAlg() != null ? c.getRequestObjectSigningAlg().getName() : null);
o.addProperty(USERINFO_SIGNED_RESPONSE_ALG, c.getUserInfoSignedResponseAlg() != null ? c.getUserInfoSignedResponseAlg().getName() : null);
o.addProperty(USERINFO_ENCRYPTED_RESPONSE_ALG, c.getUserInfoEncryptedResponseAlg() != null ? c.getUserInfoEncryptedResponseAlg().getName() : null);
o.addProperty(USERINFO_ENCRYPTED_RESPONSE_ENC, c.getUserInfoEncryptedResponseEnc() != null ? c.getUserInfoEncryptedResponseEnc().getName() : null);
o.addProperty(ID_TOKEN_SIGNED_RESPONSE_ALG, c.getIdTokenSignedResponseAlg() != null ? c.getIdTokenSignedResponseAlg().getName() : null);
o.addProperty(ID_TOKEN_ENCRYPTED_RESPONSE_ALG, c.getIdTokenEncryptedResponseAlg() != null ? c.getIdTokenEncryptedResponseAlg().getName() : null);
o.addProperty(ID_TOKEN_ENCRYPTED_RESPONSE_ENC, c.getIdTokenEncryptedResponseEnc() != null ? c.getIdTokenEncryptedResponseEnc().getName() : null);
o.addProperty(TOKEN_ENDPOINT_AUTH_SIGNING_ALG, c.getTokenEndpointAuthSigningAlg() != null ? c.getTokenEndpointAuthSigningAlg().getName() : null);
o.addProperty(DEFAULT_MAX_AGE, c.getDefaultMaxAge());
o.addProperty(REQUIRE_AUTH_TIME, c.getRequireAuthTime());
o.add(DEFAULT_ACR_VALUES, getAsArray(c.getDefaultACRvalues()));
o.addProperty(INITIATE_LOGIN_URI, c.getInitiateLoginUri());
o.add(POST_LOGOUT_REDIRECT_URIS, getAsArray(c.getPostLogoutRedirectUris()));
o.add(REQUEST_URIS, getAsArray(c.getRequestUris()));
o.add(CLAIMS_REDIRECT_URIS, getAsArray(c.getClaimsRedirectUris()));
o.addProperty(CODE_CHALLENGE_METHOD, c.getCodeChallengeMethod() != null ? c.getCodeChallengeMethod().getName() : null);
o.addProperty(SOFTWARE_ID, c.getSoftwareId());
o.addProperty(SOFTWARE_VERSION, c.getSoftwareVersion());
if (c.getSoftwareStatement() != null) {
o.addProperty(SOFTWARE_STATEMENT, c.getSoftwareStatement().serialize());
}
return o;
}
}
}
|
package org.sunbird.scoringengine.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.sunbird.scoringengine.schema.model.ScoringSchema;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.InputStream;
@Component
public class ScoringSchemaLoader {
private ScoringSchema scoringSchema;
@PostConstruct
public void load() throws Exception {
ClassPathResource classPathResource = new ClassPathResource("ScoringSchema.json");
InputStream inputStream = classPathResource.getInputStream();
File tempFile = File.createTempFile("ScoringSchema", ".json");
try {
FileUtils.copyInputStreamToFile(inputStream, tempFile);
ObjectMapper objectMapper = new ObjectMapper();
this.scoringSchema = objectMapper.readValue(tempFile, ScoringSchema.class);
} finally {
IOUtils.closeQuietly(inputStream);
}
}
public ScoringSchema getScoringSchema() {
return scoringSchema;
}
}
|
package com.osiris.launchpad;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Context;
import android.graphics.Rect;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;
public class AppWidgetResizeFrame extends FrameLayout {
private LauncherAppWidgetHostView mWidgetView;
private CellLayout mCellLayout;
private DragLayer mDragLayer;
private Workspace mWorkspace;
private ImageView mLeftHandle;
private ImageView mRightHandle;
private ImageView mTopHandle;
private ImageView mBottomHandle;
private boolean mLeftBorderActive;
private boolean mRightBorderActive;
private boolean mTopBorderActive;
private boolean mBottomBorderActive;
private int mWidgetPaddingLeft;
private int mWidgetPaddingRight;
private int mWidgetPaddingTop;
private int mWidgetPaddingBottom;
private int mBaselineWidth;
private int mBaselineHeight;
private int mBaselineX;
private int mBaselineY;
private int mResizeMode;
private int mRunningHInc;
private int mRunningVInc;
private int mMinHSpan;
private int mMinVSpan;
private int mDeltaX;
private int mDeltaY;
private int mDeltaXAddOn;
private int mDeltaYAddOn;
private int mBackgroundPadding;
private int mTouchTargetWidth;
private int mTopTouchRegionAdjustment = 0;
private int mBottomTouchRegionAdjustment = 0;
int[] mDirectionVector = new int[2];
int[] mLastDirectionVector = new int[2];
final int SNAP_DURATION = 150;
final int BACKGROUND_PADDING = 24;
final float DIMMED_HANDLE_ALPHA = 0f;
final float RESIZE_THRESHOLD = 0.66f;
private static Rect mTmpRect = new Rect();
public static final int LEFT = 0;
public static final int TOP = 1;
public static final int RIGHT = 2;
public static final int BOTTOM = 3;
private Launcher mLauncher;
public AppWidgetResizeFrame(Context context,
LauncherAppWidgetHostView widgetView, CellLayout cellLayout, DragLayer dragLayer) {
super(context);
mLauncher = (Launcher) context;
mCellLayout = cellLayout;
mWidgetView = widgetView;
mResizeMode = widgetView.getAppWidgetInfo().resizeMode;
mDragLayer = dragLayer;
mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
final AppWidgetProviderInfo info = widgetView.getAppWidgetInfo();
int[] result = Launcher.getMinSpanForWidget(mLauncher, info);
mMinHSpan = result[0];
mMinVSpan = result[1];
setBackgroundResource(R.drawable.widget_resize_frame_holo);
setPadding(0, 0, 0, 0);
LayoutParams lp;
mLeftHandle = new ImageView(context);
mLeftHandle.setImageResource(R.drawable.widget_resize_handle_left);
lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
Gravity.LEFT | Gravity.CENTER_VERTICAL);
addView(mLeftHandle, lp);
mRightHandle = new ImageView(context);
mRightHandle.setImageResource(R.drawable.widget_resize_handle_right);
lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
Gravity.RIGHT | Gravity.CENTER_VERTICAL);
addView(mRightHandle, lp);
mTopHandle = new ImageView(context);
mTopHandle.setImageResource(R.drawable.widget_resize_handle_top);
lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
Gravity.CENTER_HORIZONTAL | Gravity.TOP);
addView(mTopHandle, lp);
mBottomHandle = new ImageView(context);
mBottomHandle.setImageResource(R.drawable.widget_resize_handle_bottom);
lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
addView(mBottomHandle, lp);
Rect p = AppWidgetHostView.getDefaultPaddingForWidget(context,
widgetView.getAppWidgetInfo().provider, null);
mWidgetPaddingLeft = p.left;
mWidgetPaddingTop = p.top;
mWidgetPaddingRight = p.right;
mWidgetPaddingBottom = p.bottom;
if (mResizeMode == AppWidgetProviderInfo.RESIZE_HORIZONTAL) {
mTopHandle.setVisibility(GONE);
mBottomHandle.setVisibility(GONE);
} else if (mResizeMode == AppWidgetProviderInfo.RESIZE_VERTICAL) {
mLeftHandle.setVisibility(GONE);
mRightHandle.setVisibility(GONE);
}
final float density = mLauncher.getResources().getDisplayMetrics().density;
mBackgroundPadding = (int) Math.ceil(density * BACKGROUND_PADDING);
mTouchTargetWidth = 2 * mBackgroundPadding;
// When we create the resize frame, we first mark all cells as unoccupied. The appropriate
// cells (same if not resized, or different) will be marked as occupied when the resize
// frame is dismissed.
mCellLayout.markCellsAsUnoccupiedForView(mWidgetView);
}
public boolean beginResizeIfPointInRegion(int x, int y) {
boolean horizontalActive = (mResizeMode & AppWidgetProviderInfo.RESIZE_HORIZONTAL) != 0;
boolean verticalActive = (mResizeMode & AppWidgetProviderInfo.RESIZE_VERTICAL) != 0;
mLeftBorderActive = (x < mTouchTargetWidth) && horizontalActive;
mRightBorderActive = (x > getWidth() - mTouchTargetWidth) && horizontalActive;
mTopBorderActive = (y < mTouchTargetWidth + mTopTouchRegionAdjustment) && verticalActive;
mBottomBorderActive = (y > getHeight() - mTouchTargetWidth + mBottomTouchRegionAdjustment)
&& verticalActive;
boolean anyBordersActive = mLeftBorderActive || mRightBorderActive
|| mTopBorderActive || mBottomBorderActive;
mBaselineWidth = getMeasuredWidth();
mBaselineHeight = getMeasuredHeight();
mBaselineX = getLeft();
mBaselineY = getTop();
if (anyBordersActive) {
mLeftHandle.setAlpha(mLeftBorderActive ? 1.0f : DIMMED_HANDLE_ALPHA);
mRightHandle.setAlpha(mRightBorderActive ? 1.0f :DIMMED_HANDLE_ALPHA);
mTopHandle.setAlpha(mTopBorderActive ? 1.0f : DIMMED_HANDLE_ALPHA);
mBottomHandle.setAlpha(mBottomBorderActive ? 1.0f : DIMMED_HANDLE_ALPHA);
}
return anyBordersActive;
}
/**
* Here we bound the deltas such that the frame cannot be stretched beyond the extents
* of the CellLayout, and such that the frame's borders can't cross.
*/
public void updateDeltas(int deltaX, int deltaY) {
if (mLeftBorderActive) {
mDeltaX = Math.max(-mBaselineX, deltaX);
mDeltaX = Math.min(mBaselineWidth - 2 * mTouchTargetWidth, mDeltaX);
} else if (mRightBorderActive) {
mDeltaX = Math.min(mDragLayer.getWidth() - (mBaselineX + mBaselineWidth), deltaX);
mDeltaX = Math.max(-mBaselineWidth + 2 * mTouchTargetWidth, mDeltaX);
}
if (mTopBorderActive) {
mDeltaY = Math.max(-mBaselineY, deltaY);
mDeltaY = Math.min(mBaselineHeight - 2 * mTouchTargetWidth, mDeltaY);
} else if (mBottomBorderActive) {
mDeltaY = Math.min(mDragLayer.getHeight() - (mBaselineY + mBaselineHeight), deltaY);
mDeltaY = Math.max(-mBaselineHeight + 2 * mTouchTargetWidth, mDeltaY);
}
}
public void visualizeResizeForDelta(int deltaX, int deltaY) {
visualizeResizeForDelta(deltaX, deltaY, false);
}
/**
* Based on the deltas, we resize the frame, and, if needed, we resize the widget.
*/
private void visualizeResizeForDelta(int deltaX, int deltaY, boolean onDismiss) {
updateDeltas(deltaX, deltaY);
DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
if (mLeftBorderActive) {
lp.x = mBaselineX + mDeltaX;
lp.width = mBaselineWidth - mDeltaX;
} else if (mRightBorderActive) {
lp.width = mBaselineWidth + mDeltaX;
}
if (mTopBorderActive) {
lp.y = mBaselineY + mDeltaY;
lp.height = mBaselineHeight - mDeltaY;
} else if (mBottomBorderActive) {
lp.height = mBaselineHeight + mDeltaY;
}
resizeWidgetIfNeeded(onDismiss);
requestLayout();
}
/**
* Based on the current deltas, we determine if and how to resize the widget.
*/
private void resizeWidgetIfNeeded(boolean onDismiss) {
int xThreshold = mCellLayout.getCellWidth() + mCellLayout.getWidthGap();
int yThreshold = mCellLayout.getCellHeight() + mCellLayout.getHeightGap();
int deltaX = mDeltaX + mDeltaXAddOn;
int deltaY = mDeltaY + mDeltaYAddOn;
float hSpanIncF = 1.0f * deltaX / xThreshold - mRunningHInc;
float vSpanIncF = 1.0f * deltaY / yThreshold - mRunningVInc;
int hSpanInc = 0;
int vSpanInc = 0;
int cellXInc = 0;
int cellYInc = 0;
int countX = mCellLayout.getCountX();
int countY = mCellLayout.getCountY();
if (Math.abs(hSpanIncF) > RESIZE_THRESHOLD) {
hSpanInc = Math.round(hSpanIncF);
}
if (Math.abs(vSpanIncF) > RESIZE_THRESHOLD) {
vSpanInc = Math.round(vSpanIncF);
}
if (!onDismiss && (hSpanInc == 0 && vSpanInc == 0)) return;
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) mWidgetView.getLayoutParams();
int spanX = lp.cellHSpan;
int spanY = lp.cellVSpan;
int cellX = lp.useTmpCoords ? lp.tmpCellX : lp.cellX;
int cellY = lp.useTmpCoords ? lp.tmpCellY : lp.cellY;
int hSpanDelta = 0;
int vSpanDelta = 0;
// For each border, we bound the resizing based on the minimum width, and the maximum
// expandability.
if (mLeftBorderActive) {
cellXInc = Math.max(-cellX, hSpanInc);
cellXInc = Math.min(lp.cellHSpan - mMinHSpan, cellXInc);
hSpanInc *= -1;
hSpanInc = Math.min(cellX, hSpanInc);
hSpanInc = Math.max(-(lp.cellHSpan - mMinHSpan), hSpanInc);
hSpanDelta = -hSpanInc;
} else if (mRightBorderActive) {
hSpanInc = Math.min(countX - (cellX + spanX), hSpanInc);
hSpanInc = Math.max(-(lp.cellHSpan - mMinHSpan), hSpanInc);
hSpanDelta = hSpanInc;
}
if (mTopBorderActive) {
cellYInc = Math.max(-cellY, vSpanInc);
cellYInc = Math.min(lp.cellVSpan - mMinVSpan, cellYInc);
vSpanInc *= -1;
vSpanInc = Math.min(cellY, vSpanInc);
vSpanInc = Math.max(-(lp.cellVSpan - mMinVSpan), vSpanInc);
vSpanDelta = -vSpanInc;
} else if (mBottomBorderActive) {
vSpanInc = Math.min(countY - (cellY + spanY), vSpanInc);
vSpanInc = Math.max(-(lp.cellVSpan - mMinVSpan), vSpanInc);
vSpanDelta = vSpanInc;
}
mDirectionVector[0] = 0;
mDirectionVector[1] = 0;
// Update the widget's dimensions and position according to the deltas computed above
if (mLeftBorderActive || mRightBorderActive) {
spanX += hSpanInc;
cellX += cellXInc;
if (hSpanDelta != 0) {
mDirectionVector[0] = mLeftBorderActive ? -1 : 1;
}
}
if (mTopBorderActive || mBottomBorderActive) {
spanY += vSpanInc;
cellY += cellYInc;
if (vSpanDelta != 0) {
mDirectionVector[1] = mTopBorderActive ? -1 : 1;
}
}
if (!onDismiss && vSpanDelta == 0 && hSpanDelta == 0) return;
// We always want the final commit to match the feedback, so we make sure to use the
// last used direction vector when committing the resize / reorder.
if (onDismiss) {
mDirectionVector[0] = mLastDirectionVector[0];
mDirectionVector[1] = mLastDirectionVector[1];
} else {
mLastDirectionVector[0] = mDirectionVector[0];
mLastDirectionVector[1] = mDirectionVector[1];
}
if (mCellLayout.createAreaForResize(cellX, cellY, spanX, spanY, mWidgetView,
mDirectionVector, onDismiss)) {
lp.tmpCellX = cellX;
lp.tmpCellY = cellY;
lp.cellHSpan = spanX;
lp.cellVSpan = spanY;
mRunningVInc += vSpanDelta;
mRunningHInc += hSpanDelta;
if (!onDismiss) {
updateWidgetSizeRanges(mWidgetView, mLauncher, spanX, spanY);
}
}
mWidgetView.requestLayout();
}
static void updateWidgetSizeRanges(AppWidgetHostView widgetView, Launcher launcher,
int spanX, int spanY) {
getWidgetSizeRanges(launcher, spanX, spanY, mTmpRect);
widgetView.updateAppWidgetSize(null, mTmpRect.left, mTmpRect.top,
mTmpRect.right, mTmpRect.bottom);
}
static Rect getWidgetSizeRanges(Launcher launcher, int spanX, int spanY, Rect rect) {
if (rect == null) {
rect = new Rect();
}
Rect landMetrics = Workspace.getCellLayoutMetrics(launcher, CellLayout.LANDSCAPE);
Rect portMetrics = Workspace.getCellLayoutMetrics(launcher, CellLayout.PORTRAIT);
final float density = launcher.getResources().getDisplayMetrics().density;
// Compute landscape size
int cellWidth = landMetrics.left;
int cellHeight = landMetrics.top;
int widthGap = landMetrics.right;
int heightGap = landMetrics.bottom;
int landWidth = (int) ((spanX * cellWidth + (spanX - 1) * widthGap) / density);
int landHeight = (int) ((spanY * cellHeight + (spanY - 1) * heightGap) / density);
// Compute portrait size
cellWidth = portMetrics.left;
cellHeight = portMetrics.top;
widthGap = portMetrics.right;
heightGap = portMetrics.bottom;
int portWidth = (int) ((spanX * cellWidth + (spanX - 1) * widthGap) / density);
int portHeight = (int) ((spanY * cellHeight + (spanY - 1) * heightGap) / density);
rect.set(portWidth, landHeight, landWidth, portHeight);
return rect;
}
/**
* This is the final step of the resize. Here we save the new widget size and position
* to LauncherModel and animate the resize frame.
*/
public void commitResize() {
resizeWidgetIfNeeded(true);
requestLayout();
}
public void onTouchUp() {
int xThreshold = mCellLayout.getCellWidth() + mCellLayout.getWidthGap();
int yThreshold = mCellLayout.getCellHeight() + mCellLayout.getHeightGap();
mDeltaXAddOn = mRunningHInc * xThreshold;
mDeltaYAddOn = mRunningVInc * yThreshold;
mDeltaX = 0;
mDeltaY = 0;
post(new Runnable() {
@Override
public void run() {
snapToWidget(true);
}
});
}
public void snapToWidget(boolean animate) {
final DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
int xOffset = mCellLayout.getLeft() + mCellLayout.getPaddingLeft() - mWorkspace.getScrollX();
int yOffset = mCellLayout.getTop() + mCellLayout.getPaddingTop() - mWorkspace.getScrollY();
int newWidth = mWidgetView.getWidth() + 2 * mBackgroundPadding - mWidgetPaddingLeft -
mWidgetPaddingRight;
int newHeight = mWidgetView.getHeight() + 2 * mBackgroundPadding - mWidgetPaddingTop -
mWidgetPaddingBottom;
int newX = mWidgetView.getLeft() - mBackgroundPadding + xOffset + mWidgetPaddingLeft;
int newY = mWidgetView.getTop() - mBackgroundPadding + yOffset + mWidgetPaddingTop;
// We need to make sure the frame's touchable regions lie fully within the bounds of the
// DragLayer. We allow the actual handles to be clipped, but we shift the touch regions
// down accordingly to provide a proper touch target.
if (newY < 0) {
// In this case we shift the touch region down to start at the top of the DragLayer
mTopTouchRegionAdjustment = -newY;
} else {
mTopTouchRegionAdjustment = 0;
}
if (newY + newHeight > mDragLayer.getHeight()) {
// In this case we shift the touch region up to end at the bottom of the DragLayer
mBottomTouchRegionAdjustment = -(newY + newHeight - mDragLayer.getHeight());
} else {
mBottomTouchRegionAdjustment = 0;
}
if (!animate) {
lp.width = newWidth;
lp.height = newHeight;
lp.x = newX;
lp.y = newY;
mLeftHandle.setAlpha(1.0f);
mRightHandle.setAlpha(1.0f);
mTopHandle.setAlpha(1.0f);
mBottomHandle.setAlpha(1.0f);
requestLayout();
} else {
PropertyValuesHolder width = PropertyValuesHolder.ofInt("width", lp.width, newWidth);
PropertyValuesHolder height = PropertyValuesHolder.ofInt("height", lp.height,
newHeight);
PropertyValuesHolder x = PropertyValuesHolder.ofInt("x", lp.x, newX);
PropertyValuesHolder y = PropertyValuesHolder.ofInt("y", lp.y, newY);
ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(lp, width, height, x, y);
ObjectAnimator leftOa = LauncherAnimUtils.ofFloat(mLeftHandle, "alpha", 1.0f);
ObjectAnimator rightOa = LauncherAnimUtils.ofFloat(mRightHandle, "alpha", 1.0f);
ObjectAnimator topOa = LauncherAnimUtils.ofFloat(mTopHandle, "alpha", 1.0f);
ObjectAnimator bottomOa = LauncherAnimUtils.ofFloat(mBottomHandle, "alpha", 1.0f);
oa.addUpdateListener(new AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
requestLayout();
}
});
AnimatorSet set = LauncherAnimUtils.createAnimatorSet();
if (mResizeMode == AppWidgetProviderInfo.RESIZE_VERTICAL) {
set.playTogether(oa, topOa, bottomOa);
} else if (mResizeMode == AppWidgetProviderInfo.RESIZE_HORIZONTAL) {
set.playTogether(oa, leftOa, rightOa);
} else {
set.playTogether(oa, leftOa, rightOa, topOa, bottomOa);
}
set.setDuration(SNAP_DURATION);
set.start();
}
}
}
|
// Copyright (c) Corporation for National Research Initiatives
package org.python.core;
public class ReflectedArgs {
public Class<?>[] args;
public Object data;
public Class<?> declaringClass;
public boolean isStatic;
public boolean isVarArgs;
public int flags;
public static final int StandardCall = 0;
public static final int PyArgsCall = 1;
public static final int PyArgsKeywordsCall = 2;
public ReflectedArgs(Object data, Class<?>[] args, Class<?> declaringClass, boolean isStatic) {
this(data, args, declaringClass, isStatic, false);
}
public ReflectedArgs(Object data, Class<?>[] args, Class<?> declaringClass, boolean isStatic, boolean isVarArgs) {
this.data = data;
this.args = args;
this.declaringClass = declaringClass;
this.isStatic = isStatic;
this.isVarArgs = isVarArgs; // only used for varargs matching; it should be added after the unboxed form
if (args.length == 1 && args[0] == PyObject[].class) {
this.flags = PyArgsCall;
} else if (args.length == 2 && args[0] == PyObject[].class
&& args[1] == String[].class) {
this.flags = PyArgsKeywordsCall;
} else {
this.flags = StandardCall;
}
}
public boolean matches(PyObject self, PyObject[] pyArgs, String[] keywords,
ReflectedCallData callData) {
if (this.flags != PyArgsKeywordsCall) {
if (keywords != null && keywords.length != 0) {
return false;
}
}
// if (isStatic ? self != null : self == null) return Py.NoConversion;
/* Ugly code to handle mismatch in static vs. instance functions... */
/*
* Will be very inefficient in cases where static and instance functions
* both exist with same names and number of args
*/
if (this.isStatic) {
if (self != null) {
self = null;
}
} else {
if (self == null) {
if (pyArgs.length == 0) {
return false;
}
self = pyArgs[0];
PyObject[] newArgs = new PyObject[pyArgs.length - 1];
System.arraycopy(pyArgs, 1, newArgs, 0, newArgs.length);
pyArgs = newArgs;
}
}
if (this.flags == PyArgsKeywordsCall) { // foo(PyObject[], String[])
callData.setLength(2);
callData.args[0] = pyArgs;
callData.args[1] = keywords;
callData.self = self;
if (self != null) {
Object tmp = self.__tojava__(this.declaringClass);
if (tmp != Py.NoConversion) {
callData.self = tmp;
}
}
return true;
} else if (this.flags == PyArgsCall) { // foo(PyObject[])
callData.setLength(1);
callData.args[0] = pyArgs;
callData.self = self;
if (self != null) {
Object tmp = self.__tojava__(this.declaringClass);
if (tmp != Py.NoConversion) {
callData.self = tmp;
}
}
return true;
}
int n = this.args.length;
// if we have a varargs method AND the last PyObject is not a list/tuple
// we need to do box (wrap with an array) the last pyArgs.length - n args
// (which might be empty)
//
// examples:
// test(String... x)
// test(List... x)
//
// in this last example, don't worry if someone is overly clever in calling this,
// they can always write their own version of PyReflectedFunction and put it in the proxy
// if that's what they need to do ;)
if (isVarArgs) {
if (pyArgs.length == 0 || !(pyArgs[pyArgs.length - 1] instanceof PySequenceList)) {
int non_varargs_len = n - 1;
if (pyArgs.length >= non_varargs_len) {
PyObject[] boxedPyArgs = new PyObject[n];
for (int i = 0; i < non_varargs_len; i++) {
boxedPyArgs[i] = pyArgs[i];
}
int varargs_len = pyArgs.length - non_varargs_len;
PyObject[] varargs = new PyObject[varargs_len];
for (int i = 0; i < varargs_len; i++) {
varargs[i] = pyArgs[non_varargs_len + i];
}
boxedPyArgs[non_varargs_len] = new PyList(varargs);
pyArgs = boxedPyArgs;
}
}
}
if (pyArgs.length != n) {
return false;
}
// Make error messages clearer
callData.errArg = ReflectedCallData.UNABLE_TO_CONVERT_SELF;
if (self != null) {
Object tmp = self.__tojava__(this.declaringClass);
if (tmp == Py.NoConversion) {
return false;
}
callData.self = tmp;
} else {
callData.self = null;
}
callData.setLength(n);
Object[] javaArgs = callData.args;
for (int i = 0; i < n; i++) {
PyObject pyArg = pyArgs[i];
Class targetClass = this.args[i];
Object javaArg = pyArg.__tojava__(targetClass);
javaArgs[i] = javaArg;
if (javaArg == Py.NoConversion) {
if (i > callData.errArg) {
callData.errArg = i;
}
return false;
}
}
return true;
}
public static int precedence(Class<?> arg) {
if (arg == Object.class) {
return 3000;
}
if (arg.isPrimitive()) {
if (arg == Long.TYPE) {
return 10;
}
if (arg == Integer.TYPE) {
return 11;
}
if (arg == Short.TYPE) {
return 12;
}
if (arg == Character.TYPE) {
return 13;
}
if (arg == Byte.TYPE) {
return 14;
}
if (arg == Double.TYPE) {
return 20;
}
if (arg == Float.TYPE) {
return 21;
}
if (arg == Boolean.TYPE) {
return 30;
}
}
// Consider Strings a primitive type
// This makes them higher priority than byte[]
if (arg == String.class) {
return 40;
}
if (arg.isArray()) {
Class<?> componentType = arg.getComponentType();
if (componentType == Object.class) {
return 2500;
}
return 100 + precedence(componentType);
}
return 2000;
}
/*
* Returns 0 iff arg1 == arg2 Returns +/-1 iff arg1 and arg2 are
* unimportantly different Returns +/-2 iff arg1 and arg2 are significantly
* different
*/
public static int compare(Class<?> arg1, Class<?> arg2) {
int p1 = precedence(arg1);
int p2 = precedence(arg2);
// Special code if they are both nonprimitives
// Superclasses/superinterfaces are considered greater than sub's
if (p1 >= 2000 && p2 >= 2000) {
if (arg1.isAssignableFrom(arg2)) {
if (arg2.isAssignableFrom(arg1)) {
return 0;
} else {
return +2;
}
} else {
if (arg2.isAssignableFrom(arg1)) {
return -2;
} else {
int cmp = arg1.getName().compareTo(arg2.getName());
return cmp > 0 ? +1 : -1;
}
}
}
return p1 > p2 ? +2 : (p1 == p2 ? 0 : -2);
}
public static final int REPLACE = 1998;
public int compareTo(ReflectedArgs other) {
Class<?>[] oargs = other.args;
// First decision based on flags
if (other.flags != this.flags) {
return other.flags < this.flags ? -1 : +1;
}
// Decision based on number of args
int n = this.args.length;
if (n < oargs.length) {
return -1;
}
if (n > oargs.length) {
return +1;
}
// Decide based on static/non-static
if (this.isStatic && !other.isStatic) {
return +1;
}
if (!this.isStatic && other.isStatic) {
return -1;
}
// Compare the arg lists
int cmp = 0;
for (int i = 0; i < n; i++) {
int tmp = compare(this.args[i], oargs[i]);
if (tmp == +2 || tmp == -2) {
cmp = tmp;
}
if (cmp == 0) {
cmp = tmp;
}
}
if (cmp != 0) {
return cmp > 0 ? +1 : -1;
}
// If arg lists are equivalent, look at declaring classes
boolean replace = other.declaringClass.isAssignableFrom(this.declaringClass);
// For static methods, use the child's version
// For instance methods, use the parent's version
if (!this.isStatic) {
replace = !replace;
}
return replace ? REPLACE : 0;
}
@Override
public String toString() {
String s = declaringClass + ", static=" + isStatic + ", varargs=" + isVarArgs + ",flags=" + flags + ", " + data + "\n";
s = s + "\t(";
for (Class<?> arg : args) {
s += arg.getName() + ", ";
}
s += ")";
return s;
}
}
|
/*
* 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 com.dtstack.dtcenter.loader.client.sql;
import com.dtstack.dtcenter.loader.cache.pool.config.PoolConfig;
import com.dtstack.dtcenter.loader.client.BaseTest;
import com.dtstack.dtcenter.loader.client.ClientCache;
import com.dtstack.dtcenter.loader.client.IClient;
import com.dtstack.dtcenter.loader.dto.ColumnMetaDTO;
import com.dtstack.dtcenter.loader.dto.SqlQueryDTO;
import com.dtstack.dtcenter.loader.dto.source.OdpsSourceDTO;
import com.dtstack.dtcenter.loader.exception.DtLoaderException;
import com.dtstack.dtcenter.loader.source.DataSourceType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @company: www.dtstack.com
* @Author :loader_test
* @Date :Created in 09:52 2020/4/24
* @Description:MaxComputer 测试
*/
public class MaxComputerTest extends BaseTest {
// 构建client
private static final IClient client = ClientCache.getClient(DataSourceType.MAXCOMPUTE.getVal());
// 构建数据源信息 ps:em没有对应的数据源类型
private static final OdpsSourceDTO source = OdpsSourceDTO.builder()
.config("{\"accessId\":\"LTAIljBeC8ei9Yy0\",\"accessKey\":\"gwTWasH7sEE0pSUEuiXnw7JecXyfGF\"," +
"\"project\":\"dtstack_dev\",\"endPoint\":\"https://service.odps.aliyun.com/api\"}")
.poolConfig(new PoolConfig())
.build();
/**
* 数据准备
*/
@BeforeClass
public static void beforeClass() {
SqlQueryDTO queryDTO = SqlQueryDTO.builder().sql("drop table if exists loader_test").build();
client.executeSqlWithoutResultSet(source, queryDTO);
queryDTO = SqlQueryDTO.builder().sql("create table loader_test( id STRING COMMENT '工作类型', name STRING COMMENT '婚否') COMMENT 'table comment'").build();
client.executeSqlWithoutResultSet(source, queryDTO);
queryDTO = SqlQueryDTO.builder().sql("insert into loader_test values ('1', 'loader_test')").build();
client.executeSqlWithoutResultSet(source, queryDTO);
}
/**
* 连通性测试
*/
@Test
public void testCon() {
Boolean isConnected = client.testCon(source);
if (Boolean.FALSE.equals(isConnected)) {
throw new DtLoaderException("connection exception");
}
}
/**
* 简单查询
*/
@Test
public void executeQuery() {
SqlQueryDTO queryDTO = SqlQueryDTO.builder().sql("select * from loader_test;").build();
List<Map<String, Object>> mapList = client.executeQuery(source, queryDTO);
Assert.assertTrue(CollectionUtils.isNotEmpty(mapList));
}
/**
* 无需结果查询
*/
@Test
public void executeSqlWithoutResultSet() {
SqlQueryDTO queryDTO = SqlQueryDTO.builder().sql("show tables").build();
client.executeSqlWithoutResultSet(source, queryDTO);
}
/**
* 获取表列表
*/
@Test
public void getTableList() {
SqlQueryDTO queryDTO = SqlQueryDTO.builder().build();
List<String> tableList = client.getTableList(source, queryDTO);
Assert.assertTrue(CollectionUtils.isNotEmpty(tableList));
}
/**
* 获取表字段标准 java 类型
*/
@Test
public void getColumnClassInfo() {
SqlQueryDTO queryDTO = SqlQueryDTO.builder().tableName("loader_test").build();
List<String> columnClassInfo = client.getColumnClassInfo(source, queryDTO);
Assert.assertTrue(CollectionUtils.isNotEmpty(columnClassInfo));
}
/**
* 获取表字段详细信息
*/
@Test
public void getColumnMetaData() {
SqlQueryDTO queryDTO = SqlQueryDTO.builder().tableName("loader_test").build();
List<ColumnMetaDTO> columnMetaData = client.getColumnMetaData(source, queryDTO);
Assert.assertTrue(CollectionUtils.isNotEmpty(columnMetaData));
}
/**
* 获取表注释
*/
@Test
public void getTableMetaComment() {
SqlQueryDTO queryDTO = SqlQueryDTO.builder().tableName("loader_test").build();
String metaComment = client.getTableMetaComment(source, queryDTO);
Assert.assertTrue(StringUtils.isNotBlank(metaComment));
}
/**
* 数据预览
*/
@Test
public void getPreview() {
HashMap<String, String> map = new HashMap<>();
map.put("id", "1");
List data = client.getPreview(source, SqlQueryDTO.builder().partitionColumns(map).previewNum(1000).tableName("loader_test").build());
Assert.assertTrue(CollectionUtils.isNotEmpty(data));
}
/**
* 根据sql获取字段信息
*/
@Test
public void getColumnMetaDataWithSql() {
IClient client = ClientCache.getClient(DataSourceType.MAXCOMPUTE.getVal());
SqlQueryDTO queryDTO = SqlQueryDTO.builder().sql("select * from loader_test").build();
List data = client.getColumnMetaDataWithSql(source, queryDTO);
Assert.assertTrue(CollectionUtils.isNotEmpty(data));
}
}
|
/*
* 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.karaf.instance.core.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.management.MBeanException;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import javax.management.openmbean.TabularData;
import org.apache.karaf.instance.core.Instance;
import org.apache.karaf.instance.core.InstanceSettings;
import org.apache.karaf.instance.core.InstancesMBean;
public class InstancesMBeanImpl extends StandardMBean implements InstancesMBean {
static final String DEBUG_OPTS = " -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005";
static final String DEFAULT_OPTS = "-server -Xmx512M -Dcom.sun.management.jmxremote";
private org.apache.karaf.instance.core.InstanceService instanceService;
public InstancesMBeanImpl(org.apache.karaf.instance.core.InstanceService instanceService) throws NotCompliantMBeanException {
super(InstancesMBean.class);
this.instanceService = instanceService;
}
public int createInstance(String name,
int sshPort,
int rmiRegistryPort,
int rmiServerPort,
String location,
String javaOpts,
String features,
String featuresURLs)
throws MBeanException {
return this.createInstance(name, sshPort, rmiRegistryPort, rmiServerPort, location, javaOpts, features, featuresURLs, "localhost");
}
public int createInstance(String name, int sshPort, int rmiRegistryPort, int rmiServerPort, String location, String javaOpts, String features, String featureURLs, String address)
throws MBeanException {
try {
if ("".equals(location)) {
location = null;
}
if ("".equals(javaOpts)) {
javaOpts = null;
}
InstanceSettings settings = new InstanceSettings(sshPort, rmiRegistryPort, rmiServerPort, location, javaOpts,
parseStringList(featureURLs), parseStringList(features), address);
Instance inst = instanceService.createInstance(name, settings, false);
if (inst != null) {
return inst.getPid();
} else {
return -1;
}
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void changeSshPort(String name, int port) throws MBeanException {
try {
getExistingInstance(name).changeSshPort(port);
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void changeSshHost(String name, String host) throws MBeanException {
try {
getExistingInstance(name).changeSshHost(host);
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void changeRmiRegistryPort(String name, int port) throws MBeanException {
try {
getExistingInstance(name).changeRmiRegistryPort(port);
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void changeRmiServerPort(String name, int port) throws MBeanException {
try {
getExistingInstance(name).changeRmiServerPort(port);
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void changeJavaOpts(String name, String javaOpts) throws MBeanException {
try {
getExistingInstance(name).changeJavaOpts(javaOpts);
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void destroyInstance(String name) throws MBeanException {
try {
getExistingInstance(name).destroy();
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void startInstance(String name) throws MBeanException {
try {
getExistingInstance(name).start(null);
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void startInstance(String name, String opts) throws MBeanException {
try {
getExistingInstance(name).start(opts);
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void startInstance(String name, String opts, boolean wait, boolean debug) throws MBeanException {
try {
Instance child = getExistingInstance(name);
String options = opts;
if (options == null) {
options = child.getJavaOpts();
}
if (options == null) {
options = DEFAULT_OPTS;
}
if (debug) {
options += DEBUG_OPTS;
}
if (wait) {
String state = child.getState();
if (Instance.STOPPED.equals(state)) {
child.start(opts);
}
if (!Instance.STARTED.equals(state)) {
do {
Thread.sleep(500);
state = child.getState();
} while (Instance.STARTING.equals(state));
}
} else {
child.start(opts);
}
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void stopInstance(String name) throws MBeanException {
try {
getExistingInstance(name).stop();
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void renameInstance(String originalName, String newName) throws MBeanException {
try {
instanceService.renameInstance(originalName, newName, false);
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void renameInstance(String originalName, String newName, boolean verbose) throws MBeanException {
try {
instanceService.renameInstance(originalName, newName, verbose);
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public void cloneInstance(String name, String cloneName, int sshPort, int rmiRegistryPort, int rmiServerPort, String location, String javaOpts) throws MBeanException {
try {
if ("".equals(location)) {
location = null;
}
if ("".equals(javaOpts)) {
javaOpts = null;
}
InstanceSettings settings = new InstanceSettings(sshPort, rmiRegistryPort, rmiServerPort, location, javaOpts, null, null);
instanceService.cloneInstance(name, cloneName, settings, false);
} catch (Exception e) {
throw new MBeanException(null, e.getMessage());
}
}
public TabularData getInstances() throws MBeanException {
List<Instance> instances = Arrays.asList(instanceService.getInstances());
TabularData table = InstanceToTableMapper.tableFrom(instances);
return table;
}
private Instance getExistingInstance(String name) {
Instance i = instanceService.getInstance(name);
if (i == null) {
throw new IllegalArgumentException("Instance '" + name + "' does not exist");
}
return i;
}
private List<String> parseStringList(String value) {
List<String> list = new ArrayList<String>();
if (value != null) {
for (String el : value.split(",")) {
String trimmed = el.trim();
if (trimmed.length() == 0) {
continue;
}
list.add(trimmed);
}
}
return list;
}
}
|
package edu.berkeley.kaiju.frontend.response;
public class ClientSetIsolationResponse {
}
|
/*
* Copyright 2017 jiajunhui<junhui_jia@163.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kk.taurus.playerbase.player;
import android.os.Bundle;
import android.view.Surface;
import android.view.SurfaceHolder;
import com.kk.taurus.playerbase.entity.DataSource;
import com.kk.taurus.playerbase.event.OnErrorEventListener;
import com.kk.taurus.playerbase.event.OnPlayerEventListener;
/**
* Created by Taurus on 2018/3/17.
*/
public interface IPlayer {
int STATE_END = -2;
int STATE_ERROR = -1;
int STATE_IDLE = 0;
int STATE_INITIALIZED = 1;
int STATE_PREPARED = 2;
int STATE_STARTED = 3;
int STATE_PAUSED = 4;
int STATE_STOPPED = 5;
int STATE_PLAYBACK_COMPLETE = 6;
/**
* with this method, you can send some params for player init or switch some setting.
* such as some configuration option (use mediacodec or timeout or reconnect and so on) for decoder init.
* @param code the code value custom yourself.
* @param bundle deliver some data if you need.
*/
void option(int code, Bundle bundle);
void setDataSource(DataSource dataSource);
void setDisplay(SurfaceHolder surfaceHolder);
void setSurface(Surface surface);
void setVolume(float left, float right);
void setSpeed(float speed);
void setOnPlayerEventListener(OnPlayerEventListener onPlayerEventListener);
void setOnErrorEventListener(OnErrorEventListener onErrorEventListener);
void setOnBufferingListener(OnBufferingListener onBufferingListener);
int getBufferPercentage();
boolean isPlaying();
int getCurrentPosition();
int getDuration();
int getAudioSessionId();
int getVideoWidth();
int getVideoHeight();
int getState();
void start();
void start(int msc);
void pause();
void resume();
void seekTo(int msc);
void stop();
void reset();
void destroy();
}
|
@javax.xml.bind.annotation.XmlSchema(namespace = "http://ws.taskmeter/")
package taskmeter.ws;
|
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.seata.rm.datasource.undo.oracle;
import io.seata.rm.datasource.sql.struct.Row;
import io.seata.rm.datasource.sql.struct.TableMeta;
import io.seata.rm.datasource.sql.struct.TableRecords;
import io.seata.rm.datasource.undo.BaseExecutorTest;
import io.seata.rm.datasource.undo.SQLUndoLog;
import io.seata.sqlparser.SQLType;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author jsbxyyx
*/
public class OracleUndoDeleteExecutorTest extends BaseExecutorTest {
@Test
public void buildUndoSQL() {
OracleUndoDeleteExecutor executor = upperCase();
String sql = executor.buildUndoSQL();
Assertions.assertNotNull(sql);
Assertions.assertTrue(sql.contains("INSERT"));
Assertions.assertTrue(sql.contains("ID"));
Assertions.assertTrue(sql.contains("TABLE_NAME"));
}
@Test
public void getUndoRows() {
OracleUndoDeleteExecutor executor = upperCase();
Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getBeforeImage());
}
private OracleUndoDeleteExecutor upperCase() {
TableMeta tableMeta = Mockito.mock(TableMeta.class);
Mockito.when(tableMeta.getPrimaryKeyOnlyName()).thenReturn(Arrays.asList(new String[]{"ID"}));
Mockito.when(tableMeta.getTableName()).thenReturn("TABLE_NAME");
TableRecords beforeImage = new TableRecords();
beforeImage.setTableName("TABLE_NAME");
beforeImage.setTableMeta(tableMeta);
List<Row> beforeRows = new ArrayList<>();
Row row0 = new Row();
addField(row0, "ID", 1, "1");
addField(row0, "AGE", 1, "1");
beforeRows.add(row0);
Row row1 = new Row();
addField(row1, "ID", 1, "1");
addField(row1, "AGE", 1, "1");
beforeRows.add(row1);
beforeImage.setRows(beforeRows);
TableRecords afterImage = new TableRecords();
afterImage.setTableName("TABLE_NAME");
afterImage.setTableMeta(tableMeta);
List<Row> afterRows = new ArrayList<>();
Row row2 = new Row();
addField(row2, "ID", 1, "1");
addField(row2, "AGE", 1, "2");
afterRows.add(row2);
Row row3 = new Row();
addField(row3, "ID", 1, "1");
addField(row3, "AGE", 1, "2");
afterRows.add(row3);
afterImage.setRows(afterRows);
SQLUndoLog sqlUndoLog = new SQLUndoLog();
sqlUndoLog.setSqlType(SQLType.DELETE);
sqlUndoLog.setTableMeta(tableMeta);
sqlUndoLog.setTableName("TABLE_NAME");
sqlUndoLog.setBeforeImage(beforeImage);
sqlUndoLog.setAfterImage(afterImage);
return new OracleUndoDeleteExecutor(sqlUndoLog);
}
}
|
package org.gradle.test.performance.mediummonolithicjavaproject.p424;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test8493 {
Production8493 objectUnderTest = new Production8493();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
}
|
package co.uk.niadel.napi.events.entity;
import co.uk.niadel.napi.events.IEvent;
import net.minecraft.entity.EntityBodyHelper;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.ai.EntityAITasks;
import net.minecraft.entity.ai.EntityJumpHelper;
import net.minecraft.entity.ai.EntityLookHelper;
import net.minecraft.entity.ai.EntityMoveHelper;
import net.minecraft.entity.ai.EntitySenses;
import net.minecraft.pathfinding.PathNavigate;
import net.minecraft.world.World;
/**
* This can be considered incredibly powerful, as you can manipulate AI and other things with this.
* @author Niadel
*
*/
public class EventEntityLivingInit implements IEvent
{
/**
* The entity being initialised.
*/
public EntityLiving entity;
/**
* This entity's world object.
*/
public World world;
/**
* This entity's AI tasks, used for manipulating AI.
*/
public EntityAITasks tasks, targetTasks;
/**
* This entity's look helper.
*/
public EntityLookHelper lookHelper;
/**
* This entity's move helper.
*/
public EntityMoveHelper moveHelper;
/**
* This entity's jump helper.
*/
public EntityJumpHelper jumpHelper;
/**
* This entity's body helper.
*/
public EntityBodyHelper bodyHelper;
/**
* This entity's navigator.
*/
public PathNavigate navigator;
/**
* This entity's senses.
*/
public EntitySenses senses;
public EventEntityLivingInit(EntityLiving entity, World world, EntityAITasks tasks, EntityAITasks targetTasks, EntityLookHelper lookHelper, EntityMoveHelper moveHelper, EntityJumpHelper jumpHelper, EntityBodyHelper bodyHelper, PathNavigate navigator, EntitySenses senses)
{
this.entity = entity;
this.world = world;
this.tasks = tasks;
this.targetTasks = targetTasks;
this.lookHelper = lookHelper;
this.jumpHelper = jumpHelper;
this.moveHelper = moveHelper;
this.bodyHelper = bodyHelper;
this.navigator = navigator;
this.senses = senses;
}
}
|
package ru.job4j.tracker;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
/**
* Class TrackerSQL.
*
* @author dshustrov
* @version 1
* @since 17.02.2019
*/
public class TrackerSQL implements ITracker, AutoCloseable {
private static final Logger LOG = LogManager.getLogger(TrackerSQL.class);
private ArrayList<Item> items = new ArrayList<>();
private Connection connection;
public TrackerSQL(Connection connection) {
this.connection = connection;
}
// public boolean init() {
// try (InputStream in = TrackerSQL.class.getClassLoader().getResourceAsStream("app.properties")) {
// Properties config = new Properties();
// config.load(in);
// Class.forName(config.getProperty("driver-class-name"));
// this.connection = DriverManager.getConnection(
// config.getProperty("url"),
// config.getProperty("username"),
// config.getProperty("password")
// );
// } catch (Exception e) {
// LOG.error(e.getMessage(), e);
// }
// return this.connection != null;
// }
@Override
public Item add(Item item) {
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO items (name, discription, create_item) values (?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, item.getName());
statement.setString(2, item.getDiscription());
statement.setTimestamp(3, new Timestamp(item.getCreate()));
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
item.setId(String.valueOf(generatedKeys.getInt(1)));
}
//close();
} catch (SQLException e) {
LOG.error(e.getMessage(), e);
}
return item;
}
@Override
public boolean replace(String id, Item item) {
boolean result = false;
try (PreparedStatement statement = connection.prepareStatement("UPDATE items SET name = ?, discription = ?, create_item = ? WHERE id = ?")) {
statement.setString(1, item.getName());
statement.setString(2, item.getDiscription());
statement.setTimestamp(3, new Timestamp(item.getCreate()));
statement.setInt(4, Integer.parseInt(id));
statement.executeUpdate();
result = true;
//close();
} catch (SQLException e) {
LOG.error(e.getMessage(), e);
}
return result;
}
@Override
public boolean delete(String id) {
boolean result = false;
try (PreparedStatement statement = connection.prepareStatement("DELETE FROM items WHERE id = ?")) {
statement.setInt(1, Integer.parseInt(id));
statement.executeUpdate();
result = true;
//close();
} catch (SQLException e) {
LOG.error(e.getMessage(), e);
}
return result;
}
@Override
public ArrayList<Item> findAll() {
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM items")) {
ResultSet date = statement.executeQuery();
while (date.next()) {
Item itemTemp = new Item(date.getString("name"), date.getString("discription"), date.getTimestamp("create_item").getTime());
itemTemp.setId(String.valueOf(date.getInt(1)));
items.add(itemTemp);
}
//close();
} catch (SQLException e) {
LOG.error(e.getMessage(), e);
}
return items;
}
@Override
public ArrayList<Item> findByName(String key) {
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM items WHERE name = ?")) {
statement.setString(1, key);
ResultSet date = statement.executeQuery();
while (date.next()) {
Item itemTemp = new Item(date.getString("name"), date.getString("discription"), date.getTimestamp("create_item").getTime());
itemTemp.setId(String.valueOf(date.getInt(1)));
items.add(itemTemp);
}
//close();
} catch (SQLException e) {
LOG.error(e.getMessage(), e);
}
return items;
}
@Override
public Item findById(String id) {
Item itemId = null;
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM items WHERE id = ?")) {
statement.setInt(1, Integer.parseInt(id));
ResultSet date = statement.executeQuery();
date.next();
itemId = new Item(date.getString("name"), date.getString("discription"), date.getTimestamp("create_item").getTime());
itemId.setId(String.valueOf(date.getInt(1)));
//close();
} catch (SQLException e) {
LOG.error(e.getMessage(), e);
}
return itemId;
}
@Override
public void close() throws SQLException {
if (connection != null) {
connection.close();
}
}
}
|
package com.yan.common.logging.model;
import java.io.Serializable;
public class LoggingEventProperty extends LoggingEventPropertyKey implements Serializable {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column logging_event_property.mapped_value
*
* @mbg.generated Fri Sep 15 16:14:13 CST 2017
*/
private String mappedValue;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table logging_event_property
*
* @mbg.generated Fri Sep 15 16:14:13 CST 2017
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column logging_event_property.mapped_value
*
* @return the value of logging_event_property.mapped_value
*
* @mbg.generated Fri Sep 15 16:14:13 CST 2017
*/
public String getMappedValue() {
return mappedValue;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column logging_event_property.mapped_value
*
* @param mappedValue the value for logging_event_property.mapped_value
*
* @mbg.generated Fri Sep 15 16:14:13 CST 2017
*/
public void setMappedValue(String mappedValue) {
this.mappedValue = mappedValue == null ? null : mappedValue.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table logging_event_property
*
* @mbg.generated Fri Sep 15 16:14:13 CST 2017
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", mappedValue=").append(mappedValue);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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.gravitee.policy.groovy.sandbox;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.classgen.GeneratorContext;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.customizers.CompilationCustomizer;
/**
* Groovy compilation customizer allowing to restrict annotations used in Groovy scripts.
* This customizer acts at compilation phase and delegates all verifications to {@link SecuredResolver} instance.
*
* @see SecuredResolver
* @author Jeoffrey HAEYAERT (jeoffrey.haeyaert at graviteesource.com)
* @author GraviteeSource Team
*/
public class SecuredAnnotationCustomizer extends CompilationCustomizer {
public SecuredAnnotationCustomizer() {
super(CompilePhase.CONVERSION);
}
@Override
public void call(final SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
new RejectAnnotationVisitor(source).visitClass(classNode);
}
private static class RejectAnnotationVisitor extends ClassCodeVisitorSupport {
private SourceUnit source;
public RejectAnnotationVisitor(SourceUnit source) {
this.source = source;
}
@Override
protected SourceUnit getSourceUnit() {
return source;
}
@Override
public void visitAnnotations(AnnotatedNode node) {
for (AnnotationNode an : node.getAnnotations()) {
if (!SecuredResolver.getInstance().isAnnotationAllowed(an.getClassNode().getName())) {
throw new SecurityException("Annotation " + an.getClassNode().getName() + " cannot be used in the sandbox.");
}
}
}
}
}
|
package no.fint.sikri.service;
import no.fint.sikri.utilities.RequestUtilities;
import org.springframework.beans.factory.annotation.Autowired;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
public abstract class SikriAbstractService {
@Autowired
protected RequestUtilities requestUtilities;
final QName serviceName;
public SikriAbstractService(String namespaceURI, String localPart) {
serviceName = new QName(namespaceURI, localPart);
}
void setup(Object port, String service) {
BindingProvider bp = (BindingProvider) port;
requestUtilities.setEndpointAddress(bp.getRequestContext(), service);
}
}
|
package es.upm.miw.iwvg_devops.functional;
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction() {
this(1, 1);
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
public double decimal() {
return (double) numerator / denominator;
}
}
|
package at.meks.backupclientserver.client;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Callable;
import java.util.concurrent.locks.ReentrantLock;
import static java.nio.file.Files.createFile;
import static java.nio.file.Files.createTempFile;
import static java.nio.file.Files.isWritable;
@Singleton
public class FileService {
private static final String DIRECTORIES_WATCHKEY_FILE_SUFFIX = ".dir";
private static final String DIRECTORIES_WATCHKEY_FILE_PREFIX = "directoriesWatchKey";
private ReentrantLock configInitLock = new ReentrantLock();
@Inject
private ConfigFileInitializer configFileInitializer;
Path getConfigFile() {
return rethrowException(() -> {
Path configFile = getApplicationDirectory().resolve(".config");
configInitLock.lock();
try {
if (!configFile.toFile().exists()) {
createFile(configFile);
configFileInitializer.initializeConfigFile(configFile);
}
return configFile;
} finally {
configInitLock.unlock();
}
});
}
private <R> R rethrowException(Callable<R> callable) {
try {
return callable.call();
} catch (Exception e) {
throw new ClientBackupException(e);
}
}
private Path getApplicationDirectory() throws IOException {
return Files.createDirectories(Paths.get(System.getProperty("user.home"),".ClientServerBackup"));
}
public void cleanupDirectoriesMapFiles() {
rethrowException(() -> {
Path applicationDirectory = getApplicationDirectory();
Files.newDirectoryStream(applicationDirectory,
this::isDirectoryWatchKeyDirFile)
.forEach(this::deleteSilently);
return Void.TYPE;
});
}
private boolean isDirectoryWatchKeyDirFile(Path path) {
String fileName = path.getFileName().toString();
return isWritable(path) && path.toFile().isFile()
&& fileName.endsWith(DIRECTORIES_WATCHKEY_FILE_SUFFIX) && fileName.startsWith(DIRECTORIES_WATCHKEY_FILE_PREFIX);
}
private void deleteSilently(Path path) {
rethrowException(() -> Files.deleteIfExists(path));
}
public Path getDirectoriesMapFile() {
return rethrowException(() -> createTempFile(getApplicationDirectory(), DIRECTORIES_WATCHKEY_FILE_PREFIX,
DIRECTORIES_WATCHKEY_FILE_SUFFIX));
}
}
|
package org.zstack.sdk;
import java.util.HashMap;
import java.util.Map;
import org.zstack.sdk.*;
public class DeleteAliyunSnapshotFromRemoteAction extends AbstractAction {
private static final HashMap<String, Parameter> parameterMap = new HashMap<>();
private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>();
public static class Result {
public ErrorCode error;
public org.zstack.sdk.DeleteAliyunSnapshotFromRemoteResult value;
public Result throwExceptionIfError() {
if (error != null) {
throw new ApiException(
String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
);
}
return this;
}
}
@Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String uuid;
@Param(required = false)
public java.lang.String deleteMode = "Permissive";
@Param(required = false)
public java.util.List systemTags;
@Param(required = false)
public java.util.List userTags;
@Param(required = true)
public String sessionId;
@NonAPIParam
public long timeout = -1;
@NonAPIParam
public long pollingInterval = -1;
private Result makeResult(ApiResult res) {
Result ret = new Result();
if (res.error != null) {
ret.error = res.error;
return ret;
}
org.zstack.sdk.DeleteAliyunSnapshotFromRemoteResult value = res.getResult(org.zstack.sdk.DeleteAliyunSnapshotFromRemoteResult.class);
ret.value = value == null ? new org.zstack.sdk.DeleteAliyunSnapshotFromRemoteResult() : value;
return ret;
}
public Result call() {
ApiResult res = ZSClient.call(this);
return makeResult(res);
}
public void call(final Completion<Result> completion) {
ZSClient.call(this, new InternalCompletion() {
@Override
public void complete(ApiResult res) {
completion.complete(makeResult(res));
}
});
}
protected Map<String, Parameter> getParameterMap() {
return parameterMap;
}
protected Map<String, Parameter> getNonAPIParameterMap() {
return nonAPIParameterMap;
}
protected RestInfo getRestInfo() {
RestInfo info = new RestInfo();
info.httpMethod = "DELETE";
info.path = "/hybrid/aliyun/snapshot/{uuid}/remote";
info.needSession = true;
info.needPoll = true;
info.parameterName = "";
return info;
}
}
|
/**
*/
package br.ufes.inf.nemo.frameweb.model.frameweb;
import org.eclipse.uml2.uml.GeneralizationSet;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Service Generalization Set</b></em>'.
* <!-- end-user-doc -->
*
*
* @see br.ufes.inf.nemo.frameweb.model.frameweb.FramewebPackage#getServiceGeneralizationSet()
* @model
* @generated
*/
public interface ServiceGeneralizationSet extends GeneralizationSet {
} // ServiceGeneralizationSet
|
/*
* 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.activemq.artemis.core.management.impl;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanOperationInfo;
import java.util.Collections;
import java.util.Map;
import org.apache.activemq.artemis.api.core.JsonUtil;
import org.apache.activemq.artemis.api.core.management.DivertControl;
import org.apache.activemq.artemis.api.core.management.ResourceNames;
import org.apache.activemq.artemis.core.filter.Filter;
import org.apache.activemq.artemis.core.persistence.StorageManager;
import org.apache.activemq.artemis.core.server.Divert;
import org.apache.activemq.artemis.core.server.transformer.RegisteredTransformer;
import org.apache.activemq.artemis.core.server.transformer.Transformer;
import org.apache.activemq.artemis.logs.AuditLogger;
public class DivertControlImpl extends AbstractControl implements DivertControl {
private final Divert divert;
private final String internalNamingPrefix;
// DivertControlMBean implementation ---------------------------
public DivertControlImpl(final Divert divert,
final StorageManager storageManager,
final String internalNamingPrefix) throws Exception {
super(DivertControl.class, storageManager);
this.divert = divert;
this.internalNamingPrefix = internalNamingPrefix;
}
@Override
public String getAddress() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.getAddress(this.divert);
}
clearIO();
try {
return divert.getAddress().toString();
} finally {
blockOnIO();
}
}
@Override
public String getFilter() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.getFilter(this.divert);
}
clearIO();
try {
Filter filter = divert.getFilter();
return filter != null ? filter.getFilterString().toString() : null;
} finally {
blockOnIO();
}
}
@Override
public String getForwardingAddress() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.getForwardingAddress(this.divert);
}
clearIO();
try {
return divert.getForwardAddress().toString();
} finally {
blockOnIO();
}
}
@Override
public String getRoutingName() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.getRoutingName(this.divert);
}
clearIO();
try {
return divert.getRoutingName().toString();
} finally {
blockOnIO();
}
}
@Override
public String getTransformerClassName() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.getTransformerClassName(this.divert);
}
clearIO();
try {
Transformer transformer = divert.getTransformer();
return transformer != null ? (transformer instanceof RegisteredTransformer ?
((RegisteredTransformer)transformer).getTransformer() : transformer).getClass().getName() : null;
} finally {
blockOnIO();
}
}
@Override
public String getTransformerPropertiesAsJSON() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.getTransformerPropertiesAsJSON(this.divert);
}
return JsonUtil.toJsonObject(getTransformerProperties()).toString();
}
@Override
public Map<String, String> getTransformerProperties() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.getTransformerProperties(this.divert);
}
clearIO();
try {
Transformer transformer = divert.getTransformer();
return transformer != null && transformer instanceof RegisteredTransformer ?
((RegisteredTransformer)transformer).getProperties() : Collections.emptyMap();
} finally {
blockOnIO();
}
}
@Override
public String getRoutingType() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.getRoutingType(this.divert);
}
clearIO();
try {
return divert.getRoutingType().toString();
} finally {
blockOnIO();
}
}
@Override
public String getUniqueName() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.getUniqueName(this.divert);
}
clearIO();
try {
return divert.getUniqueName().toString();
} finally {
blockOnIO();
}
}
@Override
public boolean isExclusive() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.isExclusive(this.divert);
}
clearIO();
try {
return divert.isExclusive();
} finally {
blockOnIO();
}
}
@Override
public boolean isRetroactiveResource() {
if (AuditLogger.isBaseLoggingEnabled()) {
AuditLogger.isRetroactiveResource(this.divert);
}
return ResourceNames.isRetroactiveResource(internalNamingPrefix, divert.getUniqueName());
}
@Override
protected MBeanOperationInfo[] fillMBeanOperationInfo() {
return MBeanInfoHelper.getMBeanOperationsInfo(DivertControl.class);
}
@Override
protected MBeanAttributeInfo[] fillMBeanAttributeInfo() {
return MBeanInfoHelper.getMBeanAttributesInfo(DivertControl.class);
}
}
|
package org.fanshoufeng.interfaces.i2_5;
public class ClassD implements InterfaceB, InterfaceC {
public static void main(String[] args) {
new ClassD().hello();
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.recoveryservicesbackup.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.Response;
import com.azure.core.management.polling.PollResult;
import com.azure.core.util.Context;
import com.azure.core.util.polling.SyncPoller;
import com.azure.resourcemanager.recoveryservicesbackup.fluent.models.OperationStatusInner;
import com.azure.resourcemanager.recoveryservicesbackup.models.MoveRPAcrossTiersRequest;
import com.azure.resourcemanager.recoveryservicesbackup.models.PrepareDataMoveRequest;
import com.azure.resourcemanager.recoveryservicesbackup.models.TriggerDataMoveRequest;
/** An instance of this class provides access to all the operations defined in ResourceProvidersClient. */
public interface ResourceProvidersClient {
/**
* Fetches operation status for data move operation on vault.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param operationId The operationId parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return operation status.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
OperationStatusInner getOperationStatus(String vaultName, String resourceGroupName, String operationId);
/**
* Fetches operation status for data move operation on vault.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param operationId The operationId parameter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return operation status.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<OperationStatusInner> getOperationStatusWithResponse(
String vaultName, String resourceGroupName, String operationId, Context context);
/**
* Prepares source vault for Data Move operation.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param parameters Prepare data move request.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
SyncPoller<PollResult<Void>, Void> beginBmsPrepareDataMove(
String vaultName, String resourceGroupName, PrepareDataMoveRequest parameters);
/**
* Prepares source vault for Data Move operation.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param parameters Prepare data move request.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
SyncPoller<PollResult<Void>, Void> beginBmsPrepareDataMove(
String vaultName, String resourceGroupName, PrepareDataMoveRequest parameters, Context context);
/**
* Prepares source vault for Data Move operation.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param parameters Prepare data move request.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void bmsPrepareDataMove(String vaultName, String resourceGroupName, PrepareDataMoveRequest parameters);
/**
* Prepares source vault for Data Move operation.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param parameters Prepare data move request.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void bmsPrepareDataMove(
String vaultName, String resourceGroupName, PrepareDataMoveRequest parameters, Context context);
/**
* Triggers Data Move Operation on target vault.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param parameters Trigger data move request.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
SyncPoller<PollResult<Void>, Void> beginBmsTriggerDataMove(
String vaultName, String resourceGroupName, TriggerDataMoveRequest parameters);
/**
* Triggers Data Move Operation on target vault.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param parameters Trigger data move request.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
SyncPoller<PollResult<Void>, Void> beginBmsTriggerDataMove(
String vaultName, String resourceGroupName, TriggerDataMoveRequest parameters, Context context);
/**
* Triggers Data Move Operation on target vault.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param parameters Trigger data move request.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void bmsTriggerDataMove(String vaultName, String resourceGroupName, TriggerDataMoveRequest parameters);
/**
* Triggers Data Move Operation on target vault.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param parameters Trigger data move request.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void bmsTriggerDataMove(
String vaultName, String resourceGroupName, TriggerDataMoveRequest parameters, Context context);
/**
* Move recovery point from one datastore to another store.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param fabricName The fabricName parameter.
* @param containerName The containerName parameter.
* @param protectedItemName The protectedItemName parameter.
* @param recoveryPointId The recoveryPointId parameter.
* @param parameters Move Resource Across Tiers Request.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
SyncPoller<PollResult<Void>, Void> beginMoveRecoveryPoint(
String vaultName,
String resourceGroupName,
String fabricName,
String containerName,
String protectedItemName,
String recoveryPointId,
MoveRPAcrossTiersRequest parameters);
/**
* Move recovery point from one datastore to another store.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param fabricName The fabricName parameter.
* @param containerName The containerName parameter.
* @param protectedItemName The protectedItemName parameter.
* @param recoveryPointId The recoveryPointId parameter.
* @param parameters Move Resource Across Tiers Request.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
SyncPoller<PollResult<Void>, Void> beginMoveRecoveryPoint(
String vaultName,
String resourceGroupName,
String fabricName,
String containerName,
String protectedItemName,
String recoveryPointId,
MoveRPAcrossTiersRequest parameters,
Context context);
/**
* Move recovery point from one datastore to another store.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param fabricName The fabricName parameter.
* @param containerName The containerName parameter.
* @param protectedItemName The protectedItemName parameter.
* @param recoveryPointId The recoveryPointId parameter.
* @param parameters Move Resource Across Tiers Request.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void moveRecoveryPoint(
String vaultName,
String resourceGroupName,
String fabricName,
String containerName,
String protectedItemName,
String recoveryPointId,
MoveRPAcrossTiersRequest parameters);
/**
* Move recovery point from one datastore to another store.
*
* @param vaultName The name of the recovery services vault.
* @param resourceGroupName The name of the resource group where the recovery services vault is present.
* @param fabricName The fabricName parameter.
* @param containerName The containerName parameter.
* @param protectedItemName The protectedItemName parameter.
* @param recoveryPointId The recoveryPointId parameter.
* @param parameters Move Resource Across Tiers Request.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void moveRecoveryPoint(
String vaultName,
String resourceGroupName,
String fabricName,
String containerName,
String protectedItemName,
String recoveryPointId,
MoveRPAcrossTiersRequest parameters,
Context context);
}
|
package me.icro.topinterviewquesitons2018.heapstackqueue.nestediterator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* 描述:
* https://leetcode-cn.com/explore/interview/card/top-interview-quesitons-in-2018/266/heap-stack-queue/1160/
*
* @author Lin
* @since 2019-07-21 2:29 PM
*/
public class NestedIterator implements Iterator<Integer> {
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
* <p>
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
* <p>
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
* <p>
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return null if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
private LinkedList<Integer> linkedList = new LinkedList<>();
public NestedIterator(List<NestedInteger> nestedList) {
for (NestedInteger nestedInteger : nestedList) {
offer(nestedInteger);
}
}
@Override
public Integer next() {
return linkedList.pollFirst();
}
@Override
public boolean hasNext() {
return !linkedList.isEmpty();
}
void offer(NestedInteger nestedInteger) {
if (nestedInteger.isInteger()) {
linkedList.offer(nestedInteger.getInteger());
} else {
for (NestedInteger integer : nestedInteger.getList()) {
offer(integer);
}
}
}
}
|
package wang.raye.springboot.config;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
@EnableTransactionManagement
/**
* Druid的DataResource配置类
* @author Raye
* @since 2016年10月7日14:14:18
*/
public class DruidDataSourceConfig implements EnvironmentAware {
private RelaxedPropertyResolver propertyResolver;
public void setEnvironment(Environment env) {
this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
}
@Bean
public DataSource dataSource() {
System.out.println("注入druid!!!");
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(propertyResolver.getProperty("url"));
datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
datasource.setUsername(propertyResolver.getProperty("username"));
datasource.setPassword(propertyResolver.getProperty("password"));
datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("max-wait")));
datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("max-active")));
datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
try {
datasource.setFilters("stat,wall");
} catch (SQLException e) {
e.printStackTrace();
}
return datasource;
}
}
|
/*
* 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.avatica.util;
import org.apache.calcite.avatica.ColumnMetaData;
import java.io.Closeable;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
/**
* Interface to an iteration that is similar to, and can easily support,
* a JDBC {@link java.sql.ResultSet}, but is simpler to implement.
*/
public interface Cursor extends Closeable {
/**
* Creates a list of accessors, one per column.
*
*
* @param types List of column types, per {@link java.sql.Types}.
* @param localCalendar Calendar in local time zone
* @param factory Factory that creates sub-ResultSets when needed
* @return List of column accessors
*/
List<Accessor> createAccessors(List<ColumnMetaData> types,
Calendar localCalendar, ArrayImpl.Factory factory);
/**
* Moves to the next row.
*
* @return Whether moved
*
* @throws SQLException on database error
*/
boolean next() throws SQLException;
/**
* Closes this cursor and releases resources.
*/
void close();
/**
* Returns whether the last value returned was null.
*
* @throws SQLException on database error
*/
boolean wasNull() throws SQLException;
/**
* Accessor of a column value.
*/
public interface Accessor {
boolean wasNull() throws SQLException;
String getString() throws SQLException;
boolean getBoolean() throws SQLException;
byte getByte() throws SQLException;
short getShort() throws SQLException;
int getInt() throws SQLException;
long getLong() throws SQLException;
float getFloat() throws SQLException;
double getDouble() throws SQLException;
BigDecimal getBigDecimal() throws SQLException;
BigDecimal getBigDecimal(int scale) throws SQLException;
byte[] getBytes() throws SQLException;
InputStream getAsciiStream() throws SQLException;
InputStream getUnicodeStream() throws SQLException;
InputStream getBinaryStream() throws SQLException;
Object getObject() throws SQLException;
Reader getCharacterStream() throws SQLException;
Object getObject(Map<String, Class<?>> map) throws SQLException;
Ref getRef() throws SQLException;
Blob getBlob() throws SQLException;
Clob getClob() throws SQLException;
Array getArray() throws SQLException;
Date getDate(Calendar calendar) throws SQLException;
Time getTime(Calendar calendar) throws SQLException;
Timestamp getTimestamp(Calendar calendar) throws SQLException;
URL getURL() throws SQLException;
NClob getNClob() throws SQLException;
SQLXML getSQLXML() throws SQLException;
String getNString() throws SQLException;
Reader getNCharacterStream() throws SQLException;
<T> T getObject(Class<T> type) throws SQLException;
}
}
// End Cursor.java
|
/*
* Copyright 2016-present Open Networking Foundation
*
* 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.onosproject.netconf.ctl.impl;
import org.onosproject.netconf.NetconfDevice;
import org.onosproject.netconf.NetconfDeviceInfo;
import org.onosproject.netconf.NetconfException;
import org.onosproject.netconf.NetconfSession;
import org.onosproject.netconf.NetconfSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default implementation of a NETCONF device.
*/
public class DefaultNetconfDevice implements NetconfDevice {
public static final Logger log = LoggerFactory
.getLogger(DefaultNetconfDevice.class);
private NetconfDeviceInfo netconfDeviceInfo;
private boolean deviceState = true;
private final NetconfSessionFactory sessionFactory;
private NetconfSession netconfSession;
// will block until hello RPC handshake completes
/**
* Creates a new default NETCONF device with the information provided.
* The device gets created only if no exception is thrown while connecting to
* it and establishing the NETCONF session.
* @param deviceInfo information about the device to be created.
* @throws NetconfException if there are problems in creating or establishing
* the underlying NETCONF connection and session.
*/
public DefaultNetconfDevice(NetconfDeviceInfo deviceInfo)
throws NetconfException {
netconfDeviceInfo = deviceInfo;
sessionFactory = new NetconfSessionMinaImpl.MinaSshNetconfSessionFactory();
try {
netconfSession = sessionFactory.createNetconfSession(deviceInfo);
} catch (NetconfException e) {
deviceState = false;
throw new NetconfException("Cannot create connection and session for device " +
deviceInfo, e);
}
}
// will block until hello RPC handshake completes
/**
* Creates a new default NETCONF device with the information provided.
* The device gets created only if no exception is thrown while connecting to
* it and establishing the NETCONF session.
*
* @param deviceInfo information about the device to be created.
* @param factory the factory used to create the session
* @throws NetconfException if there are problems in creating or establishing
* the underlying NETCONF connection and session.
*/
public DefaultNetconfDevice(NetconfDeviceInfo deviceInfo, NetconfSessionFactory factory)
throws NetconfException {
netconfDeviceInfo = deviceInfo;
sessionFactory = factory;
try {
netconfSession = sessionFactory.createNetconfSession(deviceInfo);
} catch (NetconfException e) {
deviceState = false;
throw new NetconfException("Cannot create connection and session for device " +
deviceInfo, e);
}
}
@Override
public boolean isActive() {
return deviceState;
}
@Override
public NetconfSession getSession() {
return netconfSession;
}
@Override
public void disconnect() {
deviceState = false;
try {
netconfSession.close();
} catch (NetconfException e) {
log.warn("Cannot communicate with the device {} session already closed", netconfDeviceInfo);
}
}
@Override
public NetconfDeviceInfo getDeviceInfo() {
return netconfDeviceInfo;
}
}
|
package dev.lamp.models;
public class Account {
private int accountId;
private double balance;
private int clientOwner;
public Account() {
}
public Account(int accountId, double balance, int clientOwner)
{
this.accountId = accountId;
this.balance = balance;
this.clientOwner = clientOwner;
}
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public int getClientOwner() {
return clientOwner;
}
public void setClientOwner(int clientOwner) {
this.clientOwner = clientOwner;
}
@Override
public String toString() {
return "Account{" +
"accountId=" + accountId +
", balance=" + balance +
", clientOwner=" + clientOwner +
'}';
}
}
|
/*
* 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.isis.viewer.common.model.decorator.disable;
import java.io.Serializable;
import java.util.Optional;
import javax.annotation.Nullable;
import org.apache.isis.commons.internal.base._Strings;
import org.apache.isis.core.metamodel.interactions.managed.MemberInteraction;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor(staticName = "of", access = AccessLevel.PRIVATE)
public class DisablingUiModel implements Serializable {
private static final long serialVersionUID = 1L;
@NonNull final String reason;
/**
* @param disabled - overwritten to be {@code true}, whenever {@code reason} is not empty
* @param reason
* @deprecated use interaction instead
*/
public static Optional<DisablingUiModel> of(boolean disabled, @Nullable String reason) {
reason = _Strings.nullToEmpty(reason);
disabled|=_Strings.isNotEmpty(reason);
return disabled
? Optional.of(of(reason))
: Optional.empty();
}
public static Optional<DisablingUiModel> of(@NonNull MemberInteraction<?, ?> memberInteraction) {
return memberInteraction.getInteractionVeto()
.map(veto->of(veto.getReason()));
}
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.support;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCreationNotAllowedException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.SingletonBeanRegistry;
import org.springframework.core.SimpleAliasRegistry;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Generic registry for shared bean instances, implementing the
* {@link org.springframework.beans.factory.config.SingletonBeanRegistry}.
* Allows for registering singleton instances that should be shared
* for all callers of the registry, to be obtained via bean name.
*
* <p>Also supports registration of
* {@link org.springframework.beans.factory.DisposableBean} instances,
* (which might or might not correspond to registered singletons),
* to be destroyed on shutdown of the registry. Dependencies between
* beans can be registered to enforce an appropriate shutdown order.
*
* <p>This class mainly serves as base class for
* {@link org.springframework.beans.factory.BeanFactory} implementations,
* factoring out the common management of singleton bean instances. Note that
* the {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
* interface extends the {@link SingletonBeanRegistry} interface.
*
* <p>Note that this class assumes neither a bean definition concept
* nor a specific creation process for bean instances, in contrast to
* {@link AbstractBeanFactory} and {@link DefaultListableBeanFactory}
* (which inherit from it). Can alternatively also be used as a nested
* helper to delegate to.
*
* @author Juergen Hoeller
* @since 2.0
* @see #registerSingleton
* @see #registerDisposableBean
* @see org.springframework.beans.factory.DisposableBean
* @see org.springframework.beans.factory.config.ConfigurableBeanFactory
*/
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
/** Maximum number of suppressed exceptions to preserve. */
private static final int SUPPRESSED_EXCEPTIONS_LIMIT = 100;
/** Cache of singleton objects: bean name to bean instance. */
//一级缓存
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
//三级缓存
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
//二级缓存
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
/** Set of registered singletons, containing the bean names in registration order. */
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
/** Names of beans that are currently in creation. */
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
/** Names of beans currently excluded from in creation checks. */
private final Set<String> inCreationCheckExclusions =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
/** Collection of suppressed Exceptions, available for associating related causes. */
@Nullable
private Set<Exception> suppressedExceptions;
/** Flag that indicates whether we're currently within destroySingletons. */
private boolean singletonsCurrentlyInDestruction = false;
/** Disposable bean instances: bean name to disposable instance. */
private final Map<String, Object> disposableBeans = new LinkedHashMap<>();
/** Map between containing bean names: bean name to Set of bean names that the bean contains. */
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);
/** Map between dependent bean names: bean name to Set of dependent bean names. */
private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);
/** Map between depending bean names: bean name to Set of bean names for the bean's dependencies. */
private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);
@Override
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
Assert.notNull(beanName, "Bean name must not be null");
Assert.notNull(singletonObject, "Singleton object must not be null");
synchronized (this.singletonObjects) {
Object oldObject = this.singletonObjects.get(beanName);
if (oldObject != null) {
throw new IllegalStateException("Could not register object [" + singletonObject +
"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
}
addSingleton(beanName, singletonObject);
}
}
/**
* Add the given singleton object to the singleton cache of this factory.
* <p>To be called for eager registration of singletons.
* @param beanName the name of the bean
* @param singletonObject the singleton object
*/
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
/**
* Add the given singleton factory for building the specified singleton
* if necessary.
* <p>To be called for eager registration of singletons, e.g. to be able to
* resolve circular references.
* @param beanName the name of the bean
* @param singletonFactory the factory for the singleton object
*/
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
@Override
@Nullable
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
/**
* Return the (raw) singleton object registered under the given name.
* <p>Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
synchronized (this.singletonObjects) {
// Consistent creation of early reference within full singleton lock
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
/**
* Return the (raw) singleton object registered under the given name,
* creating and registering a new one if none registered yet.
* @param beanName the name of the bean
* @param singletonFactory the ObjectFactory to lazily create the singleton
* with, if necessary
* @return the registered singleton object
*/
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
/**
* Register an exception that happened to get suppressed during the creation of a
* singleton bean instance, e.g. a temporary circular reference resolution problem.
* <p>The default implementation preserves any given exception in this registry's
* collection of suppressed exceptions, up to a limit of 100 exceptions, adding
* them as related causes to an eventual top-level {@link BeanCreationException}.
* @param ex the Exception to register
* @see BeanCreationException#getRelatedCauses()
*/
protected void onSuppressedException(Exception ex) {
synchronized (this.singletonObjects) {
if (this.suppressedExceptions != null && this.suppressedExceptions.size() < SUPPRESSED_EXCEPTIONS_LIMIT) {
this.suppressedExceptions.add(ex);
}
}
}
/**
* Remove the bean with the given name from the singleton cache of this factory,
* to be able to clean up eager registration of a singleton if creation failed.
* @param beanName the name of the bean
* @see #getSingletonMutex()
*/
protected void removeSingleton(String beanName) {
synchronized (this.singletonObjects) {
this.singletonObjects.remove(beanName);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.remove(beanName);
}
}
@Override
public boolean containsSingleton(String beanName) {
return this.singletonObjects.containsKey(beanName);
}
@Override
public String[] getSingletonNames() {
synchronized (this.singletonObjects) {
return StringUtils.toStringArray(this.registeredSingletons);
}
}
@Override
public int getSingletonCount() {
synchronized (this.singletonObjects) {
return this.registeredSingletons.size();
}
}
public void setCurrentlyInCreation(String beanName, boolean inCreation) {
Assert.notNull(beanName, "Bean name must not be null");
if (!inCreation) {
this.inCreationCheckExclusions.add(beanName);
}
else {
this.inCreationCheckExclusions.remove(beanName);
}
}
public boolean isCurrentlyInCreation(String beanName) {
Assert.notNull(beanName, "Bean name must not be null");
return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName));
}
protected boolean isActuallyInCreation(String beanName) {
return isSingletonCurrentlyInCreation(beanName);
}
/**
* Return whether the specified singleton bean is currently in creation
* (within the entire factory).
* @param beanName the name of the bean
*/
public boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
/**
* Callback before singleton creation.
* <p>The default implementation register the singleton as currently in creation.
* @param beanName the name of the singleton about to be created
* @see #isSingletonCurrentlyInCreation
*/
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
/**
* Callback after singleton creation.
* <p>The default implementation marks the singleton as not in creation anymore.
* @param beanName the name of the singleton that has been created
* @see #isSingletonCurrentlyInCreation
*/
protected void afterSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}
/**
* Add the given bean to the list of disposable beans in this registry.
* <p>Disposable beans usually correspond to registered singletons,
* matching the bean name but potentially being a different instance
* (for example, a DisposableBean adapter for a singleton that does not
* naturally implement Spring's DisposableBean interface).
* @param beanName the name of the bean
* @param bean the bean instance
*/
public void registerDisposableBean(String beanName, DisposableBean bean) {
synchronized (this.disposableBeans) {
this.disposableBeans.put(beanName, bean);
}
}
/**
* Register a containment relationship between two beans,
* e.g. between an inner bean and its containing outer bean.
* <p>Also registers the containing bean as dependent on the contained bean
* in terms of destruction order.
* @param containedBeanName the name of the contained (inner) bean
* @param containingBeanName the name of the containing (outer) bean
* @see #registerDependentBean
*/
public void registerContainedBean(String containedBeanName, String containingBeanName) {
synchronized (this.containedBeanMap) {
Set<String> containedBeans =
this.containedBeanMap.computeIfAbsent(containingBeanName, k -> new LinkedHashSet<>(8));
if (!containedBeans.add(containedBeanName)) {
return;
}
}
registerDependentBean(containedBeanName, containingBeanName);
}
/**
* Register a dependent bean for the given bean,
* to be destroyed before the given bean is destroyed.
* @param beanName the name of the bean
* @param dependentBeanName the name of the dependent bean
*/
public void registerDependentBean(String beanName, String dependentBeanName) {
String canonicalName = canonicalName(beanName);
synchronized (this.dependentBeanMap) {
Set<String> dependentBeans =
this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
if (!dependentBeans.add(dependentBeanName)) {
return;
}
}
synchronized (this.dependenciesForBeanMap) {
Set<String> dependenciesForBean =
this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
dependenciesForBean.add(canonicalName);
}
}
/**
* Determine whether the specified dependent bean has been registered as
* dependent on the given bean or on any of its transitive dependencies.
* @param beanName the name of the bean to check
* @param dependentBeanName the name of the dependent bean
* @since 4.0
*/
protected boolean isDependent(String beanName, String dependentBeanName) {
synchronized (this.dependentBeanMap) {
return isDependent(beanName, dependentBeanName, null);
}
}
private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {
if (alreadySeen != null && alreadySeen.contains(beanName)) {
return false;
}
String canonicalName = canonicalName(beanName);
Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
if (dependentBeans == null) {
return false;
}
if (dependentBeans.contains(dependentBeanName)) {
return true;
}
for (String transitiveDependency : dependentBeans) {
if (alreadySeen == null) {
alreadySeen = new HashSet<>();
}
alreadySeen.add(beanName);
if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
return true;
}
}
return false;
}
/**
* Determine whether a dependent bean has been registered for the given name.
* @param beanName the name of the bean to check
*/
protected boolean hasDependentBean(String beanName) {
return this.dependentBeanMap.containsKey(beanName);
}
/**
* Return the names of all beans which depend on the specified bean, if any.
* @param beanName the name of the bean
* @return the array of dependent bean names, or an empty array if none
*/
public String[] getDependentBeans(String beanName) {
Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
if (dependentBeans == null) {
return new String[0];
}
synchronized (this.dependentBeanMap) {
return StringUtils.toStringArray(dependentBeans);
}
}
/**
* Return the names of all beans that the specified bean depends on, if any.
* @param beanName the name of the bean
* @return the array of names of beans which the bean depends on,
* or an empty array if none
*/
public String[] getDependenciesForBean(String beanName) {
Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
if (dependenciesForBean == null) {
return new String[0];
}
synchronized (this.dependenciesForBeanMap) {
return StringUtils.toStringArray(dependenciesForBean);
}
}
public void destroySingletons() {
if (logger.isTraceEnabled()) {
logger.trace("Destroying singletons in " + this);
}
synchronized (this.singletonObjects) {
this.singletonsCurrentlyInDestruction = true;
}
String[] disposableBeanNames;
synchronized (this.disposableBeans) {
disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
}
for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
destroySingleton(disposableBeanNames[i]);
}
this.containedBeanMap.clear();
this.dependentBeanMap.clear();
this.dependenciesForBeanMap.clear();
clearSingletonCache();
}
/**
* Clear all cached singleton instances in this registry.
* @since 4.3.15
*/
protected void clearSingletonCache() {
synchronized (this.singletonObjects) {
this.singletonObjects.clear();
this.singletonFactories.clear();
this.earlySingletonObjects.clear();
this.registeredSingletons.clear();
this.singletonsCurrentlyInDestruction = false;
}
}
/**
* Destroy the given bean. Delegates to {@code destroyBean}
* if a corresponding disposable bean instance is found.
* @param beanName the name of the bean
* @see #destroyBean
*/
public void destroySingleton(String beanName) {
// Remove a registered singleton of the given name, if any.
removeSingleton(beanName);
// Destroy the corresponding DisposableBean instance.
DisposableBean disposableBean;
synchronized (this.disposableBeans) {
disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
}
destroyBean(beanName, disposableBean);
}
/**
* Destroy the given bean. Must destroy beans that depend on the given
* bean before the bean itself. Should not throw any exceptions.
* @param beanName the name of the bean
* @param bean the bean instance to destroy
*/
protected void destroyBean(String beanName, @Nullable DisposableBean bean) {
// Trigger destruction of dependent beans first...
Set<String> dependencies;
synchronized (this.dependentBeanMap) {
// Within full synchronization in order to guarantee a disconnected Set
dependencies = this.dependentBeanMap.remove(beanName);
}
if (dependencies != null) {
if (logger.isTraceEnabled()) {
logger.trace("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
}
for (String dependentBeanName : dependencies) {
destroySingleton(dependentBeanName);
}
}
// Actually destroy the bean now...
if (bean != null) {
try {
bean.destroy();
}
catch (Throwable ex) {
if (logger.isWarnEnabled()) {
logger.warn("Destruction of bean with name '" + beanName + "' threw an exception", ex);
}
}
}
// Trigger destruction of contained beans...
Set<String> containedBeans;
synchronized (this.containedBeanMap) {
// Within full synchronization in order to guarantee a disconnected Set
containedBeans = this.containedBeanMap.remove(beanName);
}
if (containedBeans != null) {
for (String containedBeanName : containedBeans) {
destroySingleton(containedBeanName);
}
}
// Remove destroyed bean from other beans' dependencies.
synchronized (this.dependentBeanMap) {
for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Set<String>> entry = it.next();
Set<String> dependenciesToClean = entry.getValue();
dependenciesToClean.remove(beanName);
if (dependenciesToClean.isEmpty()) {
it.remove();
}
}
}
// Remove destroyed bean's prepared dependency information.
this.dependenciesForBeanMap.remove(beanName);
}
/**
* Exposes the singleton mutex to subclasses and external collaborators.
* <p>Subclasses should synchronize on the given Object if they perform
* any sort of extended singleton creation phase. In particular, subclasses
* should <i>not</i> have their own mutexes involved in singleton creation,
* to avoid the potential for deadlocks in lazy-init situations.
*/
@Override
public final Object getSingletonMutex() {
return this.singletonObjects;
}
}
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.python.editor.refactoring.ui;
import java.lang.ref.WeakReference;
import javax.swing.Icon;
import org.netbeans.api.project.FileOwnerQuery;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectInformation;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.modules.refactoring.spi.ui.*;
import org.openide.filesystems.FileObject;
/**
*
* @author Jan Becicka
*/
public class ProjectTreeElement implements TreeElement {
private String name;
private Icon icon;
private WeakReference<Project> prj;
private FileObject prjDir;
/** Creates a new instance of ProjectTreeElement */
public ProjectTreeElement(Project prj) {
ProjectInformation pi = ProjectUtils.getInformation(prj);
name = pi.getDisplayName();
icon = pi.getIcon();
this.prj = new WeakReference<>(prj);
prjDir = prj.getProjectDirectory();
}
@Override
public TreeElement getParent(boolean isLogical) {
return null;
}
@Override
public Icon getIcon() {
return icon;
}
@Override
public String getText(boolean isLogical) {
return name;
}
@Override
public Object getUserObject() {
Project p = prj.get();
if (p == null) {
p = FileOwnerQuery.getOwner(prjDir);
}
return p;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.