language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | quarkusio__quarkus | extensions/funqy/funqy-google-cloud-functions/runtime/src/main/java/io/quarkus/funqy/gcp/functions/FunqyCloudEventsFunction.java | {
"start": 236,
"end": 2370
} | class ____ implements CloudEventsFunction {
protected static final String deploymentStatus;
protected static boolean started = false;
static {
StringWriter error = new StringWriter();
PrintWriter errorWriter = new PrintWriter(error, true);
if (Application.currentApplication() == null) { // were we already bootstrapped? Needed for mock unit testing.
// For GCP functions, we need to set the TCCL to the QuarkusHttpFunction classloader then restore it.
// Without this, we have a lot of classloading issues (ClassNotFoundException on existing classes)
// during static init.
ClassLoader currentCl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(FunqyCloudEventsFunction.class.getClassLoader());
Class<?> appClass = Class.forName("io.quarkus.runner.ApplicationImpl");
String[] args = {};
Application app = (Application) appClass.getConstructor().newInstance();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
app.stop();
}
});
app.start(args);
errorWriter.println("Quarkus bootstrapped successfully.");
started = true;
} catch (Exception ex) {
errorWriter.println("Quarkus bootstrap failed.");
ex.printStackTrace(errorWriter);
} finally {
Thread.currentThread().setContextClassLoader(currentCl);
}
} else {
errorWriter.println("Quarkus bootstrapped successfully.");
started = true;
}
deploymentStatus = error.toString();
}
@Override
public void accept(CloudEvent cloudEvent) throws Exception {
if (!started) {
throw new RuntimeException(deploymentStatus);
}
FunqyCloudFunctionsBindingRecorder.handle(cloudEvent);
}
}
| FunqyCloudEventsFunction |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/SealedTypesWithTypedDeserializationTest.java | {
"start": 3254,
"end": 3403
} | class ____ {
@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type2")
public Date date;
}
static | Issue506DateBean |
java | elastic__elasticsearch | x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/action/TransportMonitoringBulkAction.java | {
"start": 3963,
"end": 8059
} | class ____ {
private final ThreadPool threadPool;
private final MonitoringBulkRequest request;
private final ActionListener<MonitoringBulkResponse> listener;
private final Exporters exportService;
private final String defaultClusterUUID;
private final long defaultTimestamp;
private final MonitoringDoc.Node defaultNode;
AsyncAction(
ThreadPool threadPool,
MonitoringBulkRequest request,
ActionListener<MonitoringBulkResponse> listener,
Exporters exportService,
String defaultClusterUUID,
long defaultTimestamp,
MonitoringDoc.Node defaultNode
) {
this.threadPool = threadPool;
this.request = request;
this.listener = listener;
this.exportService = exportService;
this.defaultClusterUUID = defaultClusterUUID;
this.defaultTimestamp = defaultTimestamp;
this.defaultNode = defaultNode;
}
void start() {
executeExport(createMonitoringDocs(request.getDocs()), System.nanoTime(), listener);
}
/**
* Iterate over the list of {@link MonitoringBulkDoc} to create the corresponding
* list of {@link MonitoringDoc}.
*/
Collection<MonitoringDoc> createMonitoringDocs(Collection<MonitoringBulkDoc> bulkDocs) {
return bulkDocs.stream()
.filter(bulkDoc -> bulkDoc.getSystem() != MonitoredSystem.UNKNOWN)
.map(this::createMonitoringDoc)
.toList();
}
/**
* Create a {@link MonitoringDoc} from a {@link MonitoringBulkDoc}.
*
* @param bulkDoc the {@link MonitoringBulkDoc}
* @return the {@link MonitoringDoc} to export
*/
MonitoringDoc createMonitoringDoc(final MonitoringBulkDoc bulkDoc) {
final MonitoredSystem system = bulkDoc.getSystem();
final String type = bulkDoc.getType();
final String id = bulkDoc.getId();
final long intervalMillis = bulkDoc.getIntervalMillis();
final XContentType xContentType = bulkDoc.getXContentType();
final BytesReference source = bulkDoc.getSource();
final long timestamp;
if (bulkDoc.getTimestamp() != 0L) {
timestamp = bulkDoc.getTimestamp();
} else {
timestamp = defaultTimestamp;
}
return new BytesReferenceMonitoringDoc(
defaultClusterUUID,
timestamp,
intervalMillis,
defaultNode,
system,
type,
id,
xContentType,
source
);
}
/**
* Exports the documents
*/
void executeExport(
final Collection<MonitoringDoc> docs,
final long startTimeNanos,
final ActionListener<MonitoringBulkResponse> delegate
) {
threadPool.executor(ThreadPool.Names.GENERIC).execute(new ActionRunnable<MonitoringBulkResponse>(delegate) {
@Override
protected void doRun() {
exportService.export(docs, ActionListener.wrap(r -> listener.onResponse(response(startTimeNanos)), this::onFailure));
}
@Override
public void onFailure(Exception e) {
listener.onResponse(response(startTimeNanos, e));
}
});
}
}
private static MonitoringBulkResponse response(final long start) {
return new MonitoringBulkResponse(took(start), false);
}
private static MonitoringBulkResponse response(final long start, final Exception e) {
return new MonitoringBulkResponse(took(start), new MonitoringBulkResponse.Error(e));
}
private static long took(final long start) {
return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
}
}
| AsyncAction |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletSpec.java | {
"start": 5700,
"end": 5899
} | interface ____ {
/**
* Add an object element.
* @return an object element builder
*/
OBJECT object();
/**
* Add an object element.
* @param selector as #id. | _Object |
java | apache__kafka | connect/runtime/src/test/java/org/apache/kafka/connect/integration/BlockingConnectorTest.java | {
"start": 23041,
"end": 25122
} | class ____ extends SourceConnector {
private Block block;
// No-args constructor required by the framework
public BlockingConnector() {
this(null);
}
protected BlockingConnector(String block) {
this.block = new Block(block);
}
@Override
public void initialize(ConnectorContext ctx) {
block.maybeBlockOn(CONNECTOR_INITIALIZE);
super.initialize(ctx);
}
@Override
public void initialize(ConnectorContext ctx, List<Map<String, String>> taskConfigs) {
block.maybeBlockOn(CONNECTOR_INITIALIZE_WITH_TASK_CONFIGS);
super.initialize(ctx, taskConfigs);
}
@Override
public void start(Map<String, String> props) {
this.block = new Block(props);
block.maybeBlockOn(CONNECTOR_START);
}
@Override
public void reconfigure(Map<String, String> props) {
block.maybeBlockOn(CONNECTOR_RECONFIGURE);
super.reconfigure(props);
}
@Override
public Class<? extends Task> taskClass() {
block.maybeBlockOn(CONNECTOR_TASK_CLASS);
return BlockingTask.class;
}
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
block.maybeBlockOn(CONNECTOR_TASK_CONFIGS);
return List.of(Map.of());
}
@Override
public void stop() {
block.maybeBlockOn(CONNECTOR_STOP);
}
@Override
public Config validate(Map<String, String> connectorConfigs) {
block.maybeBlockOn(CONNECTOR_VALIDATE);
return super.validate(connectorConfigs);
}
@Override
public ConfigDef config() {
block.maybeBlockOn(CONNECTOR_CONFIG);
return Block.config();
}
@Override
public String version() {
block.maybeBlockOn(CONNECTOR_VERSION);
return "0.0.0";
}
public static | BlockingConnector |
java | apache__camel | core/camel-util/src/main/java/org/apache/camel/util/concurrent/RejectableFutureTask.java | {
"start": 1069,
"end": 1684
} | class ____<V> extends FutureTask<V> implements Rejectable {
private final Rejectable rejectable;
public RejectableFutureTask(Callable<V> callable) {
super(callable);
this.rejectable = callable instanceof Rejectable ? (Rejectable) callable : null;
}
public RejectableFutureTask(Runnable runnable, V result) {
super(runnable, result);
this.rejectable = runnable instanceof Rejectable ? (Rejectable) runnable : null;
}
@Override
public void reject() {
if (rejectable != null) {
rejectable.reject();
}
}
}
| RejectableFutureTask |
java | apache__flink | flink-formats/flink-avro-confluent-registry/src/test/java/org/apache/flink/formats/avro/registry/confluent/RegistryAvroRowDataSeDeSchemaTest.java | {
"start": 2628,
"end": 8600
} | class ____ {
private static final Schema ADDRESS_SCHEMA = Address.getClassSchema();
private static final Schema ADDRESS_SCHEMA_COMPATIBLE =
new Schema.Parser()
.parse(
""
+ "{\"namespace\": \"org.apache.flink.formats.avro.generated\",\n"
+ " \"type\": \"record\",\n"
+ " \"name\": \"Address\",\n"
+ " \"fields\": [\n"
+ " {\"name\": \"num\", \"type\": \"int\"},\n"
+ " {\"name\": \"street\", \"type\": \"string\"}\n"
+ " ]\n"
+ "}");
private static final String SUBJECT = "address-value";
private static SchemaRegistryClient client;
private Address address;
@BeforeAll
static void beforeClass() {
client = new MockSchemaRegistryClient();
}
@BeforeEach
void before() {
this.address = TestDataGenerator.generateRandomAddress(new Random());
}
@AfterEach
void after() throws IOException, RestClientException {
client.deleteSubject(SUBJECT);
}
@Test
void testRowDataWriteReadWithFullSchema() throws Exception {
testRowDataWriteReadWithSchema(ADDRESS_SCHEMA);
}
@Test
void testRowDataWriteReadWithCompatibleSchema() throws Exception {
testRowDataWriteReadWithSchema(ADDRESS_SCHEMA_COMPATIBLE);
// Validates new schema has been registered.
assertThat(client.getAllVersions(SUBJECT)).hasSize(1);
}
@Test
void testRowDataWriteReadWithPreRegisteredSchema() throws Exception {
client.register(SUBJECT, ADDRESS_SCHEMA);
testRowDataWriteReadWithSchema(ADDRESS_SCHEMA);
// Validates it does not produce new schema.
assertThat(client.getAllVersions(SUBJECT)).hasSize(1);
}
@Test
void testRowDataReadWithNonRegistryAvro() throws Exception {
DataType dataType = AvroSchemaConverter.convertToDataType(ADDRESS_SCHEMA.toString());
RowType rowType = (RowType) dataType.getLogicalType();
AvroRowDataDeserializationSchema deserializer =
getDeserializationSchema(rowType, ADDRESS_SCHEMA);
deserializer.open(null);
client.register(SUBJECT, ADDRESS_SCHEMA);
byte[] oriBytes = writeRecord(address, ADDRESS_SCHEMA);
assertThatThrownBy(() -> deserializer.deserialize(oriBytes))
.isInstanceOf(IOException.class)
.hasCause(new IOException("Unknown data format. Magic number does not match"));
}
private void testRowDataWriteReadWithSchema(Schema schema) throws Exception {
DataType dataType = AvroSchemaConverter.convertToDataType(schema.toString());
RowType rowType = (RowType) dataType.getLogicalType();
AvroRowDataSerializationSchema serializer = getSerializationSchema(rowType, schema);
Schema writeSchema = AvroSchemaConverter.convertToSchema(dataType.getLogicalType());
AvroRowDataDeserializationSchema deserializer =
getDeserializationSchema(rowType, writeSchema);
serializer.open(null);
deserializer.open(null);
assertThat(deserializer.deserialize(null)).isNull();
RowData oriData = address2RowData(address);
byte[] serialized = serializer.serialize(oriData);
RowData rowData = deserializer.deserialize(serialized);
assertThat(rowData.getArity()).isEqualTo(schema.getFields().size());
assertThat(rowData.getInt(0)).isEqualTo(address.getNum());
assertThat(rowData.getString(1).toString()).isEqualTo(address.getStreet());
if (schema != ADDRESS_SCHEMA_COMPATIBLE) {
assertThat(rowData.getString(2).toString()).isEqualTo(address.getCity());
assertThat(rowData.getString(3).toString()).isEqualTo(address.getState());
assertThat(rowData.getString(4).toString()).isEqualTo(address.getZip());
}
}
// ------------------------------------------------------------------------
// Utilities
// ------------------------------------------------------------------------
private static AvroRowDataSerializationSchema getSerializationSchema(
RowType rowType, Schema avroSchema) {
ConfluentSchemaRegistryCoder registryCoder =
new ConfluentSchemaRegistryCoder(SUBJECT, client);
return new AvroRowDataSerializationSchema(
rowType,
new RegistryAvroSerializationSchema<GenericRecord>(
GenericRecord.class, avroSchema, () -> registryCoder),
RowDataToAvroConverters.createConverter(rowType));
}
private static AvroRowDataDeserializationSchema getDeserializationSchema(
RowType rowType, Schema avroSchema) {
ConfluentSchemaRegistryCoder registryCoder =
new ConfluentSchemaRegistryCoder(SUBJECT, client);
return new AvroRowDataDeserializationSchema(
new RegistryAvroDeserializationSchema<GenericRecord>(
GenericRecord.class, avroSchema, () -> registryCoder),
AvroToRowDataConverters.createRowConverter(rowType),
InternalTypeInfo.of(rowType));
}
private static RowData address2RowData(Address address) {
GenericRowData rowData = new GenericRowData(5);
rowData.setField(0, address.getNum());
rowData.setField(1, new BinaryStringData(address.getStreet().toString()));
rowData.setField(2, new BinaryStringData(address.getCity().toString()));
rowData.setField(3, new BinaryStringData(address.getState().toString()));
rowData.setField(4, new BinaryStringData(address.getZip().toString()));
return rowData;
}
}
| RegistryAvroRowDataSeDeSchemaTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/B.java | {
"start": 620,
"end": 1254
} | class ____ {
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
Long id;
@NotNull
String name;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
@OrderBy("name")
java.util.List<C> cs = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public java.util.List<C> getCs() {
return cs;
}
@Override
public String toString() {
return "B [id=" + id + ", name=" + name + ", cs="+cs+"]";
}
}
| B |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/TestSpeculativeExecution.java | {
"start": 2363,
"end": 4803
} | class ____ extends LegacyTaskRuntimeEstimator {
private static final long SPECULATE_THIS = 999999L;
public TestSpecEstimator() {
super();
}
/*
* This will only be called if speculative execution is turned on.
*
* If either mapper or reducer speculation is turned on, this will be
* called.
*
* This will cause speculation to engage for the first mapper or first
* reducer (that is, attempt ID "*_m_000000_0" or "*_r_000000_0")
*
* If this attempt is killed, the retry will have attempt id 1, so it
* will not engage speculation again.
*/
@Override
public long estimatedRuntime(TaskAttemptId id) {
if ((id.getTaskId().getId() == 0) && (id.getId() == 0)) {
return SPECULATE_THIS;
}
return super.estimatedRuntime(id);
}
}
private static final Logger LOG =
LoggerFactory.getLogger(TestSpeculativeExecution.class);
protected static MiniMRYarnCluster mrCluster;
private static Configuration initialConf = new Configuration();
private static FileSystem localFs;
static {
try {
localFs = FileSystem.getLocal(initialConf);
} catch (IOException io) {
throw new RuntimeException("problem getting local fs", io);
}
}
private static Path TEST_ROOT_DIR =
new Path("target",TestSpeculativeExecution.class.getName() + "-tmpDir")
.makeQualified(localFs.getUri(), localFs.getWorkingDirectory());
static Path APP_JAR = new Path(TEST_ROOT_DIR, "MRAppJar.jar");
private static Path TEST_OUT_DIR = new Path(TEST_ROOT_DIR, "test.out.dir");
@BeforeAll
public static void setup() throws IOException {
if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR
+ " not found. Not running test.");
return;
}
if (mrCluster == null) {
mrCluster = new MiniMRYarnCluster(TestSpeculativeExecution.class.getName(), 4);
Configuration conf = new Configuration();
mrCluster.init(conf);
mrCluster.start();
}
// workaround the absent public distcache.
localFs.copyFromLocalFile(new Path(MiniMRYarnCluster.APPJAR), APP_JAR);
localFs.setPermission(APP_JAR, new FsPermission("700"));
}
@AfterAll
public static void tearDown() {
if (mrCluster != null) {
mrCluster.stop();
mrCluster = null;
}
}
public static | TestSpecEstimator |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/rest/action/cat/AbstractCatAction.java | {
"start": 1168,
"end": 3256
} | class ____ extends BaseRestHandler {
protected abstract RestChannelConsumer doCatRequest(RestRequest request, NodeClient client);
protected abstract void documentation(StringBuilder sb);
protected abstract Table getTableWithHeader(RestRequest request);
@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
boolean helpWanted = request.paramAsBoolean("help", false);
if (helpWanted) {
return channel -> {
Table table = getTableWithHeader(request);
int[] width = buildHelpWidths(table, request);
BytesStream bytesOutput = Streams.flushOnCloseStream(channel.bytesOutput());
try (var out = new OutputStreamWriter(bytesOutput, StandardCharsets.UTF_8)) {
for (Table.Cell cell : table.getHeaders()) {
// need to do left-align always, so create new cells
pad(new Table.Cell(cell.value), width[0], request, out);
out.append(" | ");
pad(new Table.Cell(cell.attr.containsKey("alias") ? cell.attr.get("alias") : ""), width[1], request, out);
out.append(" | ");
pad(
new Table.Cell(cell.attr.containsKey("desc") ? cell.attr.get("desc") : "not available"),
width[2],
request,
out
);
out.append("\n");
}
}
channel.sendResponse(new RestResponse(RestStatus.OK, RestResponse.TEXT_CONTENT_TYPE, bytesOutput.bytes()));
};
} else {
return doCatRequest(request, client);
}
}
static Set<String> RESPONSE_PARAMS = Set.of("format", "h", "v", "ts", "pri", "bytes", "size", "time", "s");
@Override
protected Set<String> responseParams() {
return RESPONSE_PARAMS;
}
}
| AbstractCatAction |
java | eclipse-vertx__vert.x | vertx-core/src/test/java/io/vertx/tests/tls/HttpTLSTest.java | {
"start": 2115,
"end": 39234
} | class ____ extends HttpTestBase {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Rule
public Proxy proxy = new Proxy();
@Override
protected VertxOptions getOptions() {
VertxOptions options = super.getOptions();
options.getAddressResolverOptions().setHostsValue(Buffer.buffer("" +
"127.0.0.1 localhost\n" +
"127.0.0.1 host1\n" +
"127.0.0.1 host2.com\n" +
"127.0.0.1 sub.host3.com\n" +
"127.0.0.1 host4.com\n" +
"127.0.0.1 www.host4.com\n" +
"127.0.0.1 host5.com\n" +
"127.0.0.1 www.host5.com\n" +
"127.0.0.1 unknown.com"));
return options;
}
@Test
// Client trusts all server certs
public void testTLSClientTrustAll() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll().pass();
}
@Test
// Server specifies cert that the client trusts (not trust all)
public void testTLSClientTrustServerCert() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts (not trust all)
public void testTLSClientTrustServerCertKeyStore() throws Exception {
testTLS(Cert.NONE, () -> {
JksOptions opts = Trust.SERVER_JKS.get();
return new KeyStoreOptions().setType("JKS").setPath(opts.getPath()).setPassword(opts.getPassword());
}, () -> {
JksOptions opts = Cert.SERVER_JKS.get();
return new KeyStoreOptions().setType("JKS").setPath(opts.getPath()).setPassword(opts.getPassword());
}, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts (not trust all)
public void testTLSClientTrustServerCertPKCS12() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_PKCS12, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts (not trust all)
public void testTLSClientTrustServerCertPEM() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_PEM, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts via a root CA (not trust all)
public void testTLSClientTrustServerCertJKSRootCAWithJKSRootCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS_ROOT_CA, Cert.SERVER_JKS_ROOT_CA, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts via a root CA (not trust all)
public void testTLSClientTrustServerCertJKSRootCAWithPKCS12RootCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PKCS12_ROOT_CA, Cert.SERVER_JKS_ROOT_CA, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts via a root CA (not trust all)
public void testTLSClientTrustServerCertJKSRootRootCAWithPEMRootCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PEM_ROOT_CA, Cert.SERVER_JKS_ROOT_CA, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts via a root CA (not trust all)
public void testTLSClientTrustServerCertPKCS12RootCAWithJKSRootCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS_ROOT_CA, Cert.SERVER_PKCS12_ROOT_CA, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts via a root CA (not trust all)
public void testTLSClientTrustServerCertPKCS12RootCAWithPKCS12RootCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PKCS12_ROOT_CA, Cert.SERVER_PKCS12_ROOT_CA, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts via a root CA (not trust all)
public void testTLSClientTrustServerCertPKCS12RootCAWithPEMRootCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PEM_ROOT_CA, Cert.SERVER_PKCS12_ROOT_CA, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts via a root CA (not trust all)
public void testTLSClientTrustServerCertPEMRootCAWithJKSRootCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS_ROOT_CA, Cert.SERVER_PEM_ROOT_CA, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts via a root CA (not trust all)
public void testTLSClientTrustServerCertPEMRootCAWithPKCS12RootCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PKCS12_ROOT_CA, Cert.SERVER_PEM_ROOT_CA, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts via a root CA (not trust all)
public void testTLSClientTrustServerCertPEMRootCAWithPEMRootCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PEM_ROOT_CA, Cert.SERVER_PEM_ROOT_CA, Trust.NONE).pass();
}
// These two tests should be grouped in same method - todo later
@Test
// Server specifies cert that the client trusts via a root CA that is in a multi pem store (not trust all)
public void testTLSClientTrustServerCertMultiPemWithPEMRootCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PEM_ROOT_CA_AND_OTHER_CA, Cert.SERVER_PEM_ROOT_CA, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts via a other CA that is in a multi pem store (not trust all)
public void testTLSClientTrustServerCertMultiPemWithPEMOtherCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PEM_ROOT_CA_AND_OTHER_CA, Cert.SERVER_PEM_OTHER_CA, Trust.NONE).pass();
}
@Test
// Server specifies cert chain that the client trusts via a CA (not trust all)
public void testTLSClientTrustServerCertPEMRootCAWithPEMCAChain() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PEM_ROOT_CA, Cert.SERVER_PEM_CA_CHAIN, Trust.NONE).pass();
}
@Test
// Server specifies intermediate cert that the client doesn't trust because it is missing the intermediate CA signed by the root CA
public void testTLSClientUntrustedServerCertPEMRootCAWithPEMCA() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PEM_ROOT_CA, Cert.SERVER_PEM_INT_CA, Trust.NONE).fail();
}
@Test
// Server specifies cert that the client trusts (not trust all)
public void testTLSClientTrustPKCS12ServerCert() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PKCS12, Cert.SERVER_JKS, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client trusts (not trust all)
public void testTLSClientTrustPEMServerCert() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PEM, Cert.SERVER_JKS, Trust.NONE).pass();
}
@Test
// Server specifies cert that the client doesn't trust
public void testTLSClientUntrustedServer() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).fail();
}
@Test
// Server specifies cert that the client doesn't trust
public void testTLSClientUntrustedServerPEM() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_PEM, Trust.NONE).fail();
}
@Test
// Client specifies cert even though it's not required
public void testTLSClientCertNotRequired() throws Exception {
testTLS(Cert.CLIENT_JKS, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_JKS).pass();
}
@Test
// Client specifies cert even though it's not required
public void testTLSClientCertNotRequiredPEM() throws Exception {
testTLS(Cert.CLIENT_JKS, Trust.SERVER_JKS, Cert.SERVER_PEM, Trust.CLIENT_JKS).pass();
}
@Test
// Client specifies cert and it is required
public void testTLSClientCertRequired() throws Exception {
testTLS(Cert.CLIENT_JKS, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_JKS).requiresClientAuth().pass();
}
@Test
// Client specifies cert and it is required
public void testTLSClientCertRequiredPKCS12() throws Exception {
testTLS(Cert.CLIENT_JKS, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_PKCS12).requiresClientAuth().pass();
}
@Test
// Client specifies cert and it is required
public void testTLSClientCertRequiredPEM() throws Exception {
testTLS(Cert.CLIENT_JKS, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_PEM).requiresClientAuth().pass();
}
@Test
// Client specifies cert and it is required
public void testTLSClientCertPKCS12Required() throws Exception {
testTLS(Cert.CLIENT_PKCS12, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_JKS).requiresClientAuth().pass();
}
@Test
// Client specifies cert and it is required
public void testTLSClientCertPEMRequired() throws Exception {
testTLS(Cert.CLIENT_PEM, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_JKS).requiresClientAuth().pass();
}
@Test
// Client specifies cert by CA and it is required
public void testTLSClientCertPEM_CARequired() throws Exception {
testTLS(Cert.CLIENT_PEM_ROOT_CA, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_PEM_ROOT_CA).requiresClientAuth().pass();
}
@Test
// Client doesn't specify cert but it's required
public void testTLSClientCertRequiredNoClientCert() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_JKS).requiresClientAuth().fail();
}
@Test
// Client specifies cert but it's not trusted
public void testTLSClientCertClientNotTrusted() throws Exception {
testTLS(Cert.CLIENT_JKS, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.NONE).requiresClientAuth().fail();
}
@Test
// Server specifies cert that the client does not trust via a revoked certificate of the CA
public void testTLSClientRevokedServerCert() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PEM_ROOT_CA, Cert.SERVER_PEM_ROOT_CA, Trust.NONE).clientUsesCrl().fail();
}
@Test
// Client specifies cert that the server does not trust via a revoked certificate of the CA
public void testTLSRevokedClientCertServer() throws Exception {
testTLS(Cert.CLIENT_PEM_ROOT_CA, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_PEM_ROOT_CA).requiresClientAuth().serverUsesCrl().fail();
}
@Test
// Specify some matching cipher suites
public void testTLSMatchingCipherSuites() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll().serverEnabledCipherSuites(ENABLED_CIPHER_SUITES).pass();
}
@Test
// Specify some non matching cipher suites
public void testTLSNonMatchingCipherSuites() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll().serverEnabledCipherSuites(new String[]{"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"}).clientEnabledCipherSuites(new String[]{"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"}).fail();
}
@Test
// Specify some matching TLS protocols
public void testTLSMatchingProtocolVersions() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll()
.serverEnabledSecureTransportProtocol(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"}).pass();
}
@Test
// Provide a host name with a trailing dot
public void testTLSTrailingDotHost() throws Exception {
// Reuse SNI test certificate because it is convenient
TLSTest test = testTLS(Cert.NONE, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host2.com."))
.pass();
assertEquals("host2.com", TestUtils.cnOf(test.clientPeerCert()));
}
/*
checks that we can enable algorithms
static
{
Security.setProperty("jdk.tls.disabledAlgorithms", "");
}
@Test
public void testEnableProtocols() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll()
.clientEnabledSecureTransportProtocol(new String[]{"SSLv3"})
.serverEnabledSecureTransportProtocol(new String[]{"SSLv3"})
.pass();
}
*/
@Test
// Specify some matching TLS protocols
public void testTLSInvalidProtocolVersion() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll().serverEnabledSecureTransportProtocol(new String[]{"HelloWorld"}).fail();
}
@Test
// Specify some non matching TLS protocols
public void testTLSNonMatchingProtocolVersions() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll().serverEnabledSecureTransportProtocol(new String[]{"TLSv1.2"}).clientEnabledSecureTransportProtocol(new String[]{"SSLv2Hello", "TLSv1.1"}).fail();
}
@Test
// Test host verification with a CN matching localhost
public void testTLSVerifyMatchingHost() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.NONE).clientVerifyHost().pass();
}
@Test
// Test host verification with a CN NOT matching localhost
public void testTLSVerifyNonMatchingHost() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_MIM, Trust.NONE).clientVerifyHost().fail();
}
@Test
// Test host verification with a CN matching localhost
public void testTLSVerifyMatchingHostOpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.NONE).clientVerifyHost().clientOpenSSL().pass();
}
@Test
// Test host verification with a CN NOT matching localhost
public void testTLSVerifyNonMatchingHostOpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_MIM, Trust.NONE).clientVerifyHost().clientOpenSSL().fail();
}
// OpenSSL tests
@Test
// Server uses OpenSSL with JKS
public void testTLSClientTrustServerCertJKSOpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.NONE).serverOpenSSL().pass();
}
@Test
// Server uses OpenSSL with PKCS12
public void testTLSClientTrustServerCertPKCS12OpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_PKCS12, Trust.NONE).serverOpenSSL().pass();
}
@Test
// Server uses OpenSSL with PEM
public void testTLSClientTrustServerCertPEMOpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_PEM, Trust.NONE).serverOpenSSL().pass();
}
@Test
// Client trusts OpenSSL with PEM
public void testTLSClientTrustServerCertWithJKSOpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.NONE).clientOpenSSL().pass();
}
@Test
// Server specifies cert that the client trusts (not trust all)
public void testTLSClientTrustServerCertWithPKCS12OpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PKCS12, Cert.SERVER_JKS, Trust.NONE).clientOpenSSL().pass();
}
@Test
// Server specifies cert that the client trusts (not trust all)
public void testTLSClientTrustServerCertWithPEMOpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.SERVER_PEM, Cert.SERVER_JKS, Trust.NONE).clientOpenSSL().pass();
}
@Test
// Client specifies cert and it is required
public void testTLSClientCertRequiredOpenSSL() throws Exception {
testTLS(Cert.CLIENT_JKS, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_JKS).clientOpenSSL().requiresClientAuth().pass();
}
@Test
// Client specifies cert and it is required
public void testTLSClientCertPKCS12RequiredOpenSSL() throws Exception {
testTLS(Cert.CLIENT_PKCS12, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_JKS).clientOpenSSL().requiresClientAuth().pass();
}
@Test
// Client specifies cert and it is required
public void testTLSClientCertPEMRequiredOpenSSL() throws Exception {
testTLS(Cert.CLIENT_PEM, Trust.SERVER_JKS, Cert.SERVER_JKS, Trust.CLIENT_JKS).clientOpenSSL().requiresClientAuth().pass();
}
@Test
// TLSv1.3
public void testTLSv1_3() throws Exception {
Assume.assumeFalse(System.getProperty("java.version").startsWith("1.8"));
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll()
.clientEnabledSecureTransportProtocol(new String[]{"TLSv1.3"})
.serverEnabledSecureTransportProtocol(new String[]{"TLSv1.3"}).pass();
}
@Test
// TLSv1.3 with OpenSSL
public void testTLSv1_3OpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll()
.clientOpenSSL()
.clientEnabledSecureTransportProtocol(new String[]{"TLSv1.3"})
.serverOpenSSL()
.serverEnabledSecureTransportProtocol(new String[]{"TLSv1.3"}).pass();
}
@Test
// Disable TLSv1.3
public void testDisableTLSv1_3() throws Exception {
Assume.assumeFalse(System.getProperty("java.version").startsWith("1.8"));
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll()
.clientEnabledSecureTransportProtocol(new String[]{"TLSv1.3"})
.serverEnabledSecureTransportProtocol(new String[]{"TLSv1.2"})
.fail();
}
@Test
// Disable TLSv1.3 with OpenSSL
public void testDisableTLSv1_3OpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll()
.clientEnabledSecureTransportProtocol(new String[]{"TLSv1.3"})
.serverEnabledSecureTransportProtocol(new String[]{"TLSv1.2"})
.serverOpenSSL()
.fail();
}
@Test
// Disable TLSv1.2
public void testDisableTLSv1_2() throws Exception {
Assume.assumeFalse(System.getProperty("java.version").startsWith("1.8"));
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll()
.clientEnabledSecureTransportProtocol(new String[]{"TLSv1.2"})
.serverEnabledSecureTransportProtocol(new String[]{"TLSv1.3"})
.fail();
}
@Test
// Disable TLSv1.2 with OpenSSL
public void testDisableTLSv1_2OpenSSL() throws Exception {
testTLS(Cert.NONE, Trust.NONE, Cert.SERVER_JKS, Trust.NONE).clientTrustAll()
.clientEnabledSecureTransportProtocol(new String[]{"TLSv1.2"})
.serverEnabledSecureTransportProtocol(new String[]{"TLSv1.3"})
.serverOpenSSL()
.fail();
}
// SNI tests
@Test
// Client provides SNI and server responds with a matching certificate for the indicated server name
public void testSNITrust() throws Exception {
TLSTest test = testTLS(Cert.NONE, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host2.com"))
.pass();
assertEquals("host2.com", TestUtils.cnOf(test.clientPeerCert()));
assertEquals("host2.com", test.indicatedServerName);
}
@Test
// Client provides SNI and server responds with a matching certificate for the indicated server name
public void testSNITrustPKCS12() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST2, Cert.SNI_PKCS12, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host2.com"))
.pass()
.clientPeerCert();
assertEquals("host2.com", TestUtils.cnOf(cert));
}
@Test
// Client provides SNI and server responds with a matching certificate for the indicated server name
public void testSNITrustPEM() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST2, Cert.SNI_PEM, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host2.com"))
.pass()
.clientPeerCert();
assertEquals("host2.com", TestUtils.cnOf(cert));
}
@Test
// Client provides SNI but server ignores it and provides a different cerficate
public void testSNIServerIgnoresExtension1() throws Exception {
testTLS(Cert.NONE, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.NONE)
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host2.com"))
.fail();
}
@Test
// Client provides SNI but server ignores it and provides a different cerficate - check we get a certificate
public void testSNIServerIgnoresExtension2() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SNI_JKS, Trust.NONE)
.clientVerifyHost(false)
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host2.com"))
.pass()
.clientPeerCert();
assertEquals("localhost", TestUtils.cnOf(cert));
}
@Test
// Client provides SNI unknown to the server and server responds with the default certificate (first)
public void testSNIUnknownServerName1() throws Exception {
testTLS(Cert.NONE, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("unknown.com")).fail();
}
@Test
// Client provides SNI unknown to the server and server responds with the default certificate (first)
public void testSNIUnknownServerName2() throws Exception {
TLSTest test = testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.clientVerifyHost(false)
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("unknown.com"))
.pass();
assertEquals("localhost", TestUtils.cnOf(test.clientPeerCert()));
assertEquals("unknown.com", test.indicatedServerName);
}
@Test
// Client provides SNI matched on the server by a wildcard certificate
public void testSNIWildcardMatch() throws Exception {
TLSTest test = testTLS(Cert.NONE, Trust.SNI_JKS_HOST3, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("sub.host3.com"))
.pass();
assertEquals("*.host3.com", TestUtils.cnOf(test.clientPeerCert()));
assertEquals("sub.host3.com", test.indicatedServerName);
}
@Test
// Client provides SNI matched on the server by a wildcard certificate
public void testSNIWildcardMatchPKCS12() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST3, Cert.SNI_PKCS12, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("sub.host3.com"))
.pass()
.clientPeerCert();
assertEquals("*.host3.com", TestUtils.cnOf(cert));
}
@Test
// Client provides SNI matched on the server by a wildcard certificate
public void testSNIWildcardMatchPEM() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST3, Cert.SNI_PEM, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("sub.host3.com"))
.pass()
.clientPeerCert();
assertEquals("*.host3.com", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAlternativeNameMatch1() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST4, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host4.com"))
.pass()
.clientPeerCert();
assertEquals("host4.com certificate", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAlternativeNameMatch1PKCS12() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST4, Cert.SNI_PKCS12, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host4.com"))
.pass()
.clientPeerCert();
assertEquals("host4.com certificate", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAlternativeNameMatch1PEM() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST4, Cert.SNI_PEM, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host4.com"))
.pass()
.clientPeerCert();
assertEquals("host4.com certificate", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAlternativeNameMatch2() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST4, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("www.host4.com"))
.pass()
.clientPeerCert();
assertEquals("host4.com certificate", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAlternativeNameMatch2PKCS12() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST4, Cert.SNI_PKCS12, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("www.host4.com"))
.pass()
.clientPeerCert();
assertEquals("host4.com certificate", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAlternativeNameMatch2PEM() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST4, Cert.SNI_PEM, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("www.host4.com"))
.pass()
.clientPeerCert();
assertEquals("host4.com certificate", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAlternativeNameWildcardMatch() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST5, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("www.host5.com"))
.pass()
.clientPeerCert();
assertEquals("host5.com", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAlternativeNameWildcardMatchPKCS12() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST5, Cert.SNI_PKCS12, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("www.host5.com"))
.pass()
.clientPeerCert();
assertEquals("host5.com", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAlternativeNameWildcardMatchPEM() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST5, Cert.SNI_PEM, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("www.host5.com"))
.pass()
.clientPeerCert();
assertEquals("host5.com", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAltenativeNameCNMatch1() throws Exception {
testTLS(Cert.NONE, Trust.SNI_JKS_HOST5, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host5.com"))
.fail()
.clientPeerCert();
}
@Test
public void testSNISubjectAltenativeNameCNMatch1PKCS12() throws Exception {
testTLS(Cert.NONE, Trust.SNI_JKS_HOST5, Cert.SNI_PKCS12, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host5.com"))
.fail()
.clientPeerCert();
}
@Test
public void testSNISubjectAltenativeNameCNMatch1PEM() throws Exception {
testTLS(Cert.NONE, Trust.SNI_JKS_HOST5, Cert.SNI_PEM, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host5.com"))
.fail()
.clientPeerCert();
}
@Test
public void testSNISubjectAltenativeNameCNMatch2() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST5, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.clientVerifyHost(false)
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host5.com"))
.pass()
.clientPeerCert();
assertEquals("host5.com", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAltenativeNameCNMatch2PKCS12() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST5, Cert.SNI_PKCS12, Trust.NONE)
.serverSni()
.clientVerifyHost(false)
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host5.com"))
.pass()
.clientPeerCert();
assertEquals("host5.com", TestUtils.cnOf(cert));
}
@Test
public void testSNISubjectAltenativeNameCNMatch2PEM() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST5, Cert.SNI_PEM, Trust.NONE)
.serverSni()
.clientVerifyHost(false)
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host5.com"))
.pass()
.clientPeerCert();
assertEquals("host5.com", TestUtils.cnOf(cert));
}
@Test
public void testSNIWithALPN() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.clientUsesAlpn()
.serverUsesAlpn()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host2.com"))
.pass()
.clientPeerCert();
assertEquals("host2.com", TestUtils.cnOf(cert));
}
@Test
// Client provides SNI and server responds with a matching certificate for the indicated server name
public void testSNIWithHostHeader() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestProvider(client -> client.request(new RequestOptions()
.setServer(SocketAddress.inetSocketAddress(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST))
.setMethod(HttpMethod.POST)
.setPort(DEFAULT_HTTPS_PORT)
.setHost("host2.com")
.setURI("/somepath")))
.pass()
.clientPeerCert();
assertEquals("host2.com", TestUtils.cnOf(cert));
}
@Test
public void testSNIWithOpenSSL() throws Exception {
Certificate cert = testTLS(Cert.NONE, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.NONE)
.clientOpenSSL()
.serverOpenSSL()
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host2.com"))
.pass()
.clientPeerCert();
assertEquals("host2.com", TestUtils.cnOf(cert));
}
@Test
public void testSNIDontSendServerNameForShortnames1() throws Exception {
testTLS(Cert.NONE, Trust.SNI_JKS_HOST1, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host1"))
.fail();
}
@Test
public void testSNIDontSendServerNameForShortnames2() throws Exception {
TLSTest test = testTLS(Cert.NONE, Trust.SERVER_JKS, Cert.SNI_JKS, Trust.NONE)
.clientVerifyHost(false)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host1"))
.pass();
assertEquals(null, test.indicatedServerName);
}
@Test
public void testSNIForceSend() throws Exception {
TLSTest test = testTLS(Cert.NONE, Trust.SNI_JKS_HOST1, Cert.SNI_JKS, Trust.NONE)
.clientForceSni()
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host1"))
.pass();
assertEquals("host1", test.indicatedServerName);
}
@Test
public void testSNIWithServerNameTrust() throws Exception {
testTLS(Cert.CLIENT_PEM_ROOT_CA, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.SNI_SERVER_ROOT_CA_AND_OTHER_CA_1)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true)
.setPort(DEFAULT_HTTPS_PORT)
.setHost("host2.com"))
.requiresClientAuth()
.pass();
}
@Test
public void testSNIWithServerNameTrustFallback() throws Exception {
testTLS(Cert.CLIENT_PEM_ROOT_CA, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.SNI_SERVER_ROOT_CA_FALLBACK)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true)
.setPort(DEFAULT_HTTPS_PORT)
.setHost("host2.com"))
.requiresClientAuth()
.pass();
}
@Test
public void testSNIWithServerNameTrustFallbackFail() throws Exception {
testTLS(Cert.CLIENT_PEM_ROOT_CA, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.SNI_SERVER_OTHER_CA_FALLBACK)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true)
.setPort(DEFAULT_HTTPS_PORT)
.setHost("host2.com"))
.requiresClientAuth()
.fail();
}
@Test
public void testSNIWithServerNameTrustFail() throws Exception {
testTLS(Cert.CLIENT_PEM_ROOT_CA, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.SNI_SERVER_ROOT_CA_AND_OTHER_CA_2).serverSni()
.requestOptions(new RequestOptions().setSsl(true)
.setPort(DEFAULT_HTTPS_PORT)
.setHost("host2.com"))
.requiresClientAuth()
.fail();
}
@Test
public void testSNICustomTrustManagerFactoryMapper() throws Exception {
testTLS(Cert.CLIENT_PEM, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, () -> new TrustOptions() {
@Override
public Function<String, TrustManager[]> trustManagerMapper(Vertx vertx) throws Exception {
return null;
}
@Override
public TrustManagerFactory getTrustManagerFactory(Vertx v) throws Exception {
return new TrustManagerFactory(new TrustManagerFactorySpi() {
@Override
protected void engineInit(KeyStore keyStore) throws KeyStoreException {
}
@Override
protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws
InvalidAlgorithmParameterException {
}
@Override
protected TrustManager[] engineGetTrustManagers() {
return new TrustManager[]{TrustAllTrustManager.INSTANCE};
}
}, KeyPairGenerator.getInstance("RSA")
.getProvider(), KeyPairGenerator.getInstance("RSA")
.getAlgorithm()) {
};
}
@Override
public TrustOptions copy() {
return this;
}
}).serverSni()
.requestOptions(new RequestOptions().setSsl(true)
.setPort(DEFAULT_HTTPS_PORT)
.setHost("host2.com"))
.requiresClientAuth()
.pass();
}
@Test
public void testSNICustomTrustManagerFactoryMapper2() throws Exception {
testTLS(Cert.CLIENT_PEM, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, () -> new TrustOptions() {
@Override
public Function<String, TrustManager[]> trustManagerMapper(Vertx v) throws Exception {
return (serverName) -> new TrustManager[]{TrustAllTrustManager.INSTANCE};
}
@Override
public TrustManagerFactory getTrustManagerFactory(Vertx v) throws Exception {
return new TrustManagerFactory(new TrustManagerFactorySpi() {
@Override
protected void engineInit(KeyStore keyStore) throws KeyStoreException {
}
@Override
protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws
InvalidAlgorithmParameterException {
}
@Override
protected TrustManager[] engineGetTrustManagers() {
return new TrustManager[]{TrustAllTrustManager.INSTANCE};
}
}, KeyPairGenerator.getInstance("RSA")
.getProvider(), KeyPairGenerator.getInstance("RSA")
.getAlgorithm()) {
};
}
@Override
public TrustOptions copy() {
return this;
}
}).serverSni()
.requestOptions(new RequestOptions().setSsl(true)
.setPort(DEFAULT_HTTPS_PORT)
.setHost("host2.com"))
.requiresClientAuth()
.pass();
}
@Test
// Provide an host name with a trailing dot validated on the server with SNI
public void testSniWithTrailingDotHost() throws Exception {
TLSTest test = testTLS(Cert.NONE, Trust.SNI_JKS_HOST2, Cert.SNI_JKS, Trust.NONE)
.serverSni()
.requestOptions(new RequestOptions().setSsl(true).setPort(DEFAULT_HTTPS_PORT).setHost("host2.com."))
.pass();
assertEquals("host2.com", TestUtils.cnOf(test.clientPeerCert()));
assertEquals("host2.com", test.indicatedServerName);
}
// Other tests
@Test
// Test custom trust manager factory
public void testCustomTrustManagerFactory() throws Exception {
testTLS(Cert.NONE, () -> new TrustOptions() {
@Override
public Function<String, TrustManager[]> trustManagerMapper(Vertx vertx) throws Exception {
return null;
}
@Override
public TrustManagerFactory getTrustManagerFactory(Vertx v) throws Exception {
return new TrustManagerFactory(new TrustManagerFactorySpi() {
@Override
protected void engineInit(KeyStore keyStore) throws KeyStoreException {
}
@Override
protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws InvalidAlgorithmParameterException {
}
@Override
protected TrustManager[] engineGetTrustManagers() {
return new TrustManager[]{TrustAllTrustManager.INSTANCE};
}
}, KeyPairGenerator.getInstance("RSA").getProvider(), KeyPairGenerator.getInstance("RSA").getAlgorithm()) {
};
}
@Override
public TrustOptions copy() {
return this;
}
}, Cert.SERVER_JKS, Trust.NONE).pass();
}
| HttpTLSTest |
java | apache__camel | components/camel-huawei/camel-huaweicloud-smn/src/test/java/org/apache/camel/component/huaweicloud/smn/PublishTemplatedMessageFunctionalTest.java | {
"start": 1541,
"end": 5091
} | class ____ extends CamelTestSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(PublishTemplatedMessageTest.class.getName());
private static final String ACCESS_KEY = "replace_this_with_access_key";
private static final String SECRET_KEY = "replace_this_with_secret_key";
private static final String TEMPLATE_NAME = "replace_this_with_template_name";
private static final String NOTIFICATION_SUBJECT = "sample notification subjectline";
private static final String TOPIC_NAME = "replace_this_with_topic_name";
private static final String PROJECT_ID = "replace_this_with_project_id";
private static final String REGION = "replace_this_with_region";
@BindToRegistry("serviceKeys")
ServiceKeys serviceKeys
= new ServiceKeys(ACCESS_KEY, SECRET_KEY);
protected RouteBuilder createRouteBuilder() {
// populating tag values. user has to adjust the map entries according to the structure of their respective templates
Map<String, String> tags = new HashMap<>();
// create a map of your placeholder variables
/*Example :
tags.put("name", "reji");
tags.put("phone", "1234567890");
*/
return new RouteBuilder() {
public void configure() {
from("direct:publish_templated_message")
.setProperty(SmnProperties.NOTIFICATION_SUBJECT, constant(NOTIFICATION_SUBJECT))
.setProperty(SmnProperties.NOTIFICATION_TOPIC_NAME, constant(TOPIC_NAME))
.setProperty(SmnProperties.NOTIFICATION_TTL, constant(60))
.setProperty(SmnProperties.TEMPLATE_TAGS, constant(tags))
.setProperty(SmnProperties.TEMPLATE_NAME, constant(TEMPLATE_NAME))
.to("hwcloud-smn:publishMessageService?serviceKeys=#serviceKeys&operation=publishAsTemplatedMessage"
+ "&projectId=" + PROJECT_ID
+ "®ion=" + REGION
+ "&ignoreSslVerification=true")
.log("templated notification sent")
.to("mock:publish_templated_message_result");
}
};
}
/**
* following test cases should be manually enabled to perform test against the actual huaweicloud simple
* notification server with real user credentials. To perform this test, manually comment out the @Disabled
* annotation and enter relevant service parameters in the placeholders above (static variables of this test class)
*
* @throws Exception
*/
@Test
@Disabled("Manually enable this once you configure service parameters in placeholders above")
public void testTemplatedNotificationSend() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:publish_templated_message_result");
mock.expectedMinimumMessageCount(1);
template.sendBody("direct:publish_templated_message", null);
Exchange responseExchange = mock.getExchanges().get(0);
mock.assertIsSatisfied();
assertNotNull(responseExchange.getProperty(SmnProperties.SERVICE_MESSAGE_ID));
assertNotNull(responseExchange.getProperty(SmnProperties.SERVICE_REQUEST_ID));
assertTrue(responseExchange.getProperty(SmnProperties.SERVICE_MESSAGE_ID).toString().length() > 0);
assertTrue(responseExchange.getProperty(SmnProperties.SERVICE_REQUEST_ID).toString().length() > 0);
}
}
| PublishTemplatedMessageFunctionalTest |
java | google__guava | android/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java | {
"start": 23441,
"end": 23901
} | interface ____ {
/**
* @return the {@link LockGraphNode} associated with this lock.
*/
LockGraphNode getLockGraphNode();
/**
* @return {@code true} if the current thread has acquired this lock.
*/
boolean isAcquiredByCurrentThread();
}
/**
* A {@code LockGraphNode} associated with each lock instance keeps track of the directed edges in
* the lock acquisition graph.
*/
private static final | CycleDetectingLock |
java | apache__logging-log4j2 | log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/util/RecyclerFactories.java | {
"start": 1420,
"end": 7685
} | class ____ {
private RecyclerFactories() {}
private static final String JCTOOLS_QUEUE_CLASS_SUPPLIER_PATH = "org.jctools.queues.MpmcArrayQueue.new";
private static final boolean JCTOOLS_QUEUE_CLASS_AVAILABLE = isJctoolsQueueClassAvailable();
private static boolean isJctoolsQueueClassAvailable() {
try {
final String className = JCTOOLS_QUEUE_CLASS_SUPPLIER_PATH.replaceAll("\\.new$", "");
LoaderUtil.loadClass(className);
return true;
} catch (final ClassNotFoundException ignored) {
return false;
}
}
public static RecyclerFactory ofSpec(final String recyclerFactorySpec) {
// Determine the default capacity.
final int defaultCapacity = Math.max(2 * Runtime.getRuntime().availableProcessors() + 1, 8);
// TLA-, MPMC-, or ABQ-based queueing factory -- if nothing is specified.
if (recyclerFactorySpec == null) {
if (Constants.ENABLE_THREADLOCALS) {
return ThreadLocalRecyclerFactory.getInstance();
} else {
final Supplier<Queue<Object>> queueSupplier = JCTOOLS_QUEUE_CLASS_AVAILABLE
? () -> new MpmcArrayQueue<>(defaultCapacity)
: () -> new ArrayBlockingQueue<>(defaultCapacity);
return new QueueingRecyclerFactory(queueSupplier);
}
}
// Is a dummy factory requested?
else if (recyclerFactorySpec.equals("dummy")) {
return DummyRecyclerFactory.getInstance();
}
// Is a TLA factory requested?
else if (recyclerFactorySpec.equals("threadLocal")) {
return ThreadLocalRecyclerFactory.getInstance();
}
// Is a queueing factory requested?
else if (recyclerFactorySpec.startsWith("queue")) {
return readQueueingRecyclerFactory(recyclerFactorySpec, defaultCapacity);
}
// Bogus input, bail out.
else {
throw new IllegalArgumentException("invalid recycler factory: " + recyclerFactorySpec);
}
}
private static RecyclerFactory readQueueingRecyclerFactory(
final String recyclerFactorySpec, final int defaultCapacity) {
// Parse the spec.
final String queueFactorySpec =
recyclerFactorySpec.substring("queue".length() + (recyclerFactorySpec.startsWith("queue:") ? 1 : 0));
final Map<String, StringParameterParser.Value> parsedValues = StringParameterParser.parse(
queueFactorySpec, new LinkedHashSet<>(Arrays.asList("supplier", "capacity")));
// Read the supplier path.
final StringParameterParser.Value supplierValue = parsedValues.get("supplier");
final String supplierPath;
if (supplierValue == null || supplierValue instanceof StringParameterParser.NullValue) {
supplierPath = JCTOOLS_QUEUE_CLASS_AVAILABLE
? JCTOOLS_QUEUE_CLASS_SUPPLIER_PATH
: "java.util.concurrent.ArrayBlockingQueue.new";
} else {
supplierPath = supplierValue.toString();
}
// Read the capacity.
final StringParameterParser.Value capacityValue = parsedValues.get("capacity");
final int capacity;
if (capacityValue == null || capacityValue instanceof StringParameterParser.NullValue) {
capacity = defaultCapacity;
} else {
try {
capacity = Integers.parseInt(capacityValue.toString());
} catch (final NumberFormatException error) {
throw new IllegalArgumentException(
"failed reading capacity in queueing recycler " + "factory: " + queueFactorySpec, error);
}
}
// Execute the read spec.
return createRecyclerFactory(queueFactorySpec, supplierPath, capacity);
}
private static RecyclerFactory createRecyclerFactory(
final String queueFactorySpec, final String supplierPath, final int capacity) {
final int supplierPathSplitterIndex = supplierPath.lastIndexOf('.');
if (supplierPathSplitterIndex < 0) {
throw new IllegalArgumentException("invalid supplier in queueing recycler factory: " + queueFactorySpec);
}
final String supplierClassName = supplierPath.substring(0, supplierPathSplitterIndex);
final String supplierMethodName = supplierPath.substring(supplierPathSplitterIndex + 1);
try {
final Class<?> supplierClass = LoaderUtil.loadClass(supplierClassName);
final Supplier<Queue<Object>> queueSupplier;
if ("new".equals(supplierMethodName)) {
final Constructor<?> supplierCtor = supplierClass.getDeclaredConstructor(int.class);
queueSupplier = () -> {
try {
@SuppressWarnings("unchecked")
final Queue<Object> typedQueue = (Queue<Object>) supplierCtor.newInstance(capacity);
return typedQueue;
} catch (final Exception error) {
throw new RuntimeException(
"recycler queue construction failed for factory: " + queueFactorySpec, error);
}
};
} else {
final Method supplierMethod = supplierClass.getMethod(supplierMethodName, int.class);
queueSupplier = () -> {
try {
@SuppressWarnings("unchecked")
final Queue<Object> typedQueue = (Queue<Object>) supplierMethod.invoke(null, capacity);
return typedQueue;
} catch (final Exception error) {
throw new RuntimeException(
"recycler queue construction failed for factory: " + queueFactorySpec, error);
}
};
}
return new QueueingRecyclerFactory(queueSupplier);
} catch (final Exception error) {
throw new RuntimeException("failed executing queueing recycler factory: " + queueFactorySpec, error);
}
}
}
| RecyclerFactories |
java | quarkusio__quarkus | extensions/amazon-lambda/deployment/src/test/java/io/quarkus/amazon/lambda/deployment/RequestHandlerJandexUtilTest.java | {
"start": 18462,
"end": 18543
} | class ____<T> extends BaseHandler<T, String> {
}
public static | MiddleHandler |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/RestResponse.java | {
"start": 1683,
"end": 20900
} | class ____<T> implements AutoCloseable {
/**
* Protected constructor, use one of the static methods to obtain a
* {@link ResponseBuilder} instance and obtain a RestResponse from that.
*/
protected RestResponse() {
}
/**
* Get the status code associated with the response.
*
* @return the response status code.
*/
public abstract int getStatus();
/**
* Get the complete status information associated with the response.
*
* @return the response status information. The returned value is never
* {@code null}.
*/
public abstract StatusType getStatusInfo();
/**
* Get the message entity Java instance. Returns {@code null} if the message
* does not contain an entity body.
* <p>
* If the entity is represented by an un-consumed {@link InputStream input stream}
* the method will return the input stream.
* </p>
*
* @return the message entity or {@code null} if message does not contain an
* entity body (i.e. when {@link #hasEntity()} returns {@code false}).
* @throws IllegalStateException if the entity was previously fully consumed
* as an {@link InputStream input stream}, or
* if the response has been {@link #close() closed}.
*/
public abstract T getEntity();
/**
* Read the message entity input stream as an instance of specified Java type
* using a {@link jakarta.ws.rs.ext.MessageBodyReader} that supports mapping the
* message entity stream onto the requested type.
* <p>
* Method throws an {@link ProcessingException} if the content of the
* message cannot be mapped to an entity of the requested type and
* {@link IllegalStateException} in case the entity is not backed by an input
* stream or if the original entity input stream has already been consumed
* without {@link #bufferEntity() buffering} the entity data prior consuming.
* </p>
* <p>
* A message instance returned from this method will be cached for
* subsequent retrievals via {@link #getEntity()}. Unless the supplied entity
* type is an {@link java.io.InputStream input stream}, this method automatically
* {@link #close() closes} the an unconsumed original response entity data stream
* if open. In case the entity data has been buffered, the buffer will be reset
* prior consuming the buffered data to enable subsequent invocations of
* {@code readEntity(...)} methods on this response.
* </p>
*
* @param <OtherT> entity instance Java type.
* @param entityType the type of entity.
* @return the message entity; for a zero-length response entities returns a corresponding
* Java object that represents zero-length data. In case no zero-length representation
* is defined for the Java type, a {@link ProcessingException} wrapping the
* underlying {@link NoContentException} is thrown.
* @throws ProcessingException if the content of the message cannot be
* mapped to an entity of the requested type.
* @throws IllegalStateException if the entity is not backed by an input stream,
* the response has been {@link #close() closed} already,
* or if the entity input stream has been fully consumed already and has
* not been buffered prior consuming.
* @see jakarta.ws.rs.ext.MessageBodyReader
*/
public abstract <OtherT> OtherT readEntity(Class<OtherT> entityType);
/**
* Read the message entity input stream as an instance of specified Java type
* using a {@link jakarta.ws.rs.ext.MessageBodyReader} that supports mapping the
* message entity stream onto the requested type.
* <p>
* Method throws an {@link ProcessingException} if the content of the
* message cannot be mapped to an entity of the requested type and
* {@link IllegalStateException} in case the entity is not backed by an input
* stream or if the original entity input stream has already been consumed
* without {@link #bufferEntity() buffering} the entity data prior consuming.
* </p>
* <p>
* A message instance returned from this method will be cached for
* subsequent retrievals via {@link #getEntity()}. Unless the supplied entity
* type is an {@link java.io.InputStream input stream}, this method automatically
* {@link #close() closes} the an unconsumed original response entity data stream
* if open. In case the entity data has been buffered, the buffer will be reset
* prior consuming the buffered data to enable subsequent invocations of
* {@code readEntity(...)} methods on this response.
* </p>
*
* @param <OtherT> entity instance Java type.
* @param entityType the type of entity; may be generic.
* @return the message entity; for a zero-length response entities returns a corresponding
* Java object that represents zero-length data. In case no zero-length representation
* is defined for the Java type, a {@link ProcessingException} wrapping the
* underlying {@link NoContentException} is thrown.
* @throws ProcessingException if the content of the message cannot be
* mapped to an entity of the requested type.
* @throws IllegalStateException if the entity is not backed by an input stream,
* the response has been {@link #close() closed} already,
* or if the entity input stream has been fully consumed already and has
* not been buffered prior consuming.
* @see jakarta.ws.rs.ext.MessageBodyReader
*/
public abstract <OtherT> OtherT readEntity(GenericType<OtherT> entityType);
/**
* Read the message entity input stream as an instance of specified Java type
* using a {@link jakarta.ws.rs.ext.MessageBodyReader} that supports mapping the
* message entity stream onto the requested type.
* <p>
* Method throws an {@link ProcessingException} if the content of the
* message cannot be mapped to an entity of the requested type and
* {@link IllegalStateException} in case the entity is not backed by an input
* stream or if the original entity input stream has already been consumed
* without {@link #bufferEntity() buffering} the entity data prior consuming.
* </p>
* <p>
* A message instance returned from this method will be cached for
* subsequent retrievals via {@link #getEntity()}. Unless the supplied entity
* type is an {@link java.io.InputStream input stream}, this method automatically
* {@link #close() closes} the an unconsumed original response entity data stream
* if open. In case the entity data has been buffered, the buffer will be reset
* prior consuming the buffered data to enable subsequent invocations of
* {@code readEntity(...)} methods on this response.
* </p>
*
* @param <OtherT> entity instance Java type.
* @param entityType the type of entity.
* @param annotations annotations that will be passed to the {@link MessageBodyReader}.
* @return the message entity; for a zero-length response entities returns a corresponding
* Java object that represents zero-length data. In case no zero-length representation
* is defined for the Java type, a {@link ProcessingException} wrapping the
* underlying {@link NoContentException} is thrown.
* @throws ProcessingException if the content of the message cannot be
* mapped to an entity of the requested type.
* @throws IllegalStateException if the entity is not backed by an input stream,
* the response has been {@link #close() closed} already,
* or if the entity input stream has been fully consumed already and has
* not been buffered prior consuming.
* @see jakarta.ws.rs.ext.MessageBodyReader
*/
public abstract <OtherT> OtherT readEntity(Class<OtherT> entityType, Annotation[] annotations);
/**
* Read the message entity input stream as an instance of specified Java type
* using a {@link jakarta.ws.rs.ext.MessageBodyReader} that supports mapping the
* message entity stream onto the requested type.
* <p>
* Method throws an {@link ProcessingException} if the content of the
* message cannot be mapped to an entity of the requested type and
* {@link IllegalStateException} in case the entity is not backed by an input
* stream or if the original entity input stream has already been consumed
* without {@link #bufferEntity() buffering} the entity data prior consuming.
* </p>
* <p>
* A message instance returned from this method will be cached for
* subsequent retrievals via {@link #getEntity()}. Unless the supplied entity
* type is an {@link java.io.InputStream input stream}, this method automatically
* {@link #close() closes} the an unconsumed original response entity data stream
* if open. In case the entity data has been buffered, the buffer will be reset
* prior consuming the buffered data to enable subsequent invocations of
* {@code readEntity(...)} methods on this response.
* </p>
*
* @param <OtherT> entity instance Java type.
* @param entityType the type of entity; may be generic.
* @param annotations annotations that will be passed to the {@link MessageBodyReader}.
* @return the message entity; for a zero-length response entities returns a corresponding
* Java object that represents zero-length data. In case no zero-length representation
* is defined for the Java type, a {@link ProcessingException} wrapping the
* underlying {@link NoContentException} is thrown.
* @throws ProcessingException if the content of the message cannot be
* mapped to an entity of the requested type.
* @throws IllegalStateException if the entity is not backed by an input stream,
* the response has been {@link #close() closed} already,
* or if the entity input stream has been fully consumed already and has
* not been buffered prior consuming.
* @see jakarta.ws.rs.ext.MessageBodyReader
*/
public abstract <OtherT> OtherT readEntity(GenericType<OtherT> entityType, Annotation[] annotations);
/**
* Check if there is an entity available in the response. The method returns
* {@code true} if the entity is present, returns {@code false} otherwise.
* <p>
* Note that the method may return {@code true} also for response messages with
* a zero-length content, in case the <code>{@value jakarta.ws.rs.core.HttpHeaders#CONTENT_LENGTH}</code> and
* <code>{@value jakarta.ws.rs.core.HttpHeaders#CONTENT_TYPE}</code> headers are specified in the message.
* In such case, an attempt to read the entity using one of the {@code readEntity(...)}
* methods will return a corresponding instance representing a zero-length entity for a
* given Java type or produce a {@link ProcessingException} in case no such instance
* is available for the Java type.
* </p>
*
* @return {@code true} if there is an entity present in the message,
* {@code false} otherwise.
* @throws IllegalStateException in case the response has been {@link #close() closed}.
*/
public abstract boolean hasEntity();
/**
* Buffer the message entity data.
* <p>
* In case the message entity is backed by an unconsumed entity input stream,
* all the bytes of the original entity input stream are read and stored in a
* local buffer. The original entity input stream is consumed and automatically
* closed as part of the operation and the method returns {@code true}.
* </p>
* <p>
* In case the response entity instance is not backed by an unconsumed input stream
* an invocation of {@code bufferEntity} method is ignored and the method returns
* {@code false}.
* </p>
* <p>
* This operation is idempotent, i.e. it can be invoked multiple times with
* the same effect which also means that calling the {@code bufferEntity()}
* method on an already buffered (and thus closed) message instance is legal
* and has no further effect. Also, the result returned by the {@code bufferEntity()}
* method is consistent across all invocations of the method on the same
* {@code RestResponse} instance.
* </p>
* <p>
* Buffering the message entity data allows for multiple invocations of
* {@code readEntity(...)} methods on the response instance. Note however, that
* once the response instance itself is {@link #close() closed}, the implementations
* are expected to release the buffered message entity data too. Therefore any subsequent
* attempts to read a message entity stream on such closed response will result in an
* {@link IllegalStateException} being thrown.
* </p>
*
* @return {@code true} if the message entity input stream was available and
* was buffered successfully, returns {@code false} if the entity stream
* was not available.
* @throws ProcessingException if there was an error while buffering the entity
* input stream.
* @throws IllegalStateException in case the response has been {@link #close() closed}.
*/
public abstract boolean bufferEntity();
/**
* Close the underlying message entity input stream (if available and open)
* as well as releases any other resources associated with the response
* (e.g. {@link #bufferEntity() buffered message entity data}).
* <p>
* This operation is idempotent, i.e. it can be invoked multiple times with the
* same effect which also means that calling the {@code close()} method on an
* already closed message instance is legal and has no further effect.
* </p>
* <p>
* The {@code close()} method should be invoked on all instances that
* contain an un-consumed entity input stream to ensure the resources associated
* with the instance are properly cleaned-up and prevent potential memory leaks.
* This is typical for client-side scenarios where application layer code
* processes only the response headers and ignores the response entity.
* </p>
* <p>
* Any attempts to manipulate (read, get, buffer) a message entity on a closed response
* will result in an {@link IllegalStateException} being thrown.
* </p>
*
* @throws ProcessingException if there is an error closing the response.
*/
@Override
public abstract void close();
/**
* Get the media type of the message entity.
*
* @return the media type or {@code null} if there is no response entity.
*/
public abstract MediaType getMediaType();
/**
* Get the language of the message entity.
*
* @return the language of the entity or null if not specified.
*/
public abstract Locale getLanguage();
/**
* Get Content-Length value.
*
* @return Content-Length as integer if present and valid number. In other
* cases returns {@code -1}.
*/
public abstract int getLength();
/**
* Get the allowed HTTP methods from the Allow HTTP header.
*
* @return the allowed HTTP methods, all methods will returned as upper case
* strings.
*/
public abstract Set<String> getAllowedMethods();
/**
* Get any new cookies set on the response message.
*
* @return a read-only map of cookie name (String) to Cookie.
*/
public abstract Map<String, NewCookie> getCookies();
/**
* Get the entity tag.
*
* @return the entity tag, otherwise {@code null} if not present.
*/
public abstract EntityTag getEntityTag();
/**
* Get message date.
*
* @return the message date, otherwise {@code null} if not present.
*/
public abstract Date getDate();
/**
* Get the last modified date.
*
* @return the last modified date, otherwise {@code null} if not present.
*/
public abstract Date getLastModified();
/**
* Get the location.
*
* @return the location URI, otherwise {@code null} if not present.
*/
public abstract URI getLocation();
/**
* Get the links attached to the message as headers. Any links in the message
* that are relative must be resolved with respect to the actual request URI
* that produced this response. Note that request URIs may be updated by
* filters, so the actual request URI may differ from that in the original
* invocation.
*
* @return links, may return empty {@link Set} if no links are present. Does
* not return {@code null}.
*/
public abstract Set<Link> getLinks();
/**
* Check if link for relation exists.
*
* @param relation link relation.
* @return {@code true} if the link for the relation is present in the
* {@link #getHeaders() message headers}, {@code false} otherwise.
*/
public abstract boolean hasLink(String relation);
/**
* Get the link for the relation. A relative link is resolved with respect
* to the actual request URI that produced this response. Note that request
* URIs may be updated by filters, so the actual request URI may differ from
* that in the original invocation.
*
* @param relation link relation.
* @return the link for the relation, otherwise {@code null} if not present.
*/
public abstract Link getLink(String relation);
/**
* Convenience method that returns a {@link Link.Builder} for the relation.
* See {@link #getLink} for more information.
*
* @param relation link relation.
* @return the link builder for the relation, otherwise {@code null} if not
* present.
*/
public abstract Link.Builder getLinkBuilder(String relation);
/**
* See {@link #getHeaders()}.
*
* This method is considered deprecated. Users are encouraged to switch their
* code to use the {@code getHeaders()} method instead. The method may be annotated
* as {@link Deprecated @Deprecated} in a future release of the API.
*
* @return response headers as a multivalued map.
*/
public abstract MultivaluedMap<String, Object> getMetadata();
/**
* Get view of the response headers and their object values.
*
* The underlying header data may be subsequently modified by the runtime on the
* server side. Changes in the underlying header data are reflected in this view.
* <p>
* On the server-side, when the message is sent, the non-string values will be serialized
* using a {@link jakarta.ws.rs.ext.RuntimeDelegate.HeaderDelegate} if one is available via
* {@link jakarta.ws.rs.ext.RuntimeDelegate#createHeaderDelegate(java.lang.Class)} for the
* | RestResponse |
java | spring-projects__spring-framework | spring-context/src/testFixtures/java/org/springframework/context/testfixture/jndi/SimpleNamingContextBuilder.java | {
"start": 8439,
"end": 8918
} | class ____ not implement [" + InitialContextFactory.class.getName() + "]: " + icf);
}
try {
return (InitialContextFactory) ReflectionUtils.accessibleConstructor(icfClass).newInstance();
}
catch (Throwable ex) {
throw new IllegalStateException("Unable to instantiate specified InitialContextFactory: " + icf, ex);
}
}
}
// Default case...
return env -> new SimpleNamingContext("", this.boundObjects, (Hashtable<String, Object>) env);
}
}
| does |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/api/RecursiveAssertionAssert.java | {
"start": 11764,
"end": 11882
} | class ____ {
* String name;
* String occupation;
* Address address = new Address();
* }
*
* | Person |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/RLESparseResourceAllocation.java | {
"start": 17306,
"end": 19201
} | enum ____ {
add, subtract, min, max, subtractTestNonNegative
}
/**
* Get the maximum capacity across specified time instances. The search-space
* is specified using the starting value, tick, and the periodic interval for
* search. Maximum resource allocation across tick, tick + period, tick + 2 *
* period,..., tick + n * period .. is returned.
*
* @param tick the starting time instance
* @param period interval at which capacity is evaluated
* @return maximum resource allocation
*/
public Resource getMaximumPeriodicCapacity(long tick, long period) {
Resource maxCapacity = ZERO_RESOURCE;
readLock.lock();
try {
if (!cumulativeCapacity.isEmpty()) {
Long lastKey = cumulativeCapacity.lastKey();
for (long t = tick; t <= lastKey; t = t + period) {
maxCapacity = Resources.componentwiseMax(maxCapacity,
cumulativeCapacity.floorEntry(t).getValue());
}
}
return maxCapacity;
} finally {
readLock.unlock();
}
}
/**
* Get the minimum capacity in the specified time range.
*
* @param interval the {@link ReservationInterval} to be searched
* @return minimum resource allocation
*/
public Resource getMinimumCapacityInInterval(ReservationInterval interval) {
Resource minCapacity =
Resource.newInstance(Integer.MAX_VALUE, Integer.MAX_VALUE);
long start = interval.getStartTime();
long end = interval.getEndTime();
NavigableMap<Long, Resource> capacityRange =
getRangeOverlapping(start, end).getCumulative();
if (!capacityRange.isEmpty()) {
for (Map.Entry<Long, Resource> entry : capacityRange.entrySet()) {
if (entry.getValue() != null) {
minCapacity =
Resources.componentwiseMin(minCapacity, entry.getValue());
}
}
}
return minCapacity;
}
}
| RLEOperator |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/aggregations/pipeline/ExtendedStatsBucketTests.java | {
"start": 1075,
"end": 3871
} | class ____ extends AbstractBucketMetricsTestCase<ExtendedStatsBucketPipelineAggregationBuilder> {
@Override
protected ExtendedStatsBucketPipelineAggregationBuilder doCreateTestAggregatorFactory(String name, String bucketsPath) {
ExtendedStatsBucketPipelineAggregationBuilder factory = new ExtendedStatsBucketPipelineAggregationBuilder(name, bucketsPath);
if (randomBoolean()) {
factory.sigma(randomDoubleBetween(0.0, 10.0, false));
}
return factory;
}
public void testSigmaFromInt() throws Exception {
XContentBuilder content = XContentFactory.jsonBuilder()
.startObject()
.startObject("name")
.startObject("extended_stats_bucket")
.field("sigma", 5)
.field("buckets_path", "test")
.endObject()
.endObject()
.endObject();
ExtendedStatsBucketPipelineAggregationBuilder builder = (ExtendedStatsBucketPipelineAggregationBuilder) parse(
createParser(content)
);
assertThat(builder.sigma(), equalTo(5.0));
}
public void testValidate() {
AggregationBuilder singleBucketAgg = new GlobalAggregationBuilder("global");
AggregationBuilder multiBucketAgg = new TermsAggregationBuilder("terms").userValueTypeHint(ValueType.STRING);
final Set<AggregationBuilder> aggBuilders = new HashSet<>();
aggBuilders.add(singleBucketAgg);
aggBuilders.add(multiBucketAgg);
// First try to point to a non-existent agg
assertThat(
validate(aggBuilders, new ExtendedStatsBucketPipelineAggregationBuilder("name", "invalid_agg>metric")),
equalTo(
"Validation Failed: 1: "
+ PipelineAggregator.Parser.BUCKETS_PATH.getPreferredName()
+ " aggregation does not exist for aggregation [name]: invalid_agg>metric;"
)
);
// Now try to point to a single bucket agg
assertThat(
validate(aggBuilders, new ExtendedStatsBucketPipelineAggregationBuilder("name", "global>metric")),
equalTo(
"Validation Failed: 1: Unable to find unqualified multi-bucket aggregation in "
+ PipelineAggregator.Parser.BUCKETS_PATH.getPreferredName()
+ ". Path must include a multi-bucket aggregation for aggregation [name] found :"
+ GlobalAggregationBuilder.class.getName()
+ " for buckets path: global>metric;"
)
);
// Now try to point to a valid multi-bucket agg
assertThat(validate(aggBuilders, new ExtendedStatsBucketPipelineAggregationBuilder("name", "terms>metric")), nullValue());
}
}
| ExtendedStatsBucketTests |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LanguageEndpointBuilderFactory.java | {
"start": 8114,
"end": 13014
} | interface ____
extends
EndpointProducerBuilder {
default LanguageEndpointBuilder basic() {
return (LanguageEndpointBuilder) this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedLanguageEndpointBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedLanguageEndpointBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the script is binary content or text content. By default the
* script is read as text content (eg java.lang.String).
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param binary the value to set
* @return the dsl builder
*/
default AdvancedLanguageEndpointBuilder binary(boolean binary) {
doSetProperty("binary", binary);
return this;
}
/**
* Whether the script is binary content or text content. By default the
* script is read as text content (eg java.lang.String).
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param binary the value to set
* @return the dsl builder
*/
default AdvancedLanguageEndpointBuilder binary(String binary) {
doSetProperty("binary", binary);
return this;
}
/**
* Whether to cache the compiled script and reuse Notice reusing the
* script can cause side effects from processing one Camel
* org.apache.camel.Exchange to the next org.apache.camel.Exchange.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param cacheScript the value to set
* @return the dsl builder
*/
default AdvancedLanguageEndpointBuilder cacheScript(boolean cacheScript) {
doSetProperty("cacheScript", cacheScript);
return this;
}
/**
* Whether to cache the compiled script and reuse Notice reusing the
* script can cause side effects from processing one Camel
* org.apache.camel.Exchange to the next org.apache.camel.Exchange.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param cacheScript the value to set
* @return the dsl builder
*/
default AdvancedLanguageEndpointBuilder cacheScript(String cacheScript) {
doSetProperty("cacheScript", cacheScript);
return this;
}
}
public | AdvancedLanguageEndpointBuilder |
java | google__guava | android/guava/src/com/google/common/collect/MultimapBuilder.java | {
"start": 10210,
"end": 16645
} | class ____<K0 extends @Nullable Object> {
private static final int DEFAULT_EXPECTED_VALUES_PER_KEY = 2;
MultimapBuilderWithKeys() {}
abstract <K extends K0, V extends @Nullable Object> Map<K, Collection<V>> createMap();
/** Uses an {@link ArrayList} to store value collections. */
public ListMultimapBuilder<K0, @Nullable Object> arrayListValues() {
return arrayListValues(DEFAULT_EXPECTED_VALUES_PER_KEY);
}
/**
* Uses an {@link ArrayList} to store value collections, initialized to expect the specified
* number of values per key.
*
* @throws IllegalArgumentException if {@code expectedValuesPerKey < 0}
*/
public ListMultimapBuilder<K0, @Nullable Object> arrayListValues(int expectedValuesPerKey) {
checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey");
return new ListMultimapBuilder<K0, @Nullable Object>() {
@Override
public <K extends K0, V extends @Nullable Object> ListMultimap<K, V> build() {
return Multimaps.newListMultimap(
MultimapBuilderWithKeys.this.createMap(),
new ArrayListSupplier<V>(expectedValuesPerKey));
}
};
}
/**
* Uses a {@link LinkedList} to store value collections.
*
* <p><b>Performance note:</b> {@link ArrayList} and {@link java.util.ArrayDeque} consistently
* outperform {@code LinkedList} except in certain rare and specific situations. Unless you have
* spent a lot of time benchmarking your specific needs, use one of those instead. (However, we
* do not currently offer a {@link Multimap} implementation based on {@link
* java.util.ArrayDeque}.)
*/
public ListMultimapBuilder<K0, @Nullable Object> linkedListValues() {
return new ListMultimapBuilder<K0, @Nullable Object>() {
@Override
public <K extends K0, V extends @Nullable Object> ListMultimap<K, V> build() {
return Multimaps.newListMultimap(
MultimapBuilderWithKeys.this.createMap(), LinkedListSupplier.instance());
}
};
}
/** Uses a hash-based {@code Set} to store value collections. */
public SetMultimapBuilder<K0, @Nullable Object> hashSetValues() {
return hashSetValues(DEFAULT_EXPECTED_VALUES_PER_KEY);
}
/**
* Uses a hash-based {@code Set} to store value collections, initialized to expect the specified
* number of values per key.
*
* @throws IllegalArgumentException if {@code expectedValuesPerKey < 0}
*/
public SetMultimapBuilder<K0, @Nullable Object> hashSetValues(int expectedValuesPerKey) {
checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey");
return new SetMultimapBuilder<K0, @Nullable Object>() {
@Override
public <K extends K0, V extends @Nullable Object> SetMultimap<K, V> build() {
return Multimaps.newSetMultimap(
MultimapBuilderWithKeys.this.createMap(),
new HashSetSupplier<V>(expectedValuesPerKey));
}
};
}
/** Uses an insertion-ordered hash-based {@code Set} to store value collections. */
public SetMultimapBuilder<K0, @Nullable Object> linkedHashSetValues() {
return linkedHashSetValues(DEFAULT_EXPECTED_VALUES_PER_KEY);
}
/**
* Uses an insertion-ordered hash-based {@code Set} to store value collections, initialized to
* expect the specified number of values per key.
*
* @throws IllegalArgumentException if {@code expectedValuesPerKey < 0}
*/
public SetMultimapBuilder<K0, @Nullable Object> linkedHashSetValues(int expectedValuesPerKey) {
checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey");
return new SetMultimapBuilder<K0, @Nullable Object>() {
@Override
public <K extends K0, V extends @Nullable Object> SetMultimap<K, V> build() {
return Multimaps.newSetMultimap(
MultimapBuilderWithKeys.this.createMap(),
new LinkedHashSetSupplier<V>(expectedValuesPerKey));
}
};
}
/** Uses a naturally-ordered {@link TreeSet} to store value collections. */
@SuppressWarnings("rawtypes")
public SortedSetMultimapBuilder<K0, Comparable> treeSetValues() {
return treeSetValues(Ordering.natural());
}
/**
* Uses a {@link TreeSet} ordered by the specified comparator to store value collections.
*
* <p>Multimaps generated by the resulting builder will not be serializable if {@code
* comparator} is not serializable.
*/
public <V0 extends @Nullable Object> SortedSetMultimapBuilder<K0, V0> treeSetValues(
Comparator<V0> comparator) {
checkNotNull(comparator, "comparator");
return new SortedSetMultimapBuilder<K0, V0>() {
@Override
public <K extends K0, V extends V0> SortedSetMultimap<K, V> build() {
return Multimaps.newSortedSetMultimap(
MultimapBuilderWithKeys.this.createMap(), new TreeSetSupplier<V>(comparator));
}
};
}
/** Uses an {@link EnumSet} to store value collections. */
public <V0 extends Enum<V0>> SetMultimapBuilder<K0, V0> enumSetValues(Class<V0> valueClass) {
checkNotNull(valueClass, "valueClass");
return new SetMultimapBuilder<K0, V0>() {
@Override
public <K extends K0, V extends V0> SetMultimap<K, V> build() {
// V must actually be V0, since enums are effectively final
// (their subclasses are inaccessible)
@SuppressWarnings({"unchecked", "rawtypes"})
Supplier<Set<V>> factory = (Supplier) new EnumSetSupplier<V0>(valueClass);
return Multimaps.newSetMultimap(MultimapBuilderWithKeys.this.createMap(), factory);
}
};
}
}
/** Returns a new, empty {@code Multimap} with the specified implementation. */
public abstract <K extends K0, V extends V0> Multimap<K, V> build();
/**
* Returns a {@code Multimap} with the specified implementation, initialized with the entries of
* {@code multimap}.
*/
public <K extends K0, V extends V0> Multimap<K, V> build(
Multimap<? extends K, ? extends V> multimap) {
Multimap<K, V> result = build();
result.putAll(multimap);
return result;
}
/**
* A specialization of {@link MultimapBuilder} that generates {@link ListMultimap} instances.
*
* @since 16.0
*/
public abstract static | MultimapBuilderWithKeys |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/event/EagerTestExecutionEventPublishingTests.java | {
"start": 4426,
"end": 4489
} | class ____ {
@Test
void test() {
}
}
static | LazyTestCase1 |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/table/AsyncMLPredictITCase.java | {
"start": 2021,
"end": 13050
} | class ____ extends StreamingWithStateTestBase {
private final Boolean objectReuse;
private final ExecutionConfigOptions.AsyncOutputMode asyncOutputMode;
public AsyncMLPredictITCase(
StateBackendMode backend,
Boolean objectReuse,
ExecutionConfigOptions.AsyncOutputMode asyncOutputMode) {
super(backend);
this.objectReuse = objectReuse;
this.asyncOutputMode = asyncOutputMode;
}
private final List<Row> data =
Arrays.asList(
Row.of(1L, 12, "Julian"),
Row.of(2L, 15, "Hello"),
Row.of(3L, 15, "Fabian"),
Row.of(8L, 11, "Hello world"),
Row.of(9L, 12, "Hello world!"));
private final List<Row> dataWithNull =
Arrays.asList(
Row.of(15L, null, "Hello"),
Row.of(3L, 15, "Fabian"),
Row.of(11L, null, "Hello world"),
Row.of(9L, 12, "Hello world!"));
private final Map<Row, List<Row>> id2features = new HashMap<>();
{
id2features.put(Row.of(1L), Collections.singletonList(Row.of("x1", 1, "z1")));
id2features.put(Row.of(2L), Collections.singletonList(Row.of("x2", 2, "z2")));
id2features.put(Row.of(3L), Collections.singletonList(Row.of("x3", 3, "z3")));
id2features.put(Row.of(8L), Collections.singletonList(Row.of("x8", 8, "z8")));
id2features.put(Row.of(9L), Collections.singletonList(Row.of("x9", 9, "z9")));
}
private final Map<Row, List<Row>> idLen2features = new HashMap<>();
{
idLen2features.put(
Row.of(15L, null), Collections.singletonList(Row.of("x1", 1, "zNull15")));
idLen2features.put(Row.of(15L, 15), Collections.singletonList(Row.of("x1", 1, "z1515")));
idLen2features.put(Row.of(3L, 15), Collections.singletonList(Row.of("x2", 2, "z315")));
idLen2features.put(
Row.of(11L, null), Collections.singletonList(Row.of("x3", 3, "zNull11")));
idLen2features.put(Row.of(11L, 11), Collections.singletonList(Row.of("x3", 3, "z1111")));
idLen2features.put(Row.of(9L, 12), Collections.singletonList(Row.of("x8", 8, "z912")));
idLen2features.put(Row.of(12L, 12), Collections.singletonList(Row.of("x8", 8, "z1212")));
}
private final Map<Row, List<Row>> content2vector = new HashMap<>();
{
content2vector.put(
Row.of("Julian"),
Collections.singletonList(Row.of((Object) new Float[] {1.0f, 2.0f, 3.0f})));
content2vector.put(
Row.of("Hello"),
Collections.singletonList(Row.of((Object) new Float[] {2.0f, 3.0f, 4.0f})));
content2vector.put(
Row.of("Fabian"),
Collections.singletonList(Row.of((Object) new Float[] {3.0f, 4.0f, 5.0f})));
content2vector.put(
Row.of("Hello world"),
Collections.singletonList(Row.of((Object) new Float[] {4.0f, 5.0f, 6.0f})));
content2vector.put(
Row.of("Hello world!"),
Collections.singletonList(Row.of((Object) new Float[] {5.0f, 6.0f, 7.0f})));
}
@BeforeEach
public void before() {
super.before();
if (objectReuse) {
env().getConfig().enableObjectReuse();
} else {
env().getConfig().disableObjectReuse();
}
tEnv().getConfig()
.set(
ExecutionConfigOptions.TABLE_EXEC_ASYNC_ML_PREDICT_OUTPUT_MODE,
asyncOutputMode);
createScanTable("src", data);
createScanTable("nullable_src", dataWithNull);
tEnv().executeSql(
String.format(
"CREATE MODEL m1\n"
+ "INPUT (a BIGINT)\n"
+ "OUTPUT (x STRING, y INT, z STRING)\n"
+ "WITH (\n"
+ " 'provider' = 'values',"
+ " 'async' = 'true',"
+ " 'data-id' = '%s'"
+ ")",
TestValuesModelFactory.registerData(id2features)));
tEnv().executeSql(
String.format(
"CREATE MODEL m2\n"
+ "INPUT (a BIGINT, b INT)\n"
+ "OUTPUT (x STRING, y INT, z STRING)\n"
+ "WITH (\n"
+ " 'provider' = 'values',"
+ " 'async' = 'true',"
+ " 'data-id' = '%s'"
+ ")",
TestValuesModelFactory.registerData(idLen2features)));
tEnv().executeSql(
String.format(
"CREATE MODEL m3\n"
+ "INPUT (content STRING)\n"
+ "OUTPUT (vector ARRAY<FLOAT>)\n"
+ "WITH (\n"
+ " 'provider' = 'values',"
+ " 'data-id' = '%s',"
+ " 'latency' = '1000',"
+ " 'async' = 'true'"
+ ")",
TestValuesModelFactory.registerData(content2vector)));
}
@TestTemplate
public void testAsyncMLPredict() {
assertThatList(
CollectionUtil.iteratorToList(
tEnv().executeSql(
"SELECT id, z FROM ML_PREDICT(TABLE src, MODEL m1, DESCRIPTOR(`id`))")
.collect()))
.containsExactlyInAnyOrder(
Row.of(1L, "z1"),
Row.of(2L, "z2"),
Row.of(3L, "z3"),
Row.of(8L, "z8"),
Row.of(9L, "z9"));
}
@TestTemplate
public void testAsyncMLPredictWithMultipleFields() {
assertThatList(
CollectionUtil.iteratorToList(
tEnv().executeSql(
"SELECT id, len, z FROM ML_PREDICT(TABLE nullable_src, MODEL m2, DESCRIPTOR(`id`, `len`))")
.collect()))
.containsExactlyInAnyOrder(
Row.of(3L, 15, "z315"),
Row.of(9L, 12, "z912"),
Row.of(11L, null, "zNull11"),
Row.of(15L, null, "zNull15"));
}
@TestTemplate
public void testAsyncMLPredictWithConstantValues() {
assertThatList(
CollectionUtil.iteratorToList(
tEnv().executeSql(
"WITH v(id) AS (SELECT * FROM (VALUES (CAST(1 AS BIGINT)), (CAST(2 AS BIGINT)))) "
+ "SELECT * FROM ML_PREDICT(INPUT => TABLE v, MODEL => MODEL `m1`, ARGS => DESCRIPTOR(`id`))")
.collect()))
.containsExactlyInAnyOrder(Row.of(1L, "x1", 1, "z1"), Row.of(2L, "x2", 2, "z2"));
}
@TestTemplate
public void testAsyncPredictWithRuntimeConfig() {
assertThatThrownBy(
() ->
tEnv().executeSql(
"SELECT id, vector FROM ML_PREDICT(TABLE src, MODEL m3, DESCRIPTOR(`content`), MAP['timeout', '1ms'])")
.await())
.satisfies(
FlinkAssertions.anyCauseMatches(
TimeoutException.class, "Async function call has timed out."));
}
private void createScanTable(String tableName, List<Row> data) {
String dataId = TestValuesTableFactory.registerData(data);
tEnv().executeSql(
String.format(
"CREATE TABLE `%s`(\n"
+ " id BIGINT,"
+ " len INT,"
+ " content STRING,"
+ " PRIMARY KEY (`id`) NOT ENFORCED"
+ ") WITH ("
+ " 'connector' = 'values',"
+ " 'data-id' = '%s'"
+ ")",
tableName, dataId));
}
@Parameters(name = "backend = {0}, objectReuse = {1}, asyncOutputMode = {2}")
public static Collection<Object[]> parameters() {
return Arrays.asList(
new Object[][] {
{
StreamingWithStateTestBase.HEAP_BACKEND(),
true,
ExecutionConfigOptions.AsyncOutputMode.ALLOW_UNORDERED
},
{
StreamingWithStateTestBase.HEAP_BACKEND(),
true,
ExecutionConfigOptions.AsyncOutputMode.ORDERED
},
{
StreamingWithStateTestBase.HEAP_BACKEND(),
false,
ExecutionConfigOptions.AsyncOutputMode.ALLOW_UNORDERED
},
{
StreamingWithStateTestBase.HEAP_BACKEND(),
false,
ExecutionConfigOptions.AsyncOutputMode.ORDERED
},
{
StreamingWithStateTestBase.ROCKSDB_BACKEND(),
true,
ExecutionConfigOptions.AsyncOutputMode.ALLOW_UNORDERED
},
{
StreamingWithStateTestBase.ROCKSDB_BACKEND(),
true,
ExecutionConfigOptions.AsyncOutputMode.ORDERED
},
{
StreamingWithStateTestBase.ROCKSDB_BACKEND(),
false,
ExecutionConfigOptions.AsyncOutputMode.ALLOW_UNORDERED
},
{
StreamingWithStateTestBase.ROCKSDB_BACKEND(),
false,
ExecutionConfigOptions.AsyncOutputMode.ORDERED
}
});
}
}
| AsyncMLPredictITCase |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3953AuthenticatedDeploymentTest.java | {
"start": 1942,
"end": 5577
} | class ____ extends AbstractMavenIntegrationTestCase {
private Server server;
private int port;
private volatile boolean deployed;
@BeforeEach
protected void setUp() throws Exception {
Handler repoHandler = new AbstractHandler() {
@Override
public void handle(
String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) {
System.out.println("Handling " + request.getMethod() + " " + request.getRequestURL());
if ("PUT".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
deployed = true;
} else {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
((Request) request).setHandled(true);
}
};
Constraint constraint = new Constraint();
constraint.setName(Constraint.__BASIC_AUTH);
constraint.setRoles(new String[] {"deployer"});
constraint.setAuthenticate(true);
ConstraintMapping constraintMapping = new ConstraintMapping();
constraintMapping.setConstraint(constraint);
constraintMapping.setPathSpec("/*");
HashLoginService userRealm = new HashLoginService("TestRealm");
UserStore userStore = new UserStore();
userStore.addUser("testuser", new Password("testtest"), new String[] {"deployer"});
userRealm.setUserStore(userStore);
server = new Server(0);
ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
securityHandler.setLoginService(userRealm);
securityHandler.setAuthMethod(__BASIC_AUTH);
securityHandler.setConstraintMappings(new ConstraintMapping[] {constraintMapping});
HandlerList handlerList = new HandlerList();
handlerList.addHandler(securityHandler);
handlerList.addHandler(repoHandler);
server.setHandler(handlerList);
server.start();
if (server.isFailed()) {
fail("Couldn't bind the server socket to a free port!");
}
port = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
System.out.println("Bound server socket to the port " + port);
deployed = false;
}
@AfterEach
protected void tearDown() throws Exception {
if (server != null) {
server.stop();
server.join();
}
}
/**
* Test that deployment (of a release) to a repository that requires authentification works.
*
* @throws Exception in case of failure
*/
@Test
public void testitRelease() throws Exception {
testitMNG3953("release");
}
/**
* Test that deployment (of a snapshot) to a repository that requires authentification works.
*
* @throws Exception in case of failure
*/
@Test
public void testitSnapshot() throws Exception {
testitMNG3953("snapshot");
}
private void testitMNG3953(String project) throws Exception {
File testDir = extractResources("/mng-3953/" + project);
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.addCliArgument("--settings");
verifier.addCliArgument("settings.xml");
verifier.addCliArgument("-DdeploymentPort=" + port);
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
assertTrue(deployed);
}
}
| MavenITmng3953AuthenticatedDeploymentTest |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportWithConditionTests.java | {
"start": 1384,
"end": 2147
} | class ____ {
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
@Test
void conditionalThenUnconditional() {
this.context.register(ConditionalThenUnconditional.class);
this.context.refresh();
assertThat(this.context.containsBean("beanTwo")).isFalse();
assertThat(this.context.containsBean("beanOne")).isTrue();
}
@Test
void unconditionalThenConditional() {
this.context.register(UnconditionalThenConditional.class);
this.context.refresh();
assertThat(this.context.containsBean("beanTwo")).isFalse();
assertThat(this.context.containsBean("beanOne")).isTrue();
}
@Configuration
@Import({ConditionalConfiguration.class, UnconditionalConfiguration.class})
protected static | ImportWithConditionTests |
java | spring-projects__spring-framework | spring-expression/src/main/java/org/springframework/expression/spel/CodeFlow.java | {
"start": 5991,
"end": 6744
} | class ____ the compiled expression.
*/
public void finish() {
if (this.fieldAdders != null) {
for (FieldAdder fieldAdder : this.fieldAdders) {
fieldAdder.generateField(this.classWriter, this);
}
}
if (this.clinitAdders != null) {
MethodVisitor mv = this.classWriter.visitMethod(ACC_PUBLIC | ACC_STATIC, "<clinit>", "()V", null, null);
mv.visitCode();
this.nextFreeVariableId = 0; // to 0 because there is no 'this' in a clinit
for (ClinitAdder clinitAdder : this.clinitAdders) {
clinitAdder.generateCode(mv, this);
}
mv.visitInsn(RETURN);
mv.visitMaxs(0,0); // not supplied due to COMPUTE_MAXS
mv.visitEnd();
}
}
/**
* Register a FieldAdder which will add a new field to the generated
* | representing |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/pool/ui/DruidDataSourceUIManager.java | {
"start": 1404,
"end": 30028
} | class ____ extends JFrame {
private static final long serialVersionUID = 1L;
private DruidDataSource dataSource;
private SpringLayout layout = new SpringLayout();
private JButton btnInitDataSource = new JButton("Init Pool");
private JButton btnCloseDataSource = new JButton("Close Pool");
private JButton btnConnect = new JButton("Get Connection");
private JButton btnClose = new JButton("Close Connection");
private JButton btnCase_0 = new JButton("Case 0");
private JPanel mainPanel = new JPanel();
private JScrollPane scrollPane = new JScrollPane(mainPanel);
private JLabel lbUrl = new JLabel("URL : ");
private JTextField txtUrl = new JTextField(
"jdbc:oracle:thin:@a.b.c.d:1521:ocndb");
private JLabel lbDriverClass = new JLabel("DriverClassName : ");
private JTextField txtDriverClass = new JTextField();
private JLabel lbUser = new JLabel("User : ");
private JTextField txtUser = new JTextField();
private JLabel lbPassword = new JLabel("Password : ");
private JTextField txtPassword = new JTextField();
private JLabel lbConnectionProperties = new JLabel(
"Connection Properties : ");
private JTextField txtConnectionProperties = new JTextField();
private JLabel lbInitialSize = new JLabel("InitialSize : ");
private JTextField txtInitialSize = new JTextField("1");
private JLabel lbMaxActive = new JLabel("MaxActive : ");
private JTextField txtMaxActive = new JTextField("14");
private JLabel lbMaxIdle = new JLabel("MaxIdle : ");
private JTextField txtMaxIdle = new JTextField("14");
private JLabel lbMinIdle = new JLabel("MinIdle : ");
private JTextField txtMinIdle = new JTextField("1");
private JLabel lbMaxWait = new JLabel("MaxWait : ");
private JTextField txtMaxWait = new JTextField("-1");
private JLabel lbMinEvictableIdleTimeMillis = new JLabel(
"MinEvictableIdleTimeMillis : ");
private JTextField txtMinEvictableIdleTimeMillis = new JTextField("1800000");
private DruidDataStatusPanel statusPanel = new DruidDataStatusPanel();
private JLabel lbValidationQuery = new JLabel("ValidationQuery : ");
private JTextField txtValidationQuery = new JTextField("");
private JLabel lbTestWhileIdle = new JLabel("TestWhileIdle : ");
private JTextField txtTestWhileIdle = new JTextField("false");
private JLabel lbTestOnBorrow = new JLabel("TestOnBorrow : ");
private JTextField txtTestOnBorrow = new JTextField("false");
private JTextField txtGetStep = new JTextField("1");
private JTextField txtReleaseStep = new JTextField("1");
private AtomicInteger connectingCount = new AtomicInteger();
private AtomicInteger connectCount = new AtomicInteger();
private AtomicInteger closeCount = new AtomicInteger();
private AtomicInteger executingCount = new AtomicInteger();
private Thread statusThread;
private final ConcurrentLinkedQueue<Connection> activeConnections = new ConcurrentLinkedQueue<Connection>();
private ExecutorService executor;
public DruidDataSourceUIManager() {
this.setLayout(new BorderLayout());
Toolkit kit = Toolkit.getDefaultToolkit(); // 定义工具包
Dimension screenSize = kit.getScreenSize(); // 获取屏幕的尺寸
int screenWidth = screenSize.width / 2; // 获取屏幕的宽
int screenHeight = screenSize.height / 2; // 获取屏幕的高
int height = this.getHeight();
int width = this.getWidth();
setLocation(screenWidth - width / 2, screenHeight - height / 2);
this.getContentPane().add(scrollPane, BorderLayout.CENTER);
mainPanel.setLayout(layout);
mainPanel.add(lbUrl);
layout.putConstraint(SpringLayout.NORTH, lbUrl, 10, SpringLayout.NORTH, mainPanel);
layout.putConstraint(SpringLayout.WEST, lbUrl, 10, SpringLayout.WEST, mainPanel);
layout.putConstraint(SpringLayout.EAST, lbUrl, 200, SpringLayout.WEST, lbUrl);
mainPanel.add(txtUrl);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtUrl, 0, SpringLayout.VERTICAL_CENTER, lbUrl);
layout.putConstraint(SpringLayout.WEST, txtUrl, 10, SpringLayout.EAST, lbUrl);
layout.putConstraint(SpringLayout.EAST, txtUrl, -10, SpringLayout.EAST, mainPanel);
// ////
mainPanel.add(lbDriverClass);
layout.putConstraint(SpringLayout.NORTH, lbDriverClass, 10, SpringLayout.SOUTH, lbUrl);
layout.putConstraint(SpringLayout.WEST, lbDriverClass, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbDriverClass, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtDriverClass);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtDriverClass, 0, SpringLayout.VERTICAL_CENTER,
lbDriverClass);
layout.putConstraint(SpringLayout.WEST, txtDriverClass, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtDriverClass, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbUser);
layout.putConstraint(SpringLayout.NORTH, lbUser, 10, SpringLayout.SOUTH, lbDriverClass);
layout.putConstraint(SpringLayout.WEST, lbUser, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbUser, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtUser);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtUser, 0, SpringLayout.VERTICAL_CENTER, lbUser);
layout.putConstraint(SpringLayout.WEST, txtUser, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtUser, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbPassword);
layout.putConstraint(SpringLayout.NORTH, lbPassword, 10, SpringLayout.SOUTH, lbUser);
layout.putConstraint(SpringLayout.WEST, lbPassword, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbPassword, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtPassword);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtPassword, 0, SpringLayout.VERTICAL_CENTER, lbPassword);
layout.putConstraint(SpringLayout.WEST, txtPassword, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtPassword, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbConnectionProperties);
layout.putConstraint(SpringLayout.NORTH, lbConnectionProperties, 10, SpringLayout.SOUTH, lbPassword);
layout.putConstraint(SpringLayout.WEST, lbConnectionProperties, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbConnectionProperties, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtConnectionProperties);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtConnectionProperties, 0, SpringLayout.VERTICAL_CENTER,
lbConnectionProperties);
layout.putConstraint(SpringLayout.WEST, txtConnectionProperties, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtConnectionProperties, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbInitialSize);
layout.putConstraint(SpringLayout.NORTH, lbInitialSize, 10, SpringLayout.SOUTH, lbConnectionProperties);
layout.putConstraint(SpringLayout.WEST, lbInitialSize, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbInitialSize, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtInitialSize);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtInitialSize, 0, SpringLayout.VERTICAL_CENTER,
lbInitialSize);
layout.putConstraint(SpringLayout.WEST, txtInitialSize, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtInitialSize, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbMaxActive);
layout.putConstraint(SpringLayout.NORTH, lbMaxActive, 10, SpringLayout.SOUTH, lbInitialSize);
layout.putConstraint(SpringLayout.WEST, lbMaxActive, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbMaxActive, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtMaxActive);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtMaxActive, 0, SpringLayout.VERTICAL_CENTER, lbMaxActive);
layout.putConstraint(SpringLayout.WEST, txtMaxActive, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtMaxActive, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbMaxIdle);
layout.putConstraint(SpringLayout.NORTH, lbMaxIdle, 10, SpringLayout.SOUTH, lbMaxActive);
layout.putConstraint(SpringLayout.WEST, lbMaxIdle, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbMaxIdle, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtMaxIdle);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtMaxIdle, 0, SpringLayout.VERTICAL_CENTER, lbMaxIdle);
layout.putConstraint(SpringLayout.WEST, txtMaxIdle, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtMaxIdle, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbMinIdle);
layout.putConstraint(SpringLayout.NORTH, lbMinIdle, 10, SpringLayout.SOUTH, lbMaxIdle);
layout.putConstraint(SpringLayout.WEST, lbMinIdle, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbMinIdle, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtMinIdle);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtMinIdle, 0, SpringLayout.VERTICAL_CENTER, lbMinIdle);
layout.putConstraint(SpringLayout.WEST, txtMinIdle, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtMinIdle, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbMaxWait);
layout.putConstraint(SpringLayout.NORTH, lbMaxWait, 10, SpringLayout.SOUTH, lbMinIdle);
layout.putConstraint(SpringLayout.WEST, lbMaxWait, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbMaxWait, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtMaxWait);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtMaxWait, 0, SpringLayout.VERTICAL_CENTER, lbMaxWait);
layout.putConstraint(SpringLayout.WEST, txtMaxWait, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtMaxWait, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbMinEvictableIdleTimeMillis);
layout.putConstraint(SpringLayout.NORTH, lbMinEvictableIdleTimeMillis, 10, SpringLayout.SOUTH, lbMaxWait);
layout.putConstraint(SpringLayout.WEST, lbMinEvictableIdleTimeMillis, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbMinEvictableIdleTimeMillis, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtMinEvictableIdleTimeMillis);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtMinEvictableIdleTimeMillis, 0,
SpringLayout.VERTICAL_CENTER, lbMinEvictableIdleTimeMillis);
layout.putConstraint(SpringLayout.WEST, txtMinEvictableIdleTimeMillis, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtMinEvictableIdleTimeMillis, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbValidationQuery);
layout.putConstraint(SpringLayout.NORTH, lbValidationQuery, 10, SpringLayout.SOUTH,
lbMinEvictableIdleTimeMillis);
layout.putConstraint(SpringLayout.WEST, lbValidationQuery, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbValidationQuery, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtValidationQuery);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtValidationQuery, 0, SpringLayout.VERTICAL_CENTER,
lbValidationQuery);
layout.putConstraint(SpringLayout.WEST, txtValidationQuery, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtValidationQuery, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(lbTestWhileIdle);
layout.putConstraint(SpringLayout.NORTH, lbTestWhileIdle, 10, SpringLayout.SOUTH, lbValidationQuery);
layout.putConstraint(SpringLayout.WEST, lbTestWhileIdle, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbTestWhileIdle, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtTestWhileIdle);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtTestWhileIdle, 0, SpringLayout.VERTICAL_CENTER,
lbTestWhileIdle);
layout.putConstraint(SpringLayout.WEST, txtTestWhileIdle, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtTestWhileIdle, 0, SpringLayout.EAST, txtUrl);
mainPanel.add(lbTestOnBorrow);
layout.putConstraint(SpringLayout.NORTH, lbTestOnBorrow, 10, SpringLayout.SOUTH, lbTestWhileIdle);
layout.putConstraint(SpringLayout.WEST, lbTestOnBorrow, 0, SpringLayout.WEST, lbUrl);
layout.putConstraint(SpringLayout.EAST, lbTestOnBorrow, 0, SpringLayout.EAST, lbUrl);
mainPanel.add(txtTestOnBorrow);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtTestOnBorrow, 0, SpringLayout.VERTICAL_CENTER,
lbTestOnBorrow);
layout.putConstraint(SpringLayout.WEST, txtTestOnBorrow, 0, SpringLayout.WEST, txtUrl);
layout.putConstraint(SpringLayout.EAST, txtTestOnBorrow, 0, SpringLayout.EAST, txtUrl);
// ////
mainPanel.add(btnInitDataSource);
layout.putConstraint(SpringLayout.NORTH, btnInitDataSource, 10, SpringLayout.SOUTH, lbTestOnBorrow);
layout.putConstraint(SpringLayout.WEST, btnInitDataSource, 0, SpringLayout.WEST, lbUrl);
btnInitDataSource.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
init_actionPerformed(e);
}
});
mainPanel.add(btnCloseDataSource);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, btnCloseDataSource, 0, SpringLayout.VERTICAL_CENTER,
btnInitDataSource);
layout.putConstraint(SpringLayout.WEST, btnCloseDataSource, 10, SpringLayout.EAST, btnInitDataSource);
btnCloseDataSource.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
closeDataSource_actionPerformed(e);
}
});
btnCloseDataSource.setEnabled(false);
btnConnect.setEnabled(false);
btnClose.setEnabled(false);
btnCase_0.setEnabled(false);
mainPanel.add(btnConnect);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, btnConnect, 0, SpringLayout.VERTICAL_CENTER,
btnInitDataSource);
layout.putConstraint(SpringLayout.WEST, btnConnect, 10, SpringLayout.EAST, btnCloseDataSource);
btnConnect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
connect_actionPerformed(e);
}
});
mainPanel.add(txtGetStep);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtGetStep, 0, SpringLayout.VERTICAL_CENTER,
btnInitDataSource);
layout.putConstraint(SpringLayout.WEST, txtGetStep, 10, SpringLayout.EAST, btnConnect);
layout.putConstraint(SpringLayout.EAST, txtGetStep, 40, SpringLayout.WEST, txtGetStep);
// txtGetStep
mainPanel.add(btnClose);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, btnClose, 0, SpringLayout.VERTICAL_CENTER, btnInitDataSource);
layout.putConstraint(SpringLayout.WEST, btnClose, 10, SpringLayout.EAST, txtGetStep);
btnClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int step = Integer.parseInt(txtReleaseStep.getText().trim());
for (int i = 0; i < step; ++i) {
Connection conn = activeConnections.poll();
if (conn != null) {
try {
conn.close();
closeCount.incrementAndGet();
} catch (SQLException ex) {
ex.printStackTrace();
}
} else {
// System.out.println("close connection is null");
}
}
}
});
mainPanel.add(txtReleaseStep);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtReleaseStep, 0, SpringLayout.VERTICAL_CENTER,
btnInitDataSource);
layout.putConstraint(SpringLayout.WEST, txtReleaseStep, 10, SpringLayout.EAST, btnClose);
layout.putConstraint(SpringLayout.EAST, txtReleaseStep, 40, SpringLayout.WEST, txtReleaseStep);
mainPanel.add(btnCase_0);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, btnCase_0, 0, SpringLayout.VERTICAL_CENTER, txtReleaseStep);
layout.putConstraint(SpringLayout.WEST, btnCase_0, 10, SpringLayout.EAST, txtReleaseStep);
btnCase_0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
case_0();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
// txtReleaseStep
mainPanel.add(statusPanel);
layout.putConstraint(SpringLayout.NORTH, statusPanel, 10, SpringLayout.SOUTH, btnInitDataSource);
layout.putConstraint(SpringLayout.SOUTH, statusPanel, 120, SpringLayout.NORTH, statusPanel);
layout.putConstraint(SpringLayout.WEST, statusPanel, 0, SpringLayout.WEST, lbUrl);
// layout.putConstraint(SpringLayout.EAST, txtMaxWait, 0, SpringLayout.EAST, mainPanel);
// ////
}
public void connect_actionPerformed(ActionEvent e) {
int step = Integer.parseInt(txtGetStep.getText().trim());
for (int i = 0; i < step; ++i) {
final Runnable task = new Runnable() {
public void run() {
try {
connectingCount.incrementAndGet();
Connection conn = dataSource.getConnection();
connectCount.incrementAndGet();
connectingCount.decrementAndGet();
if (conn == null) {
System.out.println("get connection is null");
return;
}
executingCount.incrementAndGet();
try {
Statement stmt = conn.createStatement();
stmt.setQueryTimeout(5);
ResultSet rs = stmt.executeQuery("SELECT 1 FROM DUAL");
while (rs.next()) {
rs.getObject(1);
}
Thread.sleep(1000 * 3);
rs.close();
stmt.close();
} finally {
executingCount.decrementAndGet();
}
activeConnections.add(conn);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
executor.submit(task);
}
}
public void closeDataSource_actionPerformed(ActionEvent e) {
dataSource.close();
try {
ManagementFactory.getPlatformMBeanServer().unregisterMBean(new ObjectName(
"com.alibaba.druid:type=DruidDataSource"));
} catch (Exception e1) {
e1.printStackTrace();
}
txtUrl.setEnabled(true);
txtDriverClass.setEnabled(true);
txtConnectionProperties.setEnabled(true);
txtUser.setEnabled(true);
txtPassword.setEnabled(true);
txtInitialSize.setEnabled(true);
txtMaxActive.setEnabled(true);
txtMaxIdle.setEnabled(true);
txtMinIdle.setEnabled(true);
txtMaxWait.setEnabled(true);
txtMinEvictableIdleTimeMillis.setEnabled(true);
btnInitDataSource.setEnabled(true);
btnCloseDataSource.setEnabled(false);
btnConnect.setEnabled(false);
btnClose.setEnabled(false);
btnCase_0.setEnabled(false);
statusThread.interrupt();
}
public void init_actionPerformed(ActionEvent e) {
try {
dataSource = new DruidDataSource();
dataSource.setUrl(txtUrl.getText().trim());
dataSource.setDriverClassName(txtDriverClass.getText().trim());
dataSource.setConnectionProperties(txtConnectionProperties.getText().trim());
dataSource.setUsername(txtUser.getText().trim());
dataSource.setPassword(txtPassword.getText().trim());
dataSource.setInitialSize(Integer.parseInt(txtInitialSize.getText().trim()));
dataSource.setMaxActive(Integer.parseInt(txtMaxActive.getText().trim()));
dataSource.setMaxIdle(Integer.parseInt(txtMaxIdle.getText().trim()));
dataSource.setMinIdle(Integer.parseInt(txtMinIdle.getText().trim()));
dataSource.setMaxWait(Integer.parseInt(txtMaxWait.getText().trim()));
dataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(txtMinEvictableIdleTimeMillis.getText().trim()));
dataSource.setTestWhileIdle(Boolean.parseBoolean(txtTestWhileIdle.getText().trim()));
dataSource.setTestOnBorrow(Boolean.parseBoolean(txtTestOnBorrow.getText().trim()));
dataSource.setTimeBetweenEvictionRunsMillis(60000);
dataSource.setNumTestsPerEvictionRun(20);
ManagementFactory.getPlatformMBeanServer().registerMBean(dataSource,
new ObjectName(
"com.alibaba.druid:type=DruidDataSource"));
try {
Connection conn = dataSource.getConnection();
connectCount.incrementAndGet();
conn.close();
closeCount.incrementAndGet();
} catch (Exception ex) {
ex.printStackTrace();
}
executor = Executors.newCachedThreadPool();
txtDriverClass.setText(dataSource.getDriverClassName());
txtMinEvictableIdleTimeMillis.setText(Long.toString(dataSource.getMinEvictableIdleTimeMillis()));
txtUrl.setEnabled(false);
txtDriverClass.setEnabled(false);
txtConnectionProperties.setEnabled(false);
txtUser.setEnabled(false);
txtPassword.setEnabled(false);
txtInitialSize.setEnabled(false);
txtMaxActive.setEnabled(false);
txtMaxIdle.setEnabled(false);
txtMinIdle.setEnabled(false);
txtMaxWait.setEnabled(false);
txtMinEvictableIdleTimeMillis.setEnabled(false);
btnInitDataSource.setEnabled(false);
btnCloseDataSource.setEnabled(true);
btnConnect.setEnabled(true);
btnClose.setEnabled(true);
btnCase_0.setEnabled(true);
statusThread = new Thread("Watch Status") {
public void run() {
for (; ; ) {
statusPanel.set("CreateCount", dataSource.getCreateCount());
statusPanel.set("CreateErrorCount", dataSource.getCreateErrorCount());
statusPanel.set("CreateTimespanMillis", dataSource.getCreateTimespanMillis());
statusPanel.set("CreateTimespanNano", dataSource.getCreateTimespanNano());
statusPanel.set("DestroyCount", dataSource.getDestroyCount());
statusPanel.set("ConnectCount", dataSource.getConnectCount());
statusPanel.set("ConnectErrorCount", dataSource.getConnectErrorCount());
statusPanel.set("CloseCount", dataSource.getCloseCount());
statusPanel.set("RecycleCount", dataSource.getRecycleCount());
statusPanel.set("ActiveCount", dataSource.getActiveCount());
statusPanel.set("PoolingCount", dataSource.getPoolingCount());
statusPanel.set("UI_GettingCount", connectingCount.get());
statusPanel.set("UI_GetCount", connectCount.get());
statusPanel.set("UI_ReleaseCount", closeCount.get());
statusPanel.set("UI_ExecutingCount", executingCount.get());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
}
}
};
statusThread.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void case_0() throws Exception {
Runnable task = new Runnable() {
public void run() {
final int threadCount = 20;
final int LOOP_COUNT = 1000 * 1;
final String sql = "SELECT 1 FROM DUAL";
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch endLatch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; ++i) {
Thread thread = new Thread() {
public void run() {
try {
startLatch.await();
for (int i = 0; i < LOOP_COUNT; ++i) {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
rs.getInt(1);
}
rs.close();
stmt.close();
Thread.sleep(1);
conn.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
endLatch.countDown();
}
};
thread.start();
}
long startMillis = System.currentTimeMillis();
long startYGC = TestUtil.getYoungGC();
long startFullGC = TestUtil.getFullGC();
startLatch.countDown();
try {
endLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long millis = System.currentTimeMillis() - startMillis;
long ygc = TestUtil.getYoungGC() - startYGC;
long fullGC = TestUtil.getFullGC() - startFullGC;
System.out.println("thread " + threadCount + " druid millis : "
+ NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}
};
executor.submit(task);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
DruidDataSourceUIManager manager = new DruidDataSourceUIManager();
manager.pack();
manager.setSize(820, 580);
int w = (Toolkit.getDefaultToolkit().getScreenSize().width - manager.getWidth()) / 2;
int h = (Toolkit.getDefaultToolkit().getScreenSize().height - manager.getHeight()) / 2;
manager.setLocation(w, h);
manager.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
manager.setVisible(true);
}
});
}
}
| DruidDataSourceUIManager |
java | alibaba__nacos | common/src/main/java/com/alibaba/nacos/common/packagescan/util/AbstractAssert.java | {
"start": 2572,
"end": 8052
} | class ____ {
private AbstractAssert() {
}
/**
* Assert a boolean expression, throwing an {@code IllegalStateException}
* if the expression evaluates to {@code false}.
* Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException}
* on an assertion failure.
* <pre class="code">Assert.state(id == null, "The id property must not already be initialized");</pre>
*
* @param expression a boolean expression
* @param message the exception message to use if the assertion fails
* @throws IllegalStateException if {@code expression} is {@code false}
*/
public static void state(boolean expression, String message) {
if (!expression) {
throw new IllegalStateException(message);
}
}
/**
* Assert a boolean expression, throwing an {@code IllegalStateException}
* if the expression evaluates to {@code false}.
* Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException}
* on an assertion failure.
* <pre class="code">
* Assert.state(entity.getId() == null,
* () -> "ID for entity " + entity.getName() + " must not already be initialized");
* </pre>
*
* @param expression a boolean expression
* @param messageSupplier a supplier for the exception message to use if the
* assertion fails
* @throws IllegalStateException if {@code expression} is {@code false}
* @since 5.0
*/
public static void state(boolean expression, Supplier<String> messageSupplier) {
if (!expression) {
throw new IllegalStateException(nullSafeGet(messageSupplier));
}
}
/**
* Assert a boolean expression, throwing an {@code IllegalStateException}
* if the expression evaluates to {@code false}.
*
* @deprecated as of 4.3.7, in favor of {@link #state(boolean, String)}
*/
@Deprecated
public static void state(boolean expression) {
state(expression, "[Assertion failed] - this state invariant must be true");
}
/**
* Assert a boolean expression, throwing an {@code IllegalArgumentException}
* if the expression evaluates to {@code false}.
* <pre class="code">Assert.isTrue(i > 0, "The value must be greater than zero");</pre>
*
* @param expression a boolean expression
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if {@code expression} is {@code false}
*/
public static void isTrue(boolean expression, String message) {
if (!expression) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert a boolean expression, throwing an {@code IllegalArgumentException}
* if the expression evaluates to {@code false}.
* <pre class="code">
* Assert.isTrue(i > 0, () -> "The value '" + i + "' must be greater than zero");
* </pre>
*
* @param expression a boolean expression
* @param messageSupplier a supplier for the exception message to use if the
* assertion fails
* @throws IllegalArgumentException if {@code expression} is {@code false}
* @since 5.0
*/
public static void isTrue(boolean expression, Supplier<String> messageSupplier) {
if (!expression) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/**
* Assert a boolean expression, throwing an {@code IllegalArgumentException}
* if the expression evaluates to {@code false}.
*
* @deprecated as of 4.3.7, in favor of {@link #isTrue(boolean, String)}
*/
@Deprecated
public static void isTrue(boolean expression) {
isTrue(expression, "[Assertion failed] - this expression must be true");
}
/**
* Assert that an object is {@code null}.
* <pre class="code">Assert.isNull(value, "The value must be null");</pre>
*
* @param object the object to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the object is not {@code null}
*/
public static void isNull(Object object, String message) {
if (object != null) {
throw new IllegalArgumentException(message);
}
}
/**
* Assert that an object is {@code null}.
* <pre class="code">
* Assert.isNull(value, () -> "The value '" + value + "' must be null");
* </pre>
*
* @param object the object to check
* @param messageSupplier a supplier for the exception message to use if the
* assertion fails
* @throws IllegalArgumentException if the object is not {@code null}
* @since 5.0
*/
public static void isNull(Object object, Supplier<String> messageSupplier) {
if (object != null) {
throw new IllegalArgumentException(nullSafeGet(messageSupplier));
}
}
/**
* Assert that an object is {@code null}.
*
* @deprecated as of 4.3.7, in favor of {@link #isNull(Object, String)}
*/
@Deprecated
public static void isNull(Object object) {
isNull(object, "[Assertion failed] - the object argument must be null");
}
/**
* Assert that an object is not {@code null}.
* <pre class="code">Assert.notNull(clazz, "The | AbstractAssert |
java | google__dagger | javatests/dagger/functional/assisted/AssistedFactoryWithQualifiedTypesTest.java | {
"start": 1074,
"end": 1596
} | interface ____ {
// Test a factory with duplicate types with unique qualifiers.
DupeTypeFactory dupeTypeFactory();
// Test a factory with duplicate qualifiers with unique types.
DupeQualifierFactory dupeQualifierFactory();
// Test a factory with unnecessary qualifiers on the factory.
UnnecessaryQualifierFactory unnecessaryQualifierFactory();
// Test a factory with different parameter order than the constructor.
SwappedDupeTypeFactory swappedDupeTypeFactory();
}
static | TestComponent |
java | apache__rocketmq | client/src/test/java/org/apache/rocketmq/client/impl/mqclient/MQClientAPIExtTest.java | {
"start": 2511,
"end": 7828
} | class ____ {
MQClientAPIExt mqClientAPIExt;
@Mock
NettyRemotingClient remotingClientMock;
@Before
public void before() {
mqClientAPIExt = Mockito.spy(new MQClientAPIExt(new ClientConfig(), new NettyClientConfig(), null, null));
Mockito.when(mqClientAPIExt.getRemotingClient()).thenReturn(remotingClientMock);
Mockito.when(remotingClientMock.invoke(anyString(), any(), anyLong())).thenReturn(FutureUtils.completeExceptionally(new RemotingTimeoutException("addr")));
}
@Test
public void sendMessageAsync() {
String topic = "test";
Message msg = new Message(topic, "test".getBytes());
SendMessageRequestHeader requestHeader = new SendMessageRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setProducerGroup("test");
requestHeader.setDefaultTopic("test");
requestHeader.setDefaultTopicQueueNums(1);
requestHeader.setQueueId(0);
requestHeader.setSysFlag(0);
requestHeader.setBornTimestamp(0L);
requestHeader.setFlag(0);
requestHeader.setProperties("test");
requestHeader.setReconsumeTimes(0);
requestHeader.setUnitMode(false);
requestHeader.setBatch(false);
CompletableFuture<SendResult> future = mqClientAPIExt.sendMessageAsync("127.0.0.1:10911", "test", msg, requestHeader, 10);
assertThatThrownBy(future::get).getCause().isInstanceOf(RemotingTimeoutException.class);
}
@Test
public void testUpdateConsumerOffsetAsync_Success() throws ExecutionException, InterruptedException {
CompletableFuture<RemotingCommand> remotingFuture = new CompletableFuture<>();
remotingFuture.complete(RemotingCommand.createResponseCommand(ResponseCode.SUCCESS, ""));
doReturn(remotingFuture).when(remotingClientMock).invoke(anyString(), any(RemotingCommand.class), anyLong());
CompletableFuture<Void> future = mqClientAPIExt.updateConsumerOffsetAsync("brokerAddr", new UpdateConsumerOffsetRequestHeader(), 3000L);
assertNull("Future should be completed without exception", future.get());
}
@Test
public void testUpdateConsumerOffsetAsync_Fail() throws InterruptedException {
CompletableFuture<RemotingCommand> remotingFuture = new CompletableFuture<>();
remotingFuture.complete(RemotingCommand.createResponseCommand(ResponseCode.SYSTEM_ERROR, "QueueId is null, topic is testTopic"));
doReturn(remotingFuture).when(remotingClientMock).invoke(anyString(), any(RemotingCommand.class), anyLong());
CompletableFuture<Void> future = mqClientAPIExt.updateConsumerOffsetAsync("brokerAddr", new UpdateConsumerOffsetRequestHeader(), 3000L);
try {
future.get();
} catch (ExecutionException e) {
MQBrokerException customEx = (MQBrokerException) e.getCause();
assertEquals(customEx.getResponseCode(), ResponseCode.SYSTEM_ERROR);
assertEquals(customEx.getErrorMessage(), "QueueId is null, topic is testTopic");
}
}
@Test
public void testRecallMessageAsync_success() {
String msgId = "msgId";
RecallMessageRequestHeader requestHeader = new RecallMessageRequestHeader();
requestHeader.setProducerGroup("group");
requestHeader.setTopic("topic");
requestHeader.setRecallHandle("handle");
requestHeader.setBrokerName("brokerName");
RemotingCommand response = RemotingCommand.createResponseCommand(RecallMessageResponseHeader.class);
response.setCode(ResponseCode.SUCCESS);
RecallMessageResponseHeader responseHeader = (RecallMessageResponseHeader) response.readCustomHeader();
responseHeader.setMsgId(msgId);
response.makeCustomHeaderToNet();
CompletableFuture<RemotingCommand> remotingFuture = new CompletableFuture<>();
remotingFuture.complete(response);
doReturn(remotingFuture).when(remotingClientMock).invoke(anyString(), any(RemotingCommand.class), anyLong());
String resultId =
mqClientAPIExt.recallMessageAsync("brokerAddr", requestHeader, 3000L).join();
Assert.assertEquals(msgId, resultId);
}
@Test
public void testRecallMessageAsync_fail() {
RecallMessageRequestHeader requestHeader = new RecallMessageRequestHeader();
requestHeader.setProducerGroup("group");
requestHeader.setTopic("topic");
requestHeader.setRecallHandle("handle");
requestHeader.setBrokerName("brokerName");
CompletableFuture<RemotingCommand> remotingFuture = new CompletableFuture<>();
remotingFuture.complete(RemotingCommand.createResponseCommand(ResponseCode.SERVICE_NOT_AVAILABLE, ""));
doReturn(remotingFuture).when(remotingClientMock).invoke(anyString(), any(RemotingCommand.class), anyLong());
CompletionException exception = Assert.assertThrows(CompletionException.class, () -> {
mqClientAPIExt.recallMessageAsync("brokerAddr", requestHeader, 3000L).join();
});
Assert.assertTrue(exception.getCause() instanceof MQBrokerException);
MQBrokerException cause = (MQBrokerException) exception.getCause();
Assert.assertEquals(ResponseCode.SERVICE_NOT_AVAILABLE, cause.getResponseCode());
}
} | MQClientAPIExtTest |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/security/authenticator/DefaultKafkaPrincipalBuilder.java | {
"start": 2254,
"end": 2395
} | class ____ {@link org.apache.kafka.common.security.kerberos.KerberosShortNamer} to transform
* the name.
*
* NOTE: This is an internal | applies |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/CustomDeserializersTest.java | {
"start": 4107,
"end": 4369
} | class ____ extends ValueSerializer<CustomKey> {
@Override
public void serialize(CustomKey value, JsonGenerator g, SerializationContext provider) {
g.writeName(String.valueOf(value.getId()));
}
}
static | CustomKeySerializer |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/phoenix/visitor/PhoenixOutputVisitor.java | {
"start": 867,
"end": 1234
} | class ____ extends SQLASTOutputVisitor implements PhoenixASTVisitor {
public PhoenixOutputVisitor(StringBuilder appender) {
super(appender, DbType.phoenix, Phoenix.DIALECT);
}
public PhoenixOutputVisitor(StringBuilder appender, boolean parameterized) {
super(appender, DbType.phoenix, Phoenix.DIALECT, parameterized);
}
}
| PhoenixOutputVisitor |
java | elastic__elasticsearch | x-pack/plugin/vector-tile/src/main/java/org/elasticsearch/xpack/vectortile/feature/FeatureFactory.java | {
"start": 16010,
"end": 17765
} | class ____ implements CoordinateSequenceFilter {
private final int extent;
private final double pointXScale, pointYScale, pointXTranslate, pointYTranslate;
private MvtCoordinateSequenceFilter(Envelope tileEnvelope, int extent) {
this.extent = extent;
this.pointXScale = (double) extent / tileEnvelope.getWidth();
this.pointYScale = (double) -extent / tileEnvelope.getHeight();
this.pointXTranslate = -pointXScale * tileEnvelope.getMinX();
this.pointYTranslate = -pointYScale * tileEnvelope.getMinY();
}
@Override
public void filter(CoordinateSequence seq, int i) {
// JTS can sometimes close polygons using references to the starting coordinate, which can lead to that coordinate
// being converted twice. We need to detect if the end is the same actual Coordinate, and not do the conversion again.
if (i != 0 && i == seq.size() - 1 && seq.getCoordinate(0) == seq.getCoordinate(i)) {
return;
}
seq.setOrdinate(i, CoordinateSequence.X, lon(seq.getOrdinate(i, CoordinateSequence.X)));
seq.setOrdinate(i, CoordinateSequence.Y, lat(seq.getOrdinate(i, CoordinateSequence.Y)));
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isGeometryChanged() {
return true;
}
private int lat(double lat) {
return (int) Math.round(pointYScale * lat + pointYTranslate) + extent;
}
private int lon(double lon) {
return (int) Math.round(pointXScale * lon + pointXTranslate);
}
}
}
| MvtCoordinateSequenceFilter |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java | {
"start": 8241,
"end": 8782
} | class ____ {
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static LocalValidatorFactoryBean defaultValidator(ApplicationContext applicationContext) {
return new LocalValidatorFactoryBean();
}
@Bean
static MethodValidationPostProcessor methodValidationPostProcessor(ObjectProvider<Validator> validator) {
MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
processor.setProxyTargetClass(true);
processor.setValidatorProvider(validator);
return processor;
}
}
}
| ProxyBeanConfiguration |
java | bumptech__glide | integration/volley/src/main/java/com/bumptech/glide/integration/volley/VolleyStreamFetcher.java | {
"start": 3117,
"end": 4708
} | class ____ extends Request<byte[]> {
private final DataCallback<? super InputStream> callback;
private final Priority priority;
private final Map<String, String> headers;
public GlideRequest(String url, DataCallback<? super InputStream> callback, Priority priority) {
this(url, callback, priority, Collections.<String, String>emptyMap());
}
public GlideRequest(
String url,
DataCallback<? super InputStream> callback,
Priority priority,
Map<String, String> headers) {
super(Method.GET, url, null);
this.callback = callback;
this.priority = priority;
this.headers = headers;
}
@Override
public Map<String, String> getHeaders() {
return headers;
}
@Override
public Priority getPriority() {
return priority;
}
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Volley failed to retrieve response", volleyError);
}
if (!isCanceled()) {
callback.onLoadFailed(volleyError);
}
return super.parseNetworkError(volleyError);
}
@Override
protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
if (!isCanceled()) {
callback.onDataReady(new ByteArrayInputStream(response.data));
}
return Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(byte[] response) {
// Do nothing.
}
}
}
| GlideRequest |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/commit/ITestUploadRecovery.java | {
"start": 3838,
"end": 4052
} | class ____
* wasting time with duplicate uploads.
* <p>
* Fault injection is implemented in {@link SdkFaultInjector}.
*/
@ParameterizedClass(name="buffer={0}-commit-test={1}")
@MethodSource("params")
public | without |
java | spring-projects__spring-boot | buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/HttpTransportTests.java | {
"start": 1119,
"end": 2228
} | class ____ {
@Test
void createWhenDockerHostVariableIsAddressReturnsRemote() {
HttpTransport transport = HttpTransport.create(new DockerConnectionConfiguration.Host("tcp://192.168.1.0"));
assertThat(transport).isInstanceOf(RemoteHttpClientTransport.class);
}
@Test
void createWhenDockerHostVariableIsFileReturnsLocal(@TempDir Path tempDir) throws IOException {
String dummySocketFilePath = Files.createTempFile(tempDir, "http-transport", null).toAbsolutePath().toString();
HttpTransport transport = HttpTransport.create(new DockerConnectionConfiguration.Host(dummySocketFilePath));
assertThat(transport).isInstanceOf(LocalHttpClientTransport.class);
}
@Test
void createWhenDockerHostVariableIsUnixSchemePrefixedFileReturnsLocal(@TempDir Path tempDir) throws IOException {
String dummySocketFilePath = "unix://" + Files.createTempFile(tempDir, "http-transport", null).toAbsolutePath();
HttpTransport transport = HttpTransport.create(new DockerConnectionConfiguration.Host(dummySocketFilePath));
assertThat(transport).isInstanceOf(LocalHttpClientTransport.class);
}
}
| HttpTransportTests |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/jackson2/DurationMixin.java | {
"start": 1018,
"end": 1521
} | class ____ used to serialize/deserialize {@link Duration}.
*
* @author Joe Grandja
* @since 7.0
* @see Duration
* @deprecated as of 7.0
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE,
creatorVisibility = JsonAutoDetect.Visibility.NONE)
@Deprecated(forRemoval = true)
abstract | is |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/AutoValueSubclassLeaked.java | {
"start": 2443,
"end": 2580
} | class ____ be confined to a"
+ " single factory method, with other factories delegating to it if necessary.")
public final | should |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/logical/Filter.java | {
"start": 1413,
"end": 4027
} | class ____ extends UnaryPlan implements PostAnalysisVerificationAware, TelemetryAware, SortAgnostic {
public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(LogicalPlan.class, "Filter", Filter::new);
private final Expression condition;
public Filter(Source source, LogicalPlan child, Expression condition) {
super(source, child);
this.condition = condition;
}
private Filter(StreamInput in) throws IOException {
this(Source.readFrom((PlanStreamInput) in), in.readNamedWriteable(LogicalPlan.class), in.readNamedWriteable(Expression.class));
}
@Override
public void writeTo(StreamOutput out) throws IOException {
Source.EMPTY.writeTo(out);
out.writeNamedWriteable(child());
out.writeNamedWriteable(condition());
}
@Override
public String getWriteableName() {
return ENTRY.name;
}
@Override
protected NodeInfo<Filter> info() {
return NodeInfo.create(this, Filter::new, child(), condition);
}
@Override
public Filter replaceChild(LogicalPlan newChild) {
return new Filter(source(), newChild, condition);
}
public Expression condition() {
return condition;
}
@Override
public String telemetryLabel() {
return "WHERE";
}
@Override
public boolean expressionsResolved() {
return condition.resolved();
}
@Override
public int hashCode() {
return Objects.hash(condition, child());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Filter other = (Filter) obj;
return Objects.equals(condition, other.condition) && Objects.equals(child(), other.child());
}
public Filter with(Expression conditionExpr) {
return new Filter(source(), child(), conditionExpr);
}
public Filter with(LogicalPlan child, Expression conditionExpr) {
return new Filter(source(), child, conditionExpr);
}
@Override
public void postAnalysisVerification(Failures failures) {
checkFilterConditionDataType(condition, failures);
}
public static void checkFilterConditionDataType(Expression expression, Failures failures) {
if (expression.dataType() != NULL && expression.dataType() != BOOLEAN) {
failures.add(fail(expression, "Condition expression needs to be boolean, found [{}]", expression.dataType()));
}
}
}
| Filter |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/SubResourceInterfaceAndClientInterfaceTest.java | {
"start": 5537,
"end": 5734
} | interface ____ {
@Path("positions/{id}")
PositionResource get(@RestPath String id);
@Path("contacts")
Class<ContactResource> contacts();
}
public | OrderResource |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java | {
"start": 38414,
"end": 57687
} | interface ____ appropriate
* when you don't have a domain model. Otherwise, consider using one of the
* {@code queryForObject} methods.
* <p>The query is expected to be a single row query; the result row will be
* mapped to a Map (one entry for each column, using the column name as the key).
* @param sql the SQL query to execute
* @param args arguments to bind to the query
* (leaving it to the PreparedStatement to guess the corresponding SQL type);
* may also contain {@link SqlParameterValue} objects which indicate not
* only the argument value but also the SQL type and optionally the scale
* @return the result Map (one entry for each column, using the
* column name as the key)
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
* if the query does not return exactly one row
* @throws DataAccessException if the query fails
* @see #queryForMap(String)
* @see ColumnMapRowMapper
*/
Map<String, @Nullable Object> queryForMap(String sql, @Nullable Object @Nullable ... args) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list of
* arguments to bind to the query, expecting a result list.
* <p>The results will be mapped to a List (one entry for each row) of
* result objects, each of them matching the specified element type.
* @param sql the SQL query to execute
* @param args arguments to bind to the query
* @param argTypes the SQL types of the arguments
* (constants from {@code java.sql.Types})
* @param elementType the required type of element in the result list
* (for example, {@code Integer.class})
* @return a List of objects that match the specified element type
* @throws DataAccessException if the query fails
* @see #queryForList(String, Class)
* @see SingleColumnRowMapper
*/
<T> List<@Nullable T> queryForList(String sql, @Nullable Object @Nullable [] args, int[] argTypes, Class<T> elementType)
throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list of
* arguments to bind to the query, expecting a result list.
* <p>The results will be mapped to a List (one entry for each row) of
* result objects, each of them matching the specified element type.
* @param sql the SQL query to execute
* @param args arguments to bind to the query
* (leaving it to the PreparedStatement to guess the corresponding SQL type);
* may also contain {@link SqlParameterValue} objects which indicate not
* only the argument value but also the SQL type and optionally the scale
* @param elementType the required type of element in the result list
* (for example, {@code Integer.class})
* @return a List of objects that match the specified element type
* @throws DataAccessException if the query fails
* @see #queryForList(String, Class)
* @see SingleColumnRowMapper
* @deprecated in favor of {@link #queryForList(String, Class, Object...)}
*/
@Deprecated(since = "5.3")
<T> List<@Nullable T> queryForList(String sql, @Nullable Object @Nullable [] args, Class<T> elementType) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list of
* arguments to bind to the query, expecting a result list.
* <p>The results will be mapped to a List (one entry for each row) of
* result objects, each of them matching the specified element type.
* @param sql the SQL query to execute
* @param elementType the required type of element in the result list
* (for example, {@code Integer.class})
* @param args arguments to bind to the query
* (leaving it to the PreparedStatement to guess the corresponding SQL type);
* may also contain {@link SqlParameterValue} objects which indicate not
* only the argument value but also the SQL type and optionally the scale
* @return a List of objects that match the specified element type
* @throws DataAccessException if the query fails
* @since 3.0.1
* @see #queryForList(String, Class)
* @see SingleColumnRowMapper
*/
<T> List<@Nullable T> queryForList(String sql, Class<T> elementType, @Nullable Object @Nullable ... args) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list of
* arguments to bind to the query, expecting a result list.
* <p>The results will be mapped to a List (one entry for each row) of
* Maps (one entry for each column, using the column name as the key).
* Each element in the list will be of the form returned by this interface's
* {@code queryForMap} methods.
* @param sql the SQL query to execute
* @param args arguments to bind to the query
* @param argTypes the SQL types of the arguments
* (constants from {@code java.sql.Types})
* @return a List that contains a Map per row
* @throws DataAccessException if the query fails
* @see #queryForList(String)
* @see java.sql.Types
*/
List<Map<String, @Nullable Object>> queryForList(String sql, @Nullable Object @Nullable [] args, int[] argTypes) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list of
* arguments to bind to the query, expecting a result list.
* <p>The results will be mapped to a List (one entry for each row) of
* Maps (one entry for each column, using the column name as the key).
* Each element in the list will be of the form returned by this interface's
* {@code queryForMap} methods.
* @param sql the SQL query to execute
* @param args arguments to bind to the query
* (leaving it to the PreparedStatement to guess the corresponding SQL type);
* may also contain {@link SqlParameterValue} objects which indicate not
* only the argument value but also the SQL type and optionally the scale
* @return a List that contains a Map per row
* @throws DataAccessException if the query fails
* @see #queryForList(String)
*/
List<Map<String, @Nullable Object>> queryForList(String sql, @Nullable Object @Nullable ... args) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list of
* arguments to bind to the query, expecting an SqlRowSet.
* <p>The results will be mapped to an SqlRowSet which holds the data in a
* disconnected fashion. This wrapper will translate any SQLExceptions thrown.
* <p>Note that, for the default implementation, JDBC RowSet support needs to
* be available at runtime: by default, a standard JDBC {@code CachedRowSet}
* is used.
* @param sql the SQL query to execute
* @param args arguments to bind to the query
* @param argTypes the SQL types of the arguments
* (constants from {@code java.sql.Types})
* @return an SqlRowSet representation (possibly a wrapper around a
* {@code javax.sql.rowset.CachedRowSet})
* @throws DataAccessException if there is any problem executing the query
* @see #queryForRowSet(String)
* @see SqlRowSetResultSetExtractor
* @see javax.sql.rowset.CachedRowSet
* @see java.sql.Types
*/
SqlRowSet queryForRowSet(String sql, @Nullable Object @Nullable [] args, int[] argTypes) throws DataAccessException;
/**
* Query given SQL to create a prepared statement from SQL and a list of
* arguments to bind to the query, expecting an SqlRowSet.
* <p>The results will be mapped to an SqlRowSet which holds the data in a
* disconnected fashion. This wrapper will translate any SQLExceptions thrown.
* <p>Note that, for the default implementation, JDBC RowSet support needs to
* be available at runtime: by default, a standard JDBC {@code CachedRowSet}
* is used.
* @param sql the SQL query to execute
* @param args arguments to bind to the query
* (leaving it to the PreparedStatement to guess the corresponding SQL type);
* may also contain {@link SqlParameterValue} objects which indicate not
* only the argument value but also the SQL type and optionally the scale
* @return an SqlRowSet representation (possibly a wrapper around a
* {@code javax.sql.rowset.CachedRowSet})
* @throws DataAccessException if there is any problem executing the query
* @see #queryForRowSet(String)
* @see SqlRowSetResultSetExtractor
* @see javax.sql.rowset.CachedRowSet
*/
SqlRowSet queryForRowSet(String sql, @Nullable Object @Nullable ... args) throws DataAccessException;
/**
* Issue a single SQL update operation (such as an insert, update or delete
* statement) using a PreparedStatementCreator to provide SQL and any
* required parameters.
* <p>A PreparedStatementCreator can either be implemented directly or
* configured through a PreparedStatementCreatorFactory.
* @param psc a callback that provides SQL and any necessary parameters
* @return the number of rows affected
* @throws DataAccessException if there is any problem issuing the update
* @see PreparedStatementCreatorFactory
*/
int update(PreparedStatementCreator psc) throws DataAccessException;
/**
* Issue an update statement using a PreparedStatementCreator to provide SQL and
* any required parameters. Generated keys will be put into the given KeyHolder.
* <p>Note that the given PreparedStatementCreator has to create a statement
* with activated extraction of generated keys (a JDBC 3.0 feature). This can
* either be done directly or through using a PreparedStatementCreatorFactory.
* <p>This method requires support for generated keys in the JDBC driver.
* @param psc a callback that provides SQL and any necessary parameters
* @param generatedKeyHolder a KeyHolder that will hold the generated keys
* @return the number of rows affected
* @throws DataAccessException if there is any problem issuing the update
* @see PreparedStatementCreatorFactory
* @see org.springframework.jdbc.support.GeneratedKeyHolder
* @see java.sql.DatabaseMetaData#supportsGetGeneratedKeys()
*/
int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder) throws DataAccessException;
/**
* Issue an update statement using a PreparedStatementSetter to set bind parameters,
* with given SQL. Simpler than using a PreparedStatementCreator as this method
* will create the PreparedStatement: The PreparedStatementSetter just needs to
* set parameters.
* @param sql the SQL containing bind parameters
* @param pss helper that sets bind parameters. If this is {@code null}
* we run an update with static SQL.
* @return the number of rows affected
* @throws DataAccessException if there is any problem issuing the update
*/
int update(String sql, @Nullable PreparedStatementSetter pss) throws DataAccessException;
/**
* Issue a single SQL update operation (such as an insert, update or delete statement)
* via a prepared statement, binding the given arguments.
* @param sql the SQL containing bind parameters
* @param args arguments to bind to the query
* @param argTypes the SQL types of the arguments
* (constants from {@code java.sql.Types})
* @return the number of rows affected
* @throws DataAccessException if there is any problem issuing the update
* @see java.sql.Types
*/
int update(String sql, @Nullable Object @Nullable [] args, int[] argTypes) throws DataAccessException;
/**
* Issue a single SQL update operation (such as an insert, update or delete statement)
* via a prepared statement, binding the given arguments.
* @param sql the SQL containing bind parameters
* @param args arguments to bind to the query
* (leaving it to the PreparedStatement to guess the corresponding SQL type);
* may also contain {@link SqlParameterValue} objects which indicate not
* only the argument value but also the SQL type and optionally the scale
* @return the number of rows affected
* @throws DataAccessException if there is any problem issuing the update
*/
int update(String sql, @Nullable Object @Nullable ... args) throws DataAccessException;
/**
* Issue multiple update statements on a single PreparedStatement,
* using batch updates and a BatchPreparedStatementSetter to set values.
* <p>Will fall back to separate updates on a single PreparedStatement
* if the JDBC driver does not support batch updates.
* @param sql defining PreparedStatement that will be reused.
* All statements in the batch will use the same SQL.
* @param pss object to set parameters on the PreparedStatement
* created by this method
* @return an array of the number of rows affected by each statement
* (may also contain special JDBC-defined negative values for affected rows such as
* {@link java.sql.Statement#SUCCESS_NO_INFO}/{@link java.sql.Statement#EXECUTE_FAILED})
* @throws DataAccessException if there is any problem issuing the update
*/
int[] batchUpdate(String sql, BatchPreparedStatementSetter pss) throws DataAccessException;
/**
* Issue multiple update statements on a single PreparedStatement,
* using batch updates and a BatchPreparedStatementSetter to set values.
* Generated keys will be put into the given KeyHolder.
* <p>Note that the given PreparedStatementCreator has to create a statement
* with activated extraction of generated keys (a JDBC 3.0 feature). This can
* either be done directly or through using a PreparedStatementCreatorFactory.
* <p>This method requires support for generated keys in the JDBC driver.
* It will fall back to separate updates on a single PreparedStatement
* if the JDBC driver does not support batch updates.
* @param psc a callback that creates a PreparedStatement given a Connection
* @param pss object to set parameters on the PreparedStatement
* created by this method
* @param generatedKeyHolder a KeyHolder that will hold the generated keys
* @return an array of the number of rows affected by each statement
* (may also contain special JDBC-defined negative values for affected rows such as
* {@link java.sql.Statement#SUCCESS_NO_INFO}/{@link java.sql.Statement#EXECUTE_FAILED})
* @throws DataAccessException if there is any problem issuing the update
* @since 6.1
* @see org.springframework.jdbc.support.GeneratedKeyHolder
* @see java.sql.DatabaseMetaData#supportsGetGeneratedKeys()
*/
int[] batchUpdate(PreparedStatementCreator psc, BatchPreparedStatementSetter pss,
KeyHolder generatedKeyHolder) throws DataAccessException;
/**
* Execute a batch using the supplied SQL statement with the batch of supplied arguments.
* @param sql the SQL statement to execute
* @param batchArgs the List of Object arrays containing the batch of arguments for the query
* @return an array containing the numbers of rows affected by each update in the batch
* (may also contain special JDBC-defined negative values for affected rows such as
* {@link java.sql.Statement#SUCCESS_NO_INFO}/{@link java.sql.Statement#EXECUTE_FAILED})
* @throws DataAccessException if there is any problem issuing the update
*/
int[] batchUpdate(String sql, List<Object[]> batchArgs) throws DataAccessException;
/**
* Execute a batch using the supplied SQL statement with the batch of supplied arguments.
* @param sql the SQL statement to execute.
* @param batchArgs the List of Object arrays containing the batch of arguments for the query
* @param argTypes the SQL types of the arguments
* (constants from {@code java.sql.Types})
* @return an array containing the numbers of rows affected by each update in the batch
* (may also contain special JDBC-defined negative values for affected rows such as
* {@link java.sql.Statement#SUCCESS_NO_INFO}/{@link java.sql.Statement#EXECUTE_FAILED})
* @throws DataAccessException if there is any problem issuing the update
*/
int[] batchUpdate(String sql, List<Object[]> batchArgs, int[] argTypes) throws DataAccessException;
/**
* Execute multiple batches using the supplied SQL statement with the collect of supplied
* arguments. The arguments' values will be set using the ParameterizedPreparedStatementSetter.
* Each batch should be of size indicated in 'batchSize'.
* @param sql the SQL statement to execute.
* @param batchArgs the List of Object arrays containing the batch of arguments for the query
* @param batchSize batch size
* @param pss the ParameterizedPreparedStatementSetter to use
* @return an array containing for each batch another array containing the numbers of
* rows affected by each update in the batch
* (may also contain special JDBC-defined negative values for affected rows such as
* {@link java.sql.Statement#SUCCESS_NO_INFO}/{@link java.sql.Statement#EXECUTE_FAILED})
* @throws DataAccessException if there is any problem issuing the update
* @since 3.1
*/
<T> int[][] batchUpdate(String sql, Collection<T> batchArgs, int batchSize,
ParameterizedPreparedStatementSetter<T> pss) throws DataAccessException;
//-------------------------------------------------------------------------
// Methods dealing with callable statements
//-------------------------------------------------------------------------
/**
* Execute a JDBC data access operation, implemented as callback action
* working on a JDBC CallableStatement. This allows for implementing arbitrary
* data access operations on a single Statement, within Spring's managed JDBC
* environment: that is, participating in Spring-managed transactions and
* converting JDBC SQLExceptions into Spring's DataAccessException hierarchy.
* <p>The callback action can return a result object, for example a domain
* object or a collection of domain objects.
* @param csc a callback that creates a CallableStatement given a Connection
* @param action a callback that specifies the action
* @return a result object returned by the action, or {@code null} if none
* @throws DataAccessException if there is any problem
*/
<T extends @Nullable Object> T execute(CallableStatementCreator csc, CallableStatementCallback<T> action) throws DataAccessException;
/**
* Execute a JDBC data access operation, implemented as callback action
* working on a JDBC CallableStatement. This allows for implementing arbitrary
* data access operations on a single Statement, within Spring's managed JDBC
* environment: that is, participating in Spring-managed transactions and
* converting JDBC SQLExceptions into Spring's DataAccessException hierarchy.
* <p>The callback action can return a result object, for example a domain
* object or a collection of domain objects.
* @param callString the SQL call string to execute
* @param action a callback that specifies the action
* @return a result object returned by the action, or {@code null} if none
* @throws DataAccessException if there is any problem
*/
<T extends @Nullable Object> T execute(String callString, CallableStatementCallback<T> action) throws DataAccessException;
/**
* Execute an SQL call using a CallableStatementCreator to provide SQL and
* any required parameters.
* @param csc a callback that provides SQL and any necessary parameters
* @param declaredParameters list of declared SqlParameter objects
* @return a Map of extracted out parameters
* @throws DataAccessException if there is any problem issuing the update
*/
Map<String, @Nullable Object> call(CallableStatementCreator csc, List<SqlParameter> declaredParameters)
throws DataAccessException;
}
| are |
java | grpc__grpc-java | examples/src/main/java/io/grpc/examples/header/HeaderServerInterceptor.java | {
"start": 966,
"end": 1855
} | class ____ implements ServerInterceptor {
private static final Logger logger = Logger.getLogger(HeaderServerInterceptor.class.getName());
@VisibleForTesting
static final Metadata.Key<String> CUSTOM_HEADER_KEY =
Metadata.Key.of("custom_server_header_key", Metadata.ASCII_STRING_MARSHALLER);
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
final Metadata requestHeaders,
ServerCallHandler<ReqT, RespT> next) {
logger.info("header received from client:" + requestHeaders);
return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
@Override
public void sendHeaders(Metadata responseHeaders) {
responseHeaders.put(CUSTOM_HEADER_KEY, "customRespondValue");
super.sendHeaders(responseHeaders);
}
}, requestHeaders);
}
}
| HeaderServerInterceptor |
java | apache__rocketmq | client/src/main/java/org/apache/rocketmq/client/trace/AsyncTraceDispatcher.java | {
"start": 2499,
"end": 9413
} | class ____ implements TraceDispatcher {
private static final Logger log = LoggerFactory.getLogger(AsyncTraceDispatcher.class);
private static final AtomicInteger COUNTER = new AtomicInteger();
private static final AtomicInteger INSTANCE_NUM = new AtomicInteger(0);
private static final long WAIT_FOR_SHUTDOWN = 5000L;
private volatile boolean stopped = false;
private final int traceInstanceId = INSTANCE_NUM.getAndIncrement();
private final int batchNum;
private final int maxMsgSize;
private final DefaultMQProducer traceProducer;
private AtomicLong discardCount;
private Thread worker;
private final ThreadPoolExecutor traceExecutor;
private final ArrayBlockingQueue<TraceContext> traceContextQueue;
private final ArrayBlockingQueue<Runnable> appenderQueue;
private volatile Thread shutDownHook;
private DefaultMQProducerImpl hostProducer;
private DefaultMQPushConsumerImpl hostConsumer;
private volatile ThreadLocalIndex sendWhichQueue = new ThreadLocalIndex();
private volatile String traceTopicName;
private AtomicBoolean isStarted = new AtomicBoolean(false);
private volatile AccessChannel accessChannel = AccessChannel.LOCAL;
private String group;
private Type type;
private String namespaceV2;
private final int flushTraceInterval = 5000;
private long lastFlushTime = System.currentTimeMillis();
public AsyncTraceDispatcher(String group, Type type, int batchNum, String traceTopicName, RPCHook rpcHook) {
this.batchNum = Math.min(batchNum, 20);/* max value 20*/
this.maxMsgSize = 128000;
this.discardCount = new AtomicLong(0L);
this.traceContextQueue = new ArrayBlockingQueue<>(2048);
this.group = group;
this.type = type;
this.appenderQueue = new ArrayBlockingQueue<>(2048);
if (!UtilAll.isBlank(traceTopicName)) {
this.traceTopicName = traceTopicName;
} else {
this.traceTopicName = TopicValidator.RMQ_SYS_TRACE_TOPIC;
}
this.traceExecutor = new ThreadPoolExecutor(//
2, //
4, //
1000 * 60, //
TimeUnit.MILLISECONDS, //
this.appenderQueue, //
new ThreadFactoryImpl("MQTraceSendThread_" + traceInstanceId + "_"));
traceProducer = getAndCreateTraceProducer(rpcHook);
}
public AccessChannel getAccessChannel() {
return accessChannel;
}
public void setAccessChannel(AccessChannel accessChannel) {
this.accessChannel = accessChannel;
}
public String getTraceTopicName() {
return traceTopicName;
}
public void setTraceTopicName(String traceTopicName) {
this.traceTopicName = traceTopicName;
}
public DefaultMQProducer getTraceProducer() {
return traceProducer;
}
public DefaultMQProducerImpl getHostProducer() {
return hostProducer;
}
public void setHostProducer(DefaultMQProducerImpl hostProducer) {
this.hostProducer = hostProducer;
}
public DefaultMQPushConsumerImpl getHostConsumer() {
return hostConsumer;
}
public void setHostConsumer(DefaultMQPushConsumerImpl hostConsumer) {
this.hostConsumer = hostConsumer;
}
public String getNamespaceV2() {
return namespaceV2;
}
public void setNamespaceV2(String namespaceV2) {
this.namespaceV2 = namespaceV2;
}
public void start(String nameSrvAddr, AccessChannel accessChannel) throws MQClientException {
if (isStarted.compareAndSet(false, true)) {
traceProducer.setNamesrvAddr(nameSrvAddr);
traceProducer.setInstanceName(TRACE_INSTANCE_NAME + "_" + nameSrvAddr);
traceProducer.setNamespaceV2(namespaceV2);
traceProducer.setEnableTrace(false);
traceProducer.start();
}
this.accessChannel = accessChannel;
this.worker = new ThreadFactoryImpl("MQ-AsyncArrayDispatcher-Thread" + traceInstanceId, true)
.newThread(new AsyncRunnable());
this.worker.setDaemon(true);
this.worker.start();
this.registerShutDownHook();
}
private DefaultMQProducer getAndCreateTraceProducer(RPCHook rpcHook) {
DefaultMQProducer traceProducerInstance = this.traceProducer;
if (traceProducerInstance == null) {
traceProducerInstance = new DefaultMQProducer(rpcHook);
traceProducerInstance.setProducerGroup(genGroupNameForTrace());
traceProducerInstance.setSendMsgTimeout(5000);
traceProducerInstance.setVipChannelEnabled(false);
// The max size of message is 128K
traceProducerInstance.setMaxMessageSize(maxMsgSize);
}
return traceProducerInstance;
}
private String genGroupNameForTrace() {
return TraceConstants.GROUP_NAME_PREFIX + "-" + this.group + "-" + this.type + "-" + COUNTER.incrementAndGet();
}
@Override
public boolean append(final Object ctx) {
boolean result = traceContextQueue.offer((TraceContext) ctx);
if (!result) {
log.info("buffer full" + discardCount.incrementAndGet() + " ,context is " + ctx);
}
return result;
}
@Override
public void flush() {
while (traceContextQueue.size() > 0) {
try {
flushTraceContext(true);
} catch (Throwable throwable) {
log.error("flushTraceContext error", throwable);
}
}
}
@Override
public void shutdown() {
flush();
ThreadUtils.shutdownGracefully(this.traceExecutor, WAIT_FOR_SHUTDOWN, TimeUnit.MILLISECONDS);
if (isStarted.get()) {
traceProducer.shutdown();
}
this.removeShutdownHook();
stopped = true;
}
public void registerShutDownHook() {
if (shutDownHook == null) {
shutDownHook = new Thread(new Runnable() {
private volatile boolean hasShutdown = false;
@Override
public void run() {
synchronized (this) {
if (!this.hasShutdown) {
flush();
}
}
}
}, "ShutdownHookMQTrace");
try {
Runtime.getRuntime().addShutdownHook(shutDownHook);
} catch (IllegalStateException e) {
// ignore - VM is already shutting down
}
}
}
public void removeShutdownHook() {
if (shutDownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(shutDownHook);
} catch (IllegalStateException e) {
// ignore - VM is already shutting down
}
}
}
| AsyncTraceDispatcher |
java | spring-projects__spring-boot | module/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfiguration.java | {
"start": 20488,
"end": 20693
} | class ____ extends AnyNestedCondition {
FlywayDataSourceCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnBean(DataSource.class)
private static final | FlywayDataSourceCondition |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.java | {
"start": 1787,
"end": 9657
} | class ____ implements DatabasePopulator {
List<Resource> scripts = new ArrayList<>();
private @Nullable String sqlScriptEncoding;
private String separator = ScriptUtils.DEFAULT_STATEMENT_SEPARATOR;
private String[] commentPrefixes = ScriptUtils.DEFAULT_COMMENT_PREFIXES;
private String blockCommentStartDelimiter = ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER;
private String blockCommentEndDelimiter = ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER;
private boolean continueOnError = false;
private boolean ignoreFailedDrops = false;
/**
* Construct a new {@code ResourceDatabasePopulator} with default settings.
* @since 4.0.3
*/
public ResourceDatabasePopulator() {
}
/**
* Construct a new {@code ResourceDatabasePopulator} with default settings
* for the supplied scripts.
* @param scripts the scripts to execute to initialize or clean up the database
* (never {@code null})
* @since 4.0.3
*/
public ResourceDatabasePopulator(Resource... scripts) {
setScripts(scripts);
}
/**
* Construct a new {@code ResourceDatabasePopulator} with the supplied values.
* @param continueOnError flag to indicate that all failures in SQL should be
* logged but not cause a failure
* @param ignoreFailedDrops flag to indicate that a failed SQL {@code DROP}
* statement can be ignored
* @param sqlScriptEncoding the encoding for the supplied SQL scripts
* (may be {@code null} or <em>empty</em> to indicate platform encoding)
* @param scripts the scripts to execute to initialize or clean up the database
* (never {@code null})
* @since 4.0.3
*/
public ResourceDatabasePopulator(boolean continueOnError, boolean ignoreFailedDrops,
@Nullable String sqlScriptEncoding, Resource... scripts) {
this.continueOnError = continueOnError;
this.ignoreFailedDrops = ignoreFailedDrops;
setSqlScriptEncoding(sqlScriptEncoding);
setScripts(scripts);
}
/**
* Add a script to execute to initialize or clean up the database.
* @param script the path to an SQL script (never {@code null})
*/
public void addScript(Resource script) {
Assert.notNull(script, "'script' must not be null");
this.scripts.add(script);
}
/**
* Add multiple scripts to execute to initialize or clean up the database.
* @param scripts the scripts to execute (never {@code null})
*/
public void addScripts(Resource... scripts) {
assertContentsOfScriptArray(scripts);
this.scripts.addAll(Arrays.asList(scripts));
}
/**
* Set the scripts to execute to initialize or clean up the database,
* replacing any previously added scripts.
* @param scripts the scripts to execute (never {@code null})
*/
public void setScripts(Resource... scripts) {
assertContentsOfScriptArray(scripts);
// Ensure that the list is modifiable
this.scripts = new ArrayList<>(Arrays.asList(scripts));
}
private void assertContentsOfScriptArray(Resource... scripts) {
Assert.notNull(scripts, "'scripts' must not be null");
Assert.noNullElements(scripts, "'scripts' must not contain null elements");
}
/**
* Specify the encoding for the configured SQL scripts,
* if different from the platform encoding.
* @param sqlScriptEncoding the encoding used in scripts
* (may be {@code null} or empty to indicate platform encoding)
* @see #addScript(Resource)
*/
public void setSqlScriptEncoding(@Nullable String sqlScriptEncoding) {
this.sqlScriptEncoding = (StringUtils.hasText(sqlScriptEncoding) ? sqlScriptEncoding : null);
}
/**
* Specify the statement separator, if a custom one.
* <p>Defaults to {@code ";"} if not specified and falls back to {@code "\n"}
* as a last resort; may be set to {@link ScriptUtils#EOF_STATEMENT_SEPARATOR}
* to signal that each script contains a single statement without a separator.
* @param separator the script statement separator
*/
public void setSeparator(String separator) {
this.separator = separator;
}
/**
* Set the prefix that identifies single-line comments within the SQL scripts.
* <p>Defaults to {@code "--"}.
* @param commentPrefix the prefix for single-line comments
* @see #setCommentPrefixes(String...)
*/
public void setCommentPrefix(String commentPrefix) {
Assert.hasText(commentPrefix, "'commentPrefix' must not be null or empty");
this.commentPrefixes = new String[] { commentPrefix };
}
/**
* Set the prefixes that identify single-line comments within the SQL scripts.
* <p>Defaults to {@code ["--"]}.
* @param commentPrefixes the prefixes for single-line comments
* @since 5.2
*/
public void setCommentPrefixes(String... commentPrefixes) {
Assert.notEmpty(commentPrefixes, "'commentPrefixes' must not be null or empty");
Assert.noNullElements(commentPrefixes, "'commentPrefixes' must not contain null elements");
this.commentPrefixes = commentPrefixes;
}
/**
* Set the start delimiter that identifies block comments within the SQL
* scripts.
* <p>Defaults to {@code "/*"}.
* @param blockCommentStartDelimiter the start delimiter for block comments
* (never {@code null} or empty)
* @since 4.0.3
* @see #setBlockCommentEndDelimiter
*/
public void setBlockCommentStartDelimiter(String blockCommentStartDelimiter) {
Assert.hasText(blockCommentStartDelimiter, "'blockCommentStartDelimiter' must not be null or empty");
this.blockCommentStartDelimiter = blockCommentStartDelimiter;
}
/**
* Set the end delimiter that identifies block comments within the SQL
* scripts.
* <p>Defaults to <code>"*/"</code>.
* @param blockCommentEndDelimiter the end delimiter for block comments
* (never {@code null} or empty)
* @since 4.0.3
* @see #setBlockCommentStartDelimiter
*/
public void setBlockCommentEndDelimiter(String blockCommentEndDelimiter) {
Assert.hasText(blockCommentEndDelimiter, "'blockCommentEndDelimiter' must not be null or empty");
this.blockCommentEndDelimiter = blockCommentEndDelimiter;
}
/**
* Flag to indicate that all failures in SQL should be logged but not cause a failure.
* <p>Defaults to {@code false}.
* @param continueOnError {@code true} if script execution should continue on error
*/
public void setContinueOnError(boolean continueOnError) {
this.continueOnError = continueOnError;
}
/**
* Flag to indicate that a failed SQL {@code DROP} statement can be ignored.
* <p>This is useful for a non-embedded database whose SQL dialect does not
* support an {@code IF EXISTS} clause in a {@code DROP} statement.
* <p>The default is {@code false} so that if the populator runs accidentally, it will
* fail fast if a script starts with a {@code DROP} statement.
* @param ignoreFailedDrops {@code true} if failed drop statements should be ignored
*/
public void setIgnoreFailedDrops(boolean ignoreFailedDrops) {
this.ignoreFailedDrops = ignoreFailedDrops;
}
/**
* {@inheritDoc}
* @see #execute(DataSource)
*/
@Override
public void populate(Connection connection) throws ScriptException {
Assert.notNull(connection, "'connection' must not be null");
for (Resource script : this.scripts) {
EncodedResource encodedScript = new EncodedResource(script, this.sqlScriptEncoding);
ScriptUtils.executeSqlScript(connection, encodedScript, this.continueOnError, this.ignoreFailedDrops,
this.commentPrefixes, this.separator, this.blockCommentStartDelimiter, this.blockCommentEndDelimiter);
}
}
/**
* Execute this {@code ResourceDatabasePopulator} against the given
* {@link DataSource}.
* <p>Delegates to {@link DatabasePopulatorUtils#execute}.
* @param dataSource the {@code DataSource} to execute against (never {@code null})
* @throws ScriptException if an error occurs
* @since 4.1
* @see #populate(Connection)
*/
public void execute(DataSource dataSource) throws ScriptException {
DatabasePopulatorUtils.execute(this, dataSource);
}
}
| ResourceDatabasePopulator |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/InverseDistributionFunction.java | {
"start": 4810,
"end": 7248
} | class ____<T> extends SelfRenderingSqmOrderedSetAggregateFunction<T> {
public SelfRenderingInverseDistributionFunction(
List<? extends SqmTypedNode<?>> arguments,
SqmPredicate filter,
SqmOrderByClause withinGroupClause,
ReturnableType<T> impliedResultType,
QueryEngine queryEngine) {
super(
InverseDistributionFunction.this,
InverseDistributionFunction.this,
arguments,
filter,
withinGroupClause,
impliedResultType,
InverseDistributionFunction.this.getArgumentsValidator(),
InverseDistributionFunction.this.getReturnTypeResolver(),
queryEngine.getCriteriaBuilder(),
InverseDistributionFunction.this.getName()
);
if ( withinGroupClause == null ) {
throw new SemanticException("Inverse distribution function '" + getFunctionName()
+ "' must specify 'WITHIN GROUP'");
}
}
@Override
protected ReturnableType<?> determineResultType(
SqmToSqlAstConverter converter,
TypeConfiguration typeConfiguration) {
return (ReturnableType<?>)
getWithinGroup().getSortSpecifications().get( 0 )
.getSortExpression()
.getExpressible()
.getSqmType();
}
@Override
protected MappingModelExpressible<?> getMappingModelExpressible(
SqmToSqlAstConverter walker,
ReturnableType<?> resultType,
List<SqlAstNode> arguments) {
MappingModelExpressible<?> mapping;
if ( resultType instanceof MappingModelExpressible<?> mappingModelExpressible) {
// here we have a BasicType, which can be cast
// directly to BasicValuedMapping
mapping = mappingModelExpressible;
}
else {
// here we have something that is not a BasicType,
// and we have no way to get a BasicValuedMapping
// from it directly
final Expression expression = (Expression)
getWithinGroup().getSortSpecifications().get( 0 )
.getSortExpression()
.accept( walker );
final JdbcMappingContainer expressionType = expression.getExpressionType();
if ( expressionType instanceof BasicValuedMapping basicValuedMapping ) {
return basicValuedMapping;
}
try {
return walker.getCreationContext().getMappingMetamodel()
.resolveMappingExpressible( getNodeType(), walker.getFromClauseAccess()::getTableGroup );
}
catch (Exception e) {
return null; // this works at least approximately
}
}
return mapping;
}
}
}
| SelfRenderingInverseDistributionFunction |
java | google__error-prone | core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java | {
"start": 13077,
"end": 13511
} | class ____ {
java.util.Map.Entry<String, Integer> f() {
// BUG: Diagnostic contains: return (Entry) null;
return null;
}
}
""")
.doTest();
}
@Test
public void qualifiedName_notImported() {
CompilationTestHelper.newInstance(CastReturn.class, getClass())
.addSourceLines(
"Test.java",
"""
| Test |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsNotCloseToPercentage_Test.java | {
"start": 1803,
"end": 4706
} | class ____ extends BigIntegersBaseTest {
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertIsNotCloseToPercentage(someInfo(), null, ONE,
withPercentage(1)))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_expected_value_is_null() {
assertThatNullPointerException().isThrownBy(() -> numbers.assertIsNotCloseToPercentage(someInfo(), ONE, null,
withPercentage(1)));
}
@Test
void should_fail_if_percentage_is_null() {
assertThatNullPointerException().isThrownBy(() -> numbers.assertIsNotCloseToPercentage(someInfo(), ONE, ZERO, null));
}
@Test
void should_fail_if_percentage_is_negative() {
assertThatIllegalArgumentException().isThrownBy(() -> numbers.assertIsNotCloseToPercentage(someInfo(), ONE, ZERO,
withPercentage(-1)));
}
@ParameterizedTest
@CsvSource({
"1, 2, 1",
"1, 11, 90",
"-1, -2, 1",
"-1, -11, 90",
"0, -1, 99"
})
void should_pass_if_difference_is_greater_than_given_percentage(BigInteger actual, BigInteger other,
Integer percentage) {
numbers.assertIsNotCloseToPercentage(someInfo(), actual, other, withPercentage(percentage));
}
@ParameterizedTest
@CsvSource({
"1, 1, 0",
"2, 1, 100",
"1, 2, 50",
"-1, -1, 0",
"-2, -1, 100",
"-1, -2, 50"
})
void should_fail_if_difference_is_equal_to_given_percentage(BigInteger actual, BigInteger other,
Integer percentage) {
AssertionInfo info = someInfo();
Throwable error = catchThrowable(() -> numbers.assertIsNotCloseToPercentage(info, actual, other, withPercentage(percentage)));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldNotBeEqualWithinPercentage(actual, other, withinPercentage(percentage),
actual.subtract(other).abs()));
}
@Test
void should_fail_if_actual_is_close_enough_to_expected_value() {
AssertionInfo info = someInfo();
Throwable error = catchThrowable(() -> numbers.assertIsNotCloseToPercentage(someInfo(), ONE, TEN, withPercentage(100)));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info,
shouldNotBeEqualWithinPercentage(ONE, TEN, withinPercentage(100), TEN.subtract(ONE)));
}
}
| BigIntegers_assertIsNotCloseToPercentage_Test |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/signatures/ProcessorSignatureTest.java | {
"start": 1316,
"end": 5024
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(BeanProducingAProcessorOfMessage.class,
BeanProducingAProcessorOfPayload.class,
BeanProducingAProcessorBuilderOfMessage.class,
BeanProducingAProcessorBuilderOfPayload.class,
BeanProducingAPublisherOfPayload.class,
BeanProducingAPublisherOfMessage.class,
BeanProducingAPublisherBuilderOfPayload.class,
BeanProducingAPublisherBuilderOfMessage.class,
BeanConsumingMessages.class,
BeanConsumingPayloads.class,
BeanConsumingMessagesAsynchronously.class,
BeanConsumingPayloadsAsynchronously.class,
Spy.class));
@Inject
BeanProducingAProcessorOfMessage beanProducingAProcessorOfMessage;
@Inject
BeanProducingAProcessorOfPayload beanProducingAProcessorOfPayload;
@Inject
BeanProducingAProcessorBuilderOfMessage beanProducingAPublisherBuilderOfMessage;
@Inject
BeanProducingAProcessorBuilderOfPayload beanProducingAProcessorBuilderOfPayload;
@Inject
BeanProducingAPublisherOfPayload beanProducingAPublisherOfPayload;
@Inject
BeanProducingAPublisherOfMessage beanProducingAPublisherOfMessage;
@Inject
BeanProducingAPublisherBuilderOfPayload beanProducingAPublisherBuilderOfPayloads;
@Inject
BeanProducingAPublisherBuilderOfMessage beanProducingAPublisherBuilderOfMessages;
@Inject
BeanConsumingMessages beanConsumingMessages;
@Inject
BeanConsumingPayloads beanConsumingPayloads;
@Inject
BeanConsumingMessagesAsynchronously beanConsumingMessagesAsynchronously;
@Inject
BeanConsumingPayloadsAsynchronously beanConsumingPayloadsAsynchronously;
@AfterAll
public static void close() {
Spy.executor.shutdown();
}
@Test
public void test() {
check(beanProducingAProcessorOfMessage);
check(beanProducingAPublisherBuilderOfMessage);
check(beanProducingAProcessorOfPayload);
check(beanProducingAProcessorBuilderOfPayload);
checkDouble(beanProducingAPublisherOfPayload);
checkDouble(beanProducingAPublisherOfMessage);
checkDouble(beanProducingAPublisherBuilderOfMessages);
checkDouble(beanProducingAPublisherBuilderOfPayloads);
check(beanConsumingMessages);
check(beanConsumingPayloads);
check(beanConsumingPayloadsAsynchronously);
check(beanConsumingMessagesAsynchronously);
}
private void check(Spy spy) {
new Thread(() -> {
for (int i = 0; i < 10; i++) {
spy.getEmitter().send(i);
}
spy.getEmitter().complete();
}).start();
await().until(() -> spy.getItems().size() == 10);
assertThat(spy.getItems()).containsExactly("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
}
private void checkDouble(Spy spy) {
new Thread(() -> {
for (int i = 0; i < 10; i++) {
spy.getEmitter().send(i);
}
spy.getEmitter().complete();
}).start();
await().until(() -> spy.getItems().size() == 20);
assertThat(spy.getItems()).containsExactly("0", "0", "1", "1", "2", "2", "3", "3", "4", "4",
"5", "5", "6", "6", "7", "7", "8", "8", "9", "9");
}
@ApplicationScoped
public static | ProcessorSignatureTest |
java | bumptech__glide | library/test/src/test/java/com/bumptech/glide/signature/ApplicationVersionSignatureTest.java | {
"start": 876,
"end": 2764
} | class ____ {
@Rule public final KeyTester keyTester = new KeyTester();
private Context context;
@Before
public void setUp() {
context = ApplicationProvider.getApplicationContext();
}
@After
public void tearDown() {
ApplicationVersionSignature.reset();
}
@Test
public void testCanGetKeyForSignature() {
Key key = ApplicationVersionSignature.obtain(context);
assertNotNull(key);
}
@Test
public void testKeyForSignatureIsTheSameAcrossCallsInTheSamePackage()
throws NoSuchAlgorithmException, UnsupportedEncodingException {
keyTester
.addEquivalenceGroup(
ApplicationVersionSignature.obtain(context),
ApplicationVersionSignature.obtain(context))
.addEquivalenceGroup(new ObjectKey("test"))
.addRegressionTest(
ApplicationVersionSignature.obtain(context),
"5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9")
.test();
}
@Test
public void testUnresolvablePackageInfo() throws NameNotFoundException {
Context context = mock(Context.class, Answers.RETURNS_DEEP_STUBS);
String packageName = "my.package";
when(context.getPackageName()).thenReturn(packageName);
when(context.getPackageManager().getPackageInfo(packageName, 0))
.thenThrow(new NameNotFoundException("test"));
Key key = ApplicationVersionSignature.obtain(context);
assertNotNull(key);
}
@Test
public void testMissingPackageInfo() throws NameNotFoundException {
Context context = mock(Context.class, Answers.RETURNS_DEEP_STUBS);
String packageName = "my.package";
when(context.getPackageName()).thenReturn(packageName);
when(context.getPackageManager().getPackageInfo(packageName, 0)).thenReturn(null);
Key key = ApplicationVersionSignature.obtain(context);
assertNotNull(key);
}
}
| ApplicationVersionSignatureTest |
java | FasterXML__jackson-databind | src/test/java/perf/ObjectWriterTestBase.java | {
"start": 165,
"end": 3965
} | class ____<T1,T2>
{
protected int hash;
protected abstract int targetSizeMegs();
protected void test(ObjectMapper mapper,
String desc1, T1 inputValue1, Class<? extends T1> inputClass1,
String desc2, T2 inputValue2, Class<? extends T2> inputClass2)
throws Exception
{
final int REPS;
{
final byte[] input1 = mapper.writeValueAsBytes(inputValue1);
final byte[] input2 = mapper.writeValueAsBytes(inputValue2);
// Let's try to guestimate suitable size, N megs of output
REPS = (int) ((double) (targetSizeMegs() * 1000 * 1000) / (double) input1.length);
System.out.printf("Read %d bytes to bind (%d as array); will do %d repetitions\n",
input1.length, input2.length, REPS);
}
final ObjectWriter writer0 = mapper.writer().with(SerializationFeature.EAGER_SERIALIZER_FETCH);
final ObjectWriter writer1 = writer0.forType(inputClass1);
final ObjectWriter writer2 = writer0.forType(inputClass2);
int i = 0;
int roundsDone = 0;
final int TYPES = 2;
// Skip first 5 seconds
long startMeasure = System.currentTimeMillis() + 5000L;
System.out.print("Warming up");
final double[] timesMsec = new double[TYPES];
while (true) {
final int round = (i % TYPES);
final boolean lf = (++i % TYPES) == 0;
String msg;
ObjectWriter writer;
Object value;
switch (round) {
case 0:
msg = desc1;
writer = writer1;
value = inputValue1;
break;
case 1:
msg = desc2;
writer = writer2;
value = inputValue2;
break;
default:
throw new Error();
}
double msecs = testSer(REPS, value, writer);
// skip first N seconds to let results stabilize
if (startMeasure > 0L) {
if ((round != 0) || (System.currentTimeMillis() < startMeasure)) {
System.out.print(".");
continue;
}
startMeasure = 0L;
System.out.println();
System.out.println("Starting measurements...");
Thread.sleep(250L);
System.out.println();
}
timesMsec[round] += msecs;
if ((i % 17) == 0) {
System.out.println("[GC]");
Thread.sleep(100L);
System.gc();
Thread.sleep(100L);
}
System.out.printf("Test '%s' [hash: 0x%s] -> %.1f msecs\n", msg, hash, msecs);
Thread.sleep(50L);
if (!lf) {
continue;
}
if ((++roundsDone % 3) == 0) {
double den = (double) roundsDone;
System.out.printf("Averages after %d rounds (%s/%s): %.1f / %.1f msecs\n",
roundsDone, desc1, desc2,
timesMsec[0] / den, timesMsec[1] / den);
}
System.out.println();
}
}
protected double testSer(int REPS, Object value, ObjectWriter writer) throws Exception
{
final NopOutputStream out = new NopOutputStream();
long start = System.nanoTime();
while (--REPS >= 0) {
writer.writeValue(out, value);
}
hash = out.size();
long nanos = System.nanoTime() - start;
out.close();
return _msecsFromNanos(nanos);
}
protected final double _msecsFromNanos(long nanos) {
return (nanos / 1000000.0);
}
}
| ObjectWriterTestBase |
java | quarkusio__quarkus | independent-projects/tools/devtools-common/src/main/java/io/quarkus/platform/catalog/predicate/ExtensionPredicate.java | {
"start": 519,
"end": 5698
} | class ____ implements Predicate<Extension> {
private final String q;
public ExtensionPredicate(String keyword) {
this.q = Objects.requireNonNull(keyword, "keyword must not be null").trim().toLowerCase();
}
public static Predicate<Extension> create(String keyword) {
return new ExtensionPredicate(keyword);
}
public static boolean isPattern(String keyword) {
for (char c : keyword.toCharArray()) {
switch (c) {
case '*':
case '?':
case '^': // escape character in cmd.exe
case '(':
case ')':
case '[':
case ']':
case '$':
case '.':
case '{':
case '}':
case '|':
case '\\':
return true;
}
}
return false;
}
@Override
public boolean test(Extension extension) {
final ExtensionProcessor extensionMetadata = ExtensionProcessor.of(extension);
if (extensionMetadata.isUnlisted()) {
return false;
}
String extensionName = Objects.toString(extension.getName(), "");
String shortName = Objects.toString(extensionMetadata.getShortName(), "");
// Try exact matches
if (isExactMatch(extension)) {
return true;
}
// Try short names
if (matchesShortName(extension, q)) {
return true;
}
// Partial matches on name, artifactId and short names
if (extensionName.toLowerCase().contains(q)
|| extension.getArtifact().getArtifactId().toLowerCase().contains(q)
|| shortName.toLowerCase().contains(q)) {
return true;
}
// find by keyword
if (extensionMetadata.getExtendedKeywords().contains(q)) {
return true;
}
// find by pattern
Pattern pattern = toRegex(q);
return pattern != null && (pattern.matcher(extensionName.toLowerCase()).matches()
|| pattern.matcher(extension.getArtifact().getArtifactId().toLowerCase()).matches()
|| pattern.matcher(shortName.toLowerCase()).matches()
|| matchLabels(pattern, extensionMetadata.getKeywords()));
}
public boolean isExactMatch(Extension extension) {
String extensionName = Objects.toString(extension.getName(), "");
// Try exact matches
if (extensionName.equalsIgnoreCase(q) ||
matchesArtifactId(extension.getArtifact().getArtifactId(), q)) {
return true;
}
return false;
}
private static boolean matchesShortName(Extension extension, String q) {
return q.equalsIgnoreCase(getShortName(extension));
}
private static boolean matchesArtifactId(String artifactId, String q) {
return artifactId.equalsIgnoreCase(q) ||
artifactId.equalsIgnoreCase("quarkus-" + q);
}
private static boolean matchLabels(Pattern pattern, List<String> labels) {
boolean matches = false;
// if any label match it's ok
for (String label : labels) {
matches = matches || pattern.matcher(label.toLowerCase()).matches();
}
return matches;
}
private static Pattern toRegex(final String str) {
try {
String wildcardToRegex = wildcardToRegex(str);
if (wildcardToRegex != null && !wildcardToRegex.isEmpty()) {
return Pattern.compile(wildcardToRegex, Pattern.CASE_INSENSITIVE);
}
} catch (PatternSyntaxException e) {
//ignore it
}
return null;
}
private static String wildcardToRegex(String wildcard) {
if (wildcard == null || wildcard.isEmpty()) {
return null;
}
// don't try with file match char in pattern
if (!(wildcard.contains("*") || wildcard.contains("?"))) {
return null;
}
StringBuilder s = new StringBuilder(wildcard.length());
s.append("^.*");
for (int i = 0, is = wildcard.length(); i < is; i++) {
char c = wildcard.charAt(i);
switch (c) {
case '*':
s.append(".*");
break;
case '?':
s.append(".");
break;
case '^': // escape character in cmd.exe
s.append("\\");
break;
// escape special regexp-characters
case '(':
case ')':
case '[':
case ']':
case '$':
case '.':
case '{':
case '}':
case '|':
case '\\':
s.append("\\");
s.append(c);
break;
default:
s.append(c);
break;
}
}
s.append(".*$");
return (s.toString());
}
}
| ExtensionPredicate |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/mapper/RootObjectMapperTests.java | {
"start": 29638,
"end": 30584
} | class ____ implements RootObjectMapperNamespaceValidator {
private final String disallowed;
private final String errorMessage;
TestRootObjectMapperNamespaceValidator(String disallowedNamespace, String errorMessage) {
this.disallowed = disallowedNamespace;
this.errorMessage = errorMessage;
}
@Override
public void validateNamespace(ObjectMapper.Subobjects subobjects, String name) {
if (name.equals(disallowed)) {
throw new IllegalArgumentException(errorMessage);
} else if (subobjects != ObjectMapper.Subobjects.ENABLED) {
// name here will be something like _project.my_field, rather than just _project
if (name.startsWith(disallowed + ".")) {
throw new IllegalArgumentException(errorMessage);
}
}
}
}
}
| TestRootObjectMapperNamespaceValidator |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/leaderretrieval/ZooKeeperLeaderRetrievalConnectionHandlingTest.java | {
"start": 13909,
"end": 15467
} | class ____ implements LeaderRetrievalEventHandler {
private final BlockingQueue<LeaderInformation> queue;
public QueueLeaderElectionListener(int expectedCalls) {
this.queue = new ArrayBlockingQueue<>(expectedCalls);
}
@Override
public void notifyLeaderAddress(LeaderInformation leaderInformation) {
try {
queue.put(leaderInformation);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
public LeaderInformation next() {
try {
return queue.take();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
public Optional<LeaderInformation> next(Duration timeout) {
try {
return Optional.ofNullable(
this.queue.poll(timeout.toMillis(), TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
/**
* Clears any unhandled events. This is useful in cases where there was an unplanned
* reconnect after the test passed to prepare the shutdown. Outstanding events might cause
* an {@link InterruptedException} during shutdown, otherwise.
*/
public void clearUnhandledEvents() {
while (!queue.isEmpty()) {
queue.poll();
}
}
}
}
| QueueLeaderElectionListener |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/server/ui/OneTimeTokenSubmitPageGeneratingWebFilterTests.java | {
"start": 1141,
"end": 4936
} | class ____ {
private final OneTimeTokenSubmitPageGeneratingWebFilter filter = new OneTimeTokenSubmitPageGeneratingWebFilter();
@Test
void filterWhenTokenQueryParamThenShouldIncludeJavascriptToAutoSubmitFormAndInputHasTokenValue() {
MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.get("/login/ott").queryParam("token", "test"));
this.filter.filter(exchange, (e) -> Mono.empty()).block();
assertThat(exchange.getResponse().getBodyAsString().block()).contains(
"<input type=\"text\" id=\"token\" name=\"token\" value=\"test\" placeholder=\"Token\" required=\"true\" autofocus=\"autofocus\"/>");
}
@Test
void setRequestMatcherWhenNullThenException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestMatcher(null));
}
@Test
void setLoginProcessingUrlWhenNullOrEmptyThenException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setLoginProcessingUrl(null));
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setLoginProcessingUrl(""));
}
@Test
void setLoginProcessingUrlThenUseItForFormAction() {
this.filter.setLoginProcessingUrl("/login/another");
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/login/ott"));
this.filter.filter(exchange, (e) -> Mono.empty()).block();
assertThat(exchange.getResponse().getBodyAsString().block())
.contains("<form class=\"login-form\" action=\"/login/another\" method=\"post\">");
}
@Test
void setContextThenGenerates() {
MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.get("/test/login/ott").contextPath("/test"));
this.filter.setLoginProcessingUrl("/login/another");
this.filter.filter(exchange, (e) -> Mono.empty()).block();
assertThat(exchange.getResponse().getBodyAsString().block())
.contains("<form class=\"login-form\" action=\"/test/login/another\" method=\"post\">");
}
@Test
void filterWhenTokenQueryParamUsesSpecialCharactersThenValueIsEscaped() {
MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.get("/login/ott").queryParam("token", "this<>!@#\""));
this.filter.filter(exchange, (e) -> Mono.empty()).block();
assertThat(exchange.getResponse().getBodyAsString().block()).contains(
"<input type=\"text\" id=\"token\" name=\"token\" value=\"this<>!@#"\" placeholder=\"Token\" required=\"true\" autofocus=\"autofocus\"/>");
}
@Test
void filterThenRenders() {
MockServerWebExchange exchange = MockServerWebExchange
.from(MockServerHttpRequest.get("/login/ott").queryParam("token", "this<>!@#\""));
this.filter.setLoginProcessingUrl("/login/another");
this.filter.filter(exchange, (e) -> Mono.empty()).block();
assertThat(exchange.getResponse().getBodyAsString().block()).isEqualTo(
"""
<!DOCTYPE html>
<html lang="en">
<head>
<title>One-Time Token Login</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<link href="/default-ui.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<form class="login-form" action="/login/another" method="post">
<h2>Please input the token</h2>
<p>
<label for="token" class="screenreader">Token</label>
<input type="text" id="token" name="token" value="this<>!@#"" placeholder="Token" required="true" autofocus="autofocus"/>
</p>
<button class="primary" type="submit">Sign in</button>
</form>
</div>
</body>
</html>
""");
}
}
| OneTimeTokenSubmitPageGeneratingWebFilterTests |
java | spring-projects__spring-framework | framework-docs/src/main/java/org/springframework/docs/integration/jms/jmssendingjmsclient/JmsClientSample.java | {
"start": 898,
"end": 1559
} | class ____ {
private final JmsClient jmsClient;
public JmsClientSample(ConnectionFactory connectionFactory) {
// For custom options, use JmsClient.builder(ConnectionFactory)
this.jmsClient = JmsClient.create(connectionFactory);
}
public void sendWithConversion() {
this.jmsClient.destination("myQueue")
.withTimeToLive(1000)
.send("myPayload"); // optionally with a headers Map next to the payload
}
public void sendCustomMessage() {
Message<?> message = MessageBuilder.withPayload("myPayload").build(); // optionally with headers
this.jmsClient.destination("myQueue")
.withTimeToLive(1000)
.send(message);
}
}
| JmsClientSample |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/crypto/key/kms/TestLoadBalancingKMSClientProvider.java | {
"start": 2933,
"end": 9672
} | class ____ {
@BeforeAll
public static void setup() throws IOException {
SecurityUtil.setTokenServiceUseIp(false);
}
@Test
public void testCreation() throws Exception {
Configuration conf = new Configuration();
KeyProvider kp = new KMSClientProvider.Factory().createProvider(new URI(
"kms://http@host1:9600/kms/foo"), conf);
assertTrue(kp instanceof LoadBalancingKMSClientProvider);
KMSClientProvider[] providers =
((LoadBalancingKMSClientProvider) kp).getProviders();
assertEquals(1, providers.length);
assertEquals(new HashSet<>(Collections.singleton("http://host1:9600/kms/foo/v1/")),
new HashSet<>(Collections.singleton(providers[0].getKMSUrl())));
kp = new KMSClientProvider.Factory().createProvider(new URI(
"kms://http@host1;host2;host3:9600/kms/foo"), conf);
assertTrue(kp instanceof LoadBalancingKMSClientProvider);
providers =
((LoadBalancingKMSClientProvider) kp).getProviders();
assertEquals(3, providers.length);
assertEquals(new HashSet<>(Arrays.asList("http://host1:9600/kms/foo/v1/",
"http://host2:9600/kms/foo/v1/",
"http://host3:9600/kms/foo/v1/")),
new HashSet<>(Arrays.asList(providers[0].getKMSUrl(),
providers[1].getKMSUrl(),
providers[2].getKMSUrl())));
kp = new KMSClientProvider.Factory().createProvider(new URI(
"kms://http@host1;host2;host3:9600/kms/foo"), conf);
assertTrue(kp instanceof LoadBalancingKMSClientProvider);
providers =
((LoadBalancingKMSClientProvider) kp).getProviders();
assertEquals(3, providers.length);
assertEquals(new HashSet<>(Arrays.asList("http://host1:9600/kms/foo/v1/",
"http://host2:9600/kms/foo/v1/",
"http://host3:9600/kms/foo/v1/")),
new HashSet<>(Arrays.asList(providers[0].getKMSUrl(),
providers[1].getKMSUrl(),
providers[2].getKMSUrl())));
}
@Test
public void testLoadBalancing() throws Exception {
Configuration conf = new Configuration();
KMSClientProvider p1 = mock(KMSClientProvider.class);
when(p1.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenReturn(
new KMSClientProvider.KMSKeyVersion("p1", "v1", new byte[0]));
KMSClientProvider p2 = mock(KMSClientProvider.class);
when(p2.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenReturn(
new KMSClientProvider.KMSKeyVersion("p2", "v2", new byte[0]));
KMSClientProvider p3 = mock(KMSClientProvider.class);
when(p3.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenReturn(
new KMSClientProvider.KMSKeyVersion("p3", "v3", new byte[0]));
KeyProvider kp = new LoadBalancingKMSClientProvider(
new KMSClientProvider[] { p1, p2, p3 }, 0, conf);
assertEquals("p1", kp.createKey("test1", new Options(conf)).getName());
assertEquals("p2", kp.createKey("test2", new Options(conf)).getName());
assertEquals("p3", kp.createKey("test3", new Options(conf)).getName());
assertEquals("p1", kp.createKey("test4", new Options(conf)).getName());
}
@Test
public void testLoadBalancingWithFailure() throws Exception {
Configuration conf = new Configuration();
KMSClientProvider p1 = mock(KMSClientProvider.class);
when(p1.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenReturn(
new KMSClientProvider.KMSKeyVersion("p1", "v1", new byte[0]));
when(p1.getKMSUrl()).thenReturn("p1");
// This should not be retried
KMSClientProvider p2 = mock(KMSClientProvider.class);
when(p2.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenThrow(new NoSuchAlgorithmException("p2"));
when(p2.getKMSUrl()).thenReturn("p2");
KMSClientProvider p3 = mock(KMSClientProvider.class);
when(p3.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenReturn(
new KMSClientProvider.KMSKeyVersion("p3", "v3", new byte[0]));
when(p3.getKMSUrl()).thenReturn("p3");
// This should be retried
KMSClientProvider p4 = mock(KMSClientProvider.class);
when(p4.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenThrow(new IOException("p4"));
when(p4.getKMSUrl()).thenReturn("p4");
KeyProvider kp = new LoadBalancingKMSClientProvider(
new KMSClientProvider[] { p1, p2, p3, p4 }, 0, conf);
assertEquals("p1", kp.createKey("test4", new Options(conf)).getName());
// Exceptions other than IOExceptions will not be retried
try {
kp.createKey("test1", new Options(conf)).getName();
fail("Should fail since its not an IOException");
} catch (Exception e) {
assertTrue(e instanceof NoSuchAlgorithmException);
}
assertEquals("p3", kp.createKey("test2", new Options(conf)).getName());
// IOException will trigger retry in next provider
assertEquals("p1", kp.createKey("test3", new Options(conf)).getName());
}
@Test
public void testLoadBalancingWithAllBadNodes() throws Exception {
Configuration conf = new Configuration();
KMSClientProvider p1 = mock(KMSClientProvider.class);
when(p1.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenThrow(new IOException("p1"));
KMSClientProvider p2 = mock(KMSClientProvider.class);
when(p2.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenThrow(new IOException("p2"));
KMSClientProvider p3 = mock(KMSClientProvider.class);
when(p3.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenThrow(new IOException("p3"));
KMSClientProvider p4 = mock(KMSClientProvider.class);
when(p4.createKey(Mockito.anyString(), Mockito.any(Options.class)))
.thenThrow(new IOException("p4"));
when(p1.getKMSUrl()).thenReturn("p1");
when(p2.getKMSUrl()).thenReturn("p2");
when(p3.getKMSUrl()).thenReturn("p3");
when(p4.getKMSUrl()).thenReturn("p4");
KeyProvider kp = new LoadBalancingKMSClientProvider(
new KMSClientProvider[] { p1, p2, p3, p4 }, 0, conf);
try {
kp.createKey("test3", new Options(conf)).getName();
fail("Should fail since all providers threw an IOException");
} catch (Exception e) {
assertTrue(e instanceof IOException);
}
}
// copied from HttpExceptionUtils:
// trick, riding on generics to throw an undeclared exception
private static void throwEx(Throwable ex) {
TestLoadBalancingKMSClientProvider.<RuntimeException>throwException(ex);
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void throwException(Throwable ex)
throws E {
throw (E) ex;
}
private | TestLoadBalancingKMSClientProvider |
java | elastic__elasticsearch | x-pack/plugin/rollup/src/main/java/org/elasticsearch/xpack/rollup/rest/RestDeleteRollupJobAction.java | {
"start": 767,
"end": 1692
} | class ____ extends BaseRestHandler {
public static final ParseField ID = new ParseField("id");
@Override
public List<Route> routes() {
return List.of(new Route(DELETE, "/_rollup/job/{id}"));
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) {
String id = restRequest.param(ID.getPreferredName());
DeleteRollupJobAction.Request request = new DeleteRollupJobAction.Request(id);
return channel -> client.execute(DeleteRollupJobAction.INSTANCE, request, new RestToXContentListener<>(channel, r -> {
if (r.getNodeFailures().size() > 0 || r.getTaskFailures().size() > 0) {
return RestStatus.INTERNAL_SERVER_ERROR;
}
return RestStatus.OK;
}));
}
@Override
public String getName() {
return "delete_rollup_job";
}
}
| RestDeleteRollupJobAction |
java | apache__camel | components/camel-docker/src/test/java/org/apache/camel/component/docker/headers/StartContainerCmdHeaderTest.java | {
"start": 1331,
"end": 2160
} | class ____ extends BaseDockerHeaderTest<StartContainerCmd> {
@Mock
ExposedPort exposedPort;
@Mock
private StartContainerCmd mockObject;
@Test
void startContainerHeaderTest() {
String containerId = "be29975e0098";
Map<String, Object> headers = getDefaultParameters();
headers.put(DockerConstants.DOCKER_CONTAINER_ID, containerId);
template.sendBodyAndHeaders("direct:in", "", headers);
Mockito.verify(dockerClient, Mockito.times(1)).startContainerCmd(containerId);
}
@Override
protected void setupMocks() {
Mockito.when(dockerClient.startContainerCmd(anyString())).thenReturn(mockObject);
}
@Override
protected DockerOperation getOperation() {
return DockerOperation.START_CONTAINER;
}
}
| StartContainerCmdHeaderTest |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/json/SerializedThrowableSerializer.java | {
"start": 1320,
"end": 2328
} | class ____ extends StdSerializer<SerializedThrowable> {
private static final long serialVersionUID = 1L;
static final String FIELD_NAME_CLASS = "class";
static final String FIELD_NAME_STACK_TRACE = "stack-trace";
public static final String FIELD_NAME_SERIALIZED_THROWABLE = "serialized-throwable";
public SerializedThrowableSerializer() {
super(SerializedThrowable.class);
}
@Override
public void serialize(
final SerializedThrowable value,
final JsonGenerator gen,
final SerializerProvider provider)
throws IOException {
gen.writeStartObject();
gen.writeStringField(FIELD_NAME_CLASS, value.getOriginalErrorClassName());
gen.writeStringField(FIELD_NAME_STACK_TRACE, value.getFullStringifiedStackTrace());
gen.writeBinaryField(
FIELD_NAME_SERIALIZED_THROWABLE, InstantiationUtil.serializeObject(value));
gen.writeEndObject();
}
}
| SerializedThrowableSerializer |
java | apache__logging-log4j2 | log4j-jpa/src/main/java/org/apache/logging/log4j/core/appender/db/jpa/package-info.java | {
"start": 1086,
"end": 1448
} | class ____; these Maven dependencies are optional and will not automatically
* be added to your classpath.
*/
@Export
@Open("org.apache.logging.log4j.core")
@Version("2.20.1")
package org.apache.logging.log4j.core.appender.db.jpa;
import aQute.bnd.annotation.jpms.Open;
import org.osgi.annotation.bundle.Export;
import org.osgi.annotation.versioning.Version;
| path |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java | {
"start": 3723,
"end": 4011
} | class ____ extends SimpleApplicationEventMulticaster {
private static int counter = 0;
@Override
public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
super.multicastEvent(event, eventType);
counter++;
}
}
}
| TestApplicationEventMulticaster |
java | apache__kafka | metadata/src/main/java/org/apache/kafka/controller/KRaftVersionAccessor.java | {
"start": 952,
"end": 1457
} | interface ____ {
/**
* Returns the latest kraft version.
*
* The latest version may be uncommitted.
*/
KRaftVersion kraftVersion();
/**
* Upgrade the kraft version.
*
* @param epoch the current epoch
* @param newVersion the new kraft version to upgrade to
* @param validateOnly whether to just validate the change and not persist it
*/
void upgradeKRaftVersion(int epoch, KRaftVersion newVersion, boolean validateOnly);
}
| KRaftVersionAccessor |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java | {
"start": 14309,
"end": 14589
} | class ____ extends AbstractTestExecutionListener {
@Override
public int getOrder() {
// 2250 is between DependencyInjectionTestExecutionListener (2000) and
// MicrometerObservationRegistryTestExecutionListener (2500)
return 2250;
}
}
static | BarTestExecutionListener |
java | apache__maven | compat/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionResult.java | {
"start": 1326,
"end": 9453
} | class ____ {
private Artifact originatingArtifact;
private List<Artifact> missingArtifacts;
// Exceptions
private List<Exception> exceptions;
private List<Exception> versionRangeViolations;
private List<ArtifactResolutionException> metadataResolutionExceptions;
private List<CyclicDependencyException> circularDependencyExceptions;
private List<ArtifactResolutionException> errorArtifactExceptions;
// file system errors
private List<ArtifactRepository> repositories;
private Set<Artifact> requestedArtifacts;
private Set<Artifact> artifacts;
private MetadataGraph resolvedTree;
public Artifact getOriginatingArtifact() {
return originatingArtifact;
}
public MetadataResolutionResult listOriginatingArtifact(final Artifact originatingArtifact) {
this.originatingArtifact = originatingArtifact;
return this;
}
public void addArtifact(Artifact artifact) {
if (artifacts == null) {
artifacts = new LinkedHashSet<>();
}
artifacts.add(artifact);
}
public Set<Artifact> getArtifacts() {
return artifacts;
}
public void addRequestedArtifact(Artifact artifact) {
if (requestedArtifacts == null) {
requestedArtifacts = new LinkedHashSet<>();
}
requestedArtifacts.add(artifact);
}
public Set<Artifact> getRequestedArtifacts() {
return requestedArtifacts;
}
public boolean hasMissingArtifacts() {
return missingArtifacts != null && !missingArtifacts.isEmpty();
}
public List<Artifact> getMissingArtifacts() {
return missingArtifacts == null ? Collections.emptyList() : Collections.unmodifiableList(missingArtifacts);
}
public MetadataResolutionResult addMissingArtifact(Artifact artifact) {
missingArtifacts = initList(missingArtifacts);
missingArtifacts.add(artifact);
return this;
}
public MetadataResolutionResult setUnresolvedArtifacts(final List<Artifact> unresolvedArtifacts) {
this.missingArtifacts = unresolvedArtifacts;
return this;
}
// ------------------------------------------------------------------------
// Exceptions
// ------------------------------------------------------------------------
public boolean hasExceptions() {
return exceptions != null && !exceptions.isEmpty();
}
public List<Exception> getExceptions() {
return exceptions == null ? Collections.emptyList() : Collections.unmodifiableList(exceptions);
}
// ------------------------------------------------------------------------
// Version Range Violations
// ------------------------------------------------------------------------
public boolean hasVersionRangeViolations() {
return versionRangeViolations != null;
}
/**
* TODO this needs to accept a {@link OverConstrainedVersionException} as returned by
* {@link #getVersionRangeViolation(int)} but it's not used like that in
* {@link org.apache.maven.repository.legacy.resolver.DefaultLegacyArtifactCollector}
*/
public MetadataResolutionResult addVersionRangeViolation(Exception e) {
versionRangeViolations = initList(versionRangeViolations);
versionRangeViolations.add(e);
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public OverConstrainedVersionException getVersionRangeViolation(int i) {
return (OverConstrainedVersionException) versionRangeViolations.get(i);
}
public List<Exception> getVersionRangeViolations() {
return versionRangeViolations == null
? Collections.emptyList()
: Collections.unmodifiableList(versionRangeViolations);
}
// ------------------------------------------------------------------------
// Metadata Resolution Exceptions: ArtifactResolutionExceptions
// ------------------------------------------------------------------------
public boolean hasMetadataResolutionExceptions() {
return metadataResolutionExceptions != null;
}
public MetadataResolutionResult addMetadataResolutionException(ArtifactResolutionException e) {
metadataResolutionExceptions = initList(metadataResolutionExceptions);
metadataResolutionExceptions.add(e);
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public ArtifactResolutionException getMetadataResolutionException(int i) {
return metadataResolutionExceptions.get(i);
}
public List<ArtifactResolutionException> getMetadataResolutionExceptions() {
return metadataResolutionExceptions == null
? Collections.emptyList()
: Collections.unmodifiableList(metadataResolutionExceptions);
}
// ------------------------------------------------------------------------
// ErrorArtifactExceptions: ArtifactResolutionExceptions
// ------------------------------------------------------------------------
public boolean hasErrorArtifactExceptions() {
return errorArtifactExceptions != null;
}
public MetadataResolutionResult addError(Exception e) {
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public List<ArtifactResolutionException> getErrorArtifactExceptions() {
if (errorArtifactExceptions == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(errorArtifactExceptions);
}
// ------------------------------------------------------------------------
// Circular Dependency Exceptions
// ------------------------------------------------------------------------
public boolean hasCircularDependencyExceptions() {
return circularDependencyExceptions != null;
}
public MetadataResolutionResult addCircularDependencyException(CyclicDependencyException e) {
circularDependencyExceptions = initList(circularDependencyExceptions);
circularDependencyExceptions.add(e);
exceptions = initList(exceptions);
exceptions.add(e);
return this;
}
public CyclicDependencyException getCircularDependencyException(int i) {
return circularDependencyExceptions.get(i);
}
public List<CyclicDependencyException> getCircularDependencyExceptions() {
if (circularDependencyExceptions == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(circularDependencyExceptions);
}
// ------------------------------------------------------------------------
// Repositories
// ------------------------------------------------------------------------
public List<ArtifactRepository> getRepositories() {
if (repositories == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(repositories);
}
public MetadataResolutionResult setRepositories(final List<ArtifactRepository> repositories) {
this.repositories = repositories;
return this;
}
//
// Internal
//
private <T> List<T> initList(final List<T> l) {
if (l == null) {
return new ArrayList<>();
}
return l;
}
@Override
public String toString() {
if (artifacts == null) {
return "";
}
StringBuilder sb = new StringBuilder(256);
int i = 1;
sb.append("---------\n");
sb.append(artifacts.size()).append('\n');
for (Artifact a : artifacts) {
sb.append(i).append(' ').append(a).append('\n');
i++;
}
sb.append("---------\n");
return sb.toString();
}
public MetadataGraph getResolvedTree() {
return resolvedTree;
}
public void setResolvedTree(MetadataGraph resolvedTree) {
this.resolvedTree = resolvedTree;
}
}
| MetadataResolutionResult |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/builder/SpringApplicationBuilder.java | {
"start": 19250,
"end": 21424
} | class ____ is
* needed, this is where it would be added.
* @param resourceLoader the resource loader to set.
* @return the current builder
*/
public SpringApplicationBuilder resourceLoader(ResourceLoader resourceLoader) {
this.application.setResourceLoader(resourceLoader);
return this;
}
/**
* Add some initializers to the application (applied to the {@link ApplicationContext}
* before any bean definitions are loaded).
* @param initializers some initializers to add
* @return the current builder
*/
public SpringApplicationBuilder initializers(ApplicationContextInitializer<?>... initializers) {
this.application.addInitializers(initializers);
return this;
}
/**
* Add some listeners to the application (listening for SpringApplication events as
* well as regular Spring events once the context is running). Any listeners that are
* also {@link ApplicationContextInitializer} will be added to the
* {@link #initializers(ApplicationContextInitializer...) initializers} automatically.
* @param listeners some listeners to add
* @return the current builder
*/
public SpringApplicationBuilder listeners(ApplicationListener<?>... listeners) {
this.application.addListeners(listeners);
return this;
}
/**
* Configure the {@link ApplicationStartup} to be used with the
* {@link ApplicationContext} for collecting startup metrics.
* @param applicationStartup the application startup to use
* @return the current builder
* @since 2.4.0
*/
public SpringApplicationBuilder applicationStartup(ApplicationStartup applicationStartup) {
this.application.setApplicationStartup(applicationStartup);
return this;
}
/**
* Whether to allow circular references between beans and automatically try to resolve
* them.
* @param allowCircularReferences whether circular references are allowed
* @return the current builder
* @since 2.6.0
* @see AbstractAutowireCapableBeanFactory#setAllowCircularReferences(boolean)
*/
public SpringApplicationBuilder allowCircularReferences(boolean allowCircularReferences) {
this.application.setAllowCircularReferences(allowCircularReferences);
return this;
}
}
| loader |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/jdk8/DurationTest.java | {
"start": 873,
"end": 1083
} | class ____ {
private Duration date;
public Duration getDate() {
return date;
}
public void setDate(Duration date) {
this.date = date;
}
}
}
| VO |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/bytes/BytesReference.java | {
"start": 1095,
"end": 7109
} | interface ____ extends Comparable<BytesReference>, ToXContentFragment {
/**
* Convert an {@link XContentBuilder} into a BytesReference. This method closes the builder,
* so no further fields may be added.
*/
static BytesReference bytes(XContentBuilder xContentBuilder) {
xContentBuilder.close();
OutputStream stream = xContentBuilder.getOutputStream();
if (stream instanceof ByteArrayOutputStream) {
return new BytesArray(((ByteArrayOutputStream) stream).toByteArray());
} else {
return ((BytesStream) stream).bytes();
}
}
/**
* Returns a compact array from the given BytesReference. The returned array won't be copied unless necessary. If you need
* to modify the returned array use {@code BytesRef.deepCopyOf(reference.toBytesRef()} instead
*/
static byte[] toBytes(BytesReference reference) {
final BytesRef bytesRef = reference.toBytesRef();
if (bytesRef.offset == 0 && bytesRef.length == bytesRef.bytes.length) {
return bytesRef.bytes;
}
return ArrayUtil.copyOfSubArray(bytesRef.bytes, bytesRef.offset, bytesRef.offset + bytesRef.length);
}
/**
* Returns an array of byte buffers from the given BytesReference.
*/
static ByteBuffer[] toByteBuffers(BytesReference reference) {
BytesRefIterator byteRefIterator = reference.iterator();
BytesRef r;
try {
ArrayList<ByteBuffer> buffers = new ArrayList<>();
while ((r = byteRefIterator.next()) != null) {
buffers.add(ByteBuffer.wrap(r.bytes, r.offset, r.length));
}
return buffers.toArray(ByteBuffer[]::new);
} catch (IOException e) {
// this is really an error since we don't do IO in our bytesreferences
throw new AssertionError("won't happen", e);
}
}
/**
* Returns BytesReference composed of the provided ByteBuffers.
*/
static BytesReference fromByteBuffers(ByteBuffer[] buffers) {
int bufferCount = buffers.length;
if (bufferCount == 0) {
return BytesArray.EMPTY;
} else if (bufferCount == 1) {
return fromByteBuffer(buffers[0]);
} else {
BytesReference[] references = new BytesReference[bufferCount];
for (int i = 0; i < bufferCount; ++i) {
references[i] = fromByteBuffer(buffers[i]);
}
return CompositeBytesReference.of(references);
}
}
/**
* Returns BytesReference composed of the provided ByteBuffer.
*/
static BytesReference fromByteBuffer(ByteBuffer buffer) {
assert buffer.hasArray();
return new BytesArray(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
}
/**
* Returns BytesReference either wrapping the provided {@link ByteArray} or in case the has a backing raw byte array one that wraps
* that backing array directly.
*/
static BytesReference fromByteArray(ByteArray byteArray, int length) {
if (length == 0) {
return BytesArray.EMPTY;
}
if (byteArray.hasArray()) {
return new BytesArray(byteArray.array(), 0, length);
}
return new PagedBytesReference(byteArray, 0, length);
}
/**
* Returns the byte at the specified index. Need to be between 0 and length.
*/
byte get(int index);
/**
* Returns the integer read from the 4 bytes (BE) starting at the given index.
*/
int getInt(int index);
/**
* Returns the integer read from the 4 bytes (LE) starting at the given index.
*/
int getIntLE(int index);
/**
* Returns the long read from the 8 bytes (LE) starting at the given index.
*/
long getLongLE(int index);
/**
* Returns the double read from the 8 bytes (LE) starting at the given index.
*/
double getDoubleLE(int index);
/**
* Finds the index of the first occurrence of the given marker between within the given bounds.
* @param marker marker byte to search
* @param from lower bound for the index to check (inclusive)
* @return first index of the marker or {@code -1} if not found
*/
int indexOf(byte marker, int from);
/**
* The length.
*/
int length();
/**
* Slice the bytes from the {@code from} index up to {@code length}.
*/
BytesReference slice(int from, int length);
/**
* The amount of memory used by this BytesReference.
* <p>
* Note that this is not always the same as length and can vary by implementation.
* </p>
*/
long ramBytesUsed();
/**
* A stream input of the bytes.
*/
StreamInput streamInput() throws IOException;
/**
* Writes the bytes directly to the output stream.
*/
void writeTo(OutputStream os) throws IOException;
/**
* Interprets the referenced bytes as UTF8 bytes, returning the resulting string
*/
String utf8ToString();
/**
* Converts to Lucene BytesRef.
*/
BytesRef toBytesRef();
/**
* Returns a BytesRefIterator for this BytesReference. This method allows
* access to the internal pages of this reference without copying them.
* It must return direct references to the pages, not copies. Use with care!
*
* @see BytesRefIterator
*/
BytesRefIterator iterator();
/**
* @return {@code true} if this instance is backed by a byte array
*/
default boolean hasArray() {
return false;
}
/**
* @return backing byte array for this instance
*/
default byte[] array() {
throw new UnsupportedOperationException();
}
/**
* @return offset of the first byte of this instance in the backing byte array
*/
default int arrayOffset() {
throw new UnsupportedOperationException();
}
}
| BytesReference |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/collectioninitializer/CostCenter.java | {
"start": 287,
"end": 728
} | class ____ {
@Id
private Long id;
@ManyToOne(optional = false)
private Company company;
@Override
public String toString() {
return "CostCenter{" +
"id=" + id +
", company=" + company +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
| CostCenter |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/publisher/MonoIgnoreEmptyTest.java | {
"start": 921,
"end": 1707
} | class ____ {
@Test
public void normal() {
StepVerifier.create(Flux.just(1)
.thenEmpty(Flux.empty()))
.verifyComplete();
}
@Test
public void normal3() {
StepVerifier.create(Flux.just(1)
.then())
.verifyComplete();
}
@Test
public void scanSubscriber() {
CoreSubscriber<String> actual = new LambdaMonoSubscriber<>(null, e -> {}, null, null);
MonoIgnoreElements.IgnoreElementsSubscriber<String> test = new
MonoIgnoreElements.IgnoreElementsSubscriber<>(actual);
Subscription sub = Operators.emptySubscription();
test.onSubscribe(sub);
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(sub);
assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
}
}
| MonoIgnoreEmptyTest |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/java/typeutils/PojoTypeExtractionTest.java | {
"start": 36478,
"end": 37127
} | class ____ extends Container<Container<Object>> {}
@Test
void testRecursivePojoWithTypeVariable() {
TypeInformation<?> ti = TypeExtractor.createTypeInfo(MyType.class);
assertThat(ti).isInstanceOf(PojoTypeInfo.class);
TypeInformation<?> pti = ((PojoTypeInfo) ti).getPojoFieldAt(0).getTypeInformation();
assertThat(pti).isInstanceOf(PojoTypeInfo.class);
assertThat(((PojoTypeInfo) pti).getPojoFieldAt(0).getTypeInformation().getClass())
.isEqualTo(GenericTypeInfo.class);
}
/** POJO generated using Lombok. */
@Getter
@Setter
@NoArgsConstructor
public static | MyType |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/output/ScoredValueListOutputUnitTests.java | {
"start": 353,
"end": 1098
} | class ____ {
private ScoredValueListOutput<String, String> sut = new ScoredValueListOutput<>(StringCodec.UTF8);
@Test
void defaultSubscriberIsSet() {
sut.multi(1);
assertThat(sut.getSubscriber()).isNotNull().isInstanceOf(ListSubscriber.class);
}
@Test
void setIntegerShouldFail() {
assertThatThrownBy(() -> sut.set(123L)).isInstanceOf(UnsupportedOperationException.class);
}
@Test
void commandOutputCorrectlyDecoded() {
sut.multi(1);
sut.set(ByteBuffer.wrap("key".getBytes()));
sut.set(ByteBuffer.wrap("4.567".getBytes()));
sut.multi(-1);
assertThat(sut.get()).contains(ScoredValue.just(4.567, "key"));
}
}
| ScoredValueListOutputUnitTests |
java | elastic__elasticsearch | x-pack/plugin/otel-data/src/test/java/org/elasticsearch/xpack/oteldata/otlp/datapoint/ExponentialHistogramConverterAccuracyTests.java | {
"start": 1662,
"end": 8301
} | class ____ extends ExponentialHistogramTestCase {
public static final double[] QUANTILES_TO_TEST = { 0, 0.0000001, 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.999999, 1.0 };
private static final TDigestArrays arrays = new MemoryTrackingTDigestArrays(new NoopCircuitBreaker("default-wrapper-tdigest-arrays"));
public static final int TDIGEST_COMPRESSION = 100;
public void testUniformDistribution() {
testDistributionQuantileAccuracy(new UniformRealDistribution(new Well19937c(randomInt()), 0, 100));
}
public void testNormalDistribution() {
testDistributionQuantileAccuracy(new NormalDistribution(new Well19937c(randomInt()), 100, 15));
}
public void testExponentialDistribution() {
testDistributionQuantileAccuracy(new ExponentialDistribution(new Well19937c(randomInt()), 10));
}
public void testLogNormalDistribution() {
testDistributionQuantileAccuracy(new LogNormalDistribution(new Well19937c(randomInt()), 0, 1));
}
public void testGammaDistribution() {
testDistributionQuantileAccuracy(new GammaDistribution(new Well19937c(randomInt()), 2, 5));
}
public void testBetaDistribution() {
testDistributionQuantileAccuracy(new BetaDistribution(new Well19937c(randomInt()), 2, 5));
}
public void testWeibullDistribution() {
testDistributionQuantileAccuracy(new WeibullDistribution(new Well19937c(randomInt()), 2, 5));
}
private void testDistributionQuantileAccuracy(RealDistribution distribution) {
double[] samples = QuantileAccuracyTests.generateSamples(distribution, between(3_000, 10_000));
int numBuckets = randomIntBetween(50, 100);
ExponentialHistogram exponentialHistogram = createAutoReleasedHistogram(numBuckets, samples);
ExponentialHistogramDataPoint otlpHistogram = convertToOtlpHistogram(exponentialHistogram);
double rawTDigestMaxError;
try (TDigest rawTDigest = TDigest.createAvlTreeDigest(arrays, TDIGEST_COMPRESSION)) {
for (double sample : samples) {
rawTDigest.add(sample);
}
rawTDigestMaxError = getMaxRelativeError(samples, rawTDigest::quantile);
}
double convertedTDigestMaxError;
try (TDigest convertedTDigest = convertToTDigest(otlpHistogram)) {
convertedTDigestMaxError = getMaxRelativeError(samples, convertedTDigest::quantile);
}
double exponentialHistogramMaxError = QuantileAccuracyTests.getMaximumRelativeError(samples, numBuckets);
double combinedRelativeError = rawTDigestMaxError + exponentialHistogramMaxError;
// It's hard to reason about the upper bound of the combined error for this conversion,
// so we just check that it's not worse than twice the sum of the individual errors.
// For a lower number of buckets or samples than the ones we're testing with here,
// the error can be even higher than this.
// The same is true when using a different TDigest implementation that's less accurate (such as hybrid or merging).
assertThat(convertedTDigestMaxError, lessThanOrEqualTo(combinedRelativeError * 2));
}
private static TDigest convertToTDigest(ExponentialHistogramDataPoint otlpHistogram) {
TDigest result = TDigest.createAvlTreeDigest(arrays, 100);
List<Double> centroidValues = new ArrayList<>();
HistogramConverter.centroidValues(otlpHistogram, centroidValues::add);
List<Long> counts = new ArrayList<>();
HistogramConverter.counts(otlpHistogram, counts::add);
assertEquals(centroidValues.size(), counts.size());
for (int i = 0; i < centroidValues.size(); i++) {
if (counts.get(i) > 0) {
result.add(centroidValues.get(i), counts.get(i));
}
}
return result;
}
private ExponentialHistogramDataPoint convertToOtlpHistogram(ExponentialHistogram histogram) {
ExponentialHistogramDataPoint.Builder builder = ExponentialHistogramDataPoint.newBuilder();
builder.setScale(histogram.scale());
builder.setZeroCount(histogram.zeroBucket().count());
builder.setZeroThreshold(histogram.zeroBucket().zeroThreshold());
builder.setPositive(convertBuckets(histogram.positiveBuckets()));
builder.setNegative(convertBuckets(histogram.negativeBuckets()));
return builder.build();
}
private static ExponentialHistogramDataPoint.Buckets.Builder convertBuckets(ExponentialHistogram.Buckets buckets) {
ExponentialHistogramDataPoint.Buckets.Builder result = ExponentialHistogramDataPoint.Buckets.newBuilder();
BucketIterator it = buckets.iterator();
if (it.hasNext() == false) {
return result;
}
result.setOffset((int) it.peekIndex());
for (long index = it.peekIndex(); it.hasNext(); index++) {
int missingBuckets = (int) (it.peekIndex() - index);
for (int i = 0; i < missingBuckets; i++) {
result.addBucketCounts(0);
index++;
}
result.addBucketCounts(it.peekCount());
it.advance();
}
return result;
}
private double getMaxRelativeError(double[] values, DoubleFunction<Double> quantileFunction) {
Arrays.sort(values);
double maxError = 0;
// Compare histogram quantiles with exact quantiles
for (double q : QUANTILES_TO_TEST) {
double percentileRank = q * (values.length - 1);
int lowerRank = (int) Math.floor(percentileRank);
int upperRank = (int) Math.ceil(percentileRank);
double upperFactor = percentileRank - lowerRank;
if (values[lowerRank] < 0 && values[upperRank] > 0) {
// the percentile lies directly between a sign change and we interpolate linearly in-between
// in this case the relative error bound does not hold
continue;
}
double exactValue = values[lowerRank] * (1 - upperFactor) + values[upperRank] * upperFactor;
double histoValue = quantileFunction.apply(q);
// Skip comparison if exact value is close to zero to avoid false-positives due to numerical imprecision
if (Math.abs(exactValue) < 1e-100) {
continue;
}
double relativeError = Math.abs(histoValue - exactValue) / Math.abs(exactValue);
maxError = Math.max(maxError, relativeError);
}
return maxError;
}
}
| ExponentialHistogramConverterAccuracyTests |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java | {
"start": 63333,
"end": 63411
} | class ____ {
@Configuration
@Order(1)
static | ConfigWithOrderedNestedClasses |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/CaseStatementWithTypeTest.java | {
"start": 1587,
"end": 4517
} | class ____ {
@BeforeEach
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
session.persist( new SingleChildA( 1L ) );
session.persist( new SingleChildB( 2L ) );
session.persist( new JoinedChildA( 1L ) );
session.persist( new JoinedChildB( 2L ) );
session.persist( new JoinedDiscChildA( 1L ) );
session.persist( new JoinedDiscChildB( 2L ) );
session.persist( new UnionChildA( 1L ) );
session.persist( new UnionChildB( 2L ) );
} );
}
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.dropData();
}
@Test
public void testSingleTableInheritance(SessionFactoryScope scope) {
executeQuery( scope, SingleParent.class, SingleChildA.class, SingleChildB.class, false );
executeQuery( scope, SingleParent.class, SingleChildA.class, SingleChildB.class, true );
}
@Test
public void testJoinedInheritance(SessionFactoryScope scope) {
executeQuery( scope, JoinedParent.class, JoinedChildA.class, JoinedChildB.class, false );
executeQuery( scope, JoinedParent.class, JoinedChildA.class, JoinedChildB.class, true );
}
@Test
public void testJoinedInheritanceAndDiscriminator(SessionFactoryScope scope) {
executeQuery( scope, JoinedDiscParent.class, JoinedDiscChildA.class, JoinedDiscChildB.class, false );
executeQuery( scope, JoinedDiscParent.class, JoinedDiscChildA.class, JoinedDiscChildB.class, true );
}
@Test
public void testTablePerClassInheritance(SessionFactoryScope scope) {
executeQuery( scope, UnionParent.class, UnionChildA.class, UnionChildB.class, false );
executeQuery( scope, UnionParent.class, UnionChildA.class, UnionChildB.class, true );
}
private <T> void executeQuery(
SessionFactoryScope scope,
Class<T> parent,
Class<? extends T> childA,
Class<? extends T> childB,
boolean orderBy) {
scope.inTransaction( session -> {
final StringBuilder sb = new StringBuilder( "select p.id" );
final String caseExpression = String.format(
"case type(p) when %s then 'A' when %s then 'B' else null end",
childA.getSimpleName(),
childB.getSimpleName()
);
if ( orderBy ) {
sb.append( String.format( " from %s p order by %s", parent.getSimpleName(), caseExpression ) );
}
else {
sb.append( String.format( ", %s from %s p", caseExpression, parent.getSimpleName() ) );
}
//noinspection removal
final List<Tuple> resultList = session.createQuery( sb.toString(), Tuple.class ).getResultList();
assertThat( resultList ).hasSize( 2 );
if ( orderBy ) {
assertThat( resultList.stream().map( t -> t.get( 0, Long.class ) ) ).containsExactly( 1L, 2L );
}
else {
assertThat( resultList.stream().map( t -> t.get( 1, String.class ) ) ).contains( "A", "B" );
}
} );
}
@SuppressWarnings({"FieldCanBeLocal", "unused"})
@Entity( name = "SingleParent" )
@Inheritance( strategy = InheritanceType.SINGLE_TABLE )
public static | CaseStatementWithTypeTest |
java | micronaut-projects__micronaut-core | core/src/main/java/io/micronaut/core/beans/DefaultBeanIntrospector.java | {
"start": 1241,
"end": 1401
} | interface ____ uses service loader to discovery introspections.
*
* @author graemerocher
* @since 1.1
* @see BeanIntrospector
* @see BeanIntrospection
*/
| that |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TrafficController.java | {
"start": 14922,
"end": 15183
} | class ____
if (currentClassId != -1) {
int bytes = Integer.parseInt(bytesMatcher.group(1));
containerClassIdStats.put(currentClassId, bytes);
} else {
LOG.warn("Matched a 'bytes sent' line outside of a | segment |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/ExpressionsTest.java | {
"start": 2161,
"end": 19007
} | class ____ {
private CriteriaBuilder builder;
@BeforeEach
public void prepareTestData(EntityManagerFactoryScope scope) {
builder = scope.getEntityManagerFactory().getCriteriaBuilder();
scope.inTransaction( entityManager -> {
Product product = new Product();
product.setId( "product1" );
product.setPrice( 1.23d );
product.setQuantity( 2 );
product.setPartNumber( ( (long) Integer.MAX_VALUE ) + 1 );
product.setRating( 1.999f );
product.setSomeBigInteger( BigInteger.valueOf( 987654321 ) );
product.setSomeBigDecimal( BigDecimal.valueOf( 987654.32 ) );
entityManager.persist( product );
}
);
}
@AfterEach
public void cleanupTestData(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
}
@Test
public void testEmptyConjunction(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
criteria.from( Product.class );
criteria.where( builder.and() );
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 1, result.size() );
}
);
}
@Test
@JiraKey( value = "HHH-15452")
public void testGetConjunctionExpressionsAndAddPredicate(EntityManagerFactoryScope scope){
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery(Product.class);
Root<Product> root = criteria.from(Product.class);
Predicate conjunction = builder.conjunction();
Predicate expr = builder.equal(root.get("id"), "NON existing id");
// Modifications to the list do not affect the query
List<Expression<Boolean>> expressions = conjunction.getExpressions();
expressions.add( expr);
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 1, result.size() );
}
);
}
@Test
@JiraKey(value = "HHH-6876")
public void testEmptyInList(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
Root<Product> from = criteria.from( Product.class );
criteria.where( from.get( Product_.partNumber ).in() ); // empty IN list
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 0, result.size() );
}
);
}
@Test
public void testEmptyConjunctionIsTrue(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
criteria.from( Product.class );
criteria.where( builder.isTrue( builder.and() ) );
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 1, result.size() );
}
);
}
@Test
public void testEmptyConjunctionIsFalse(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
criteria.from( Product.class );
criteria.where( builder.isFalse( builder.and() ) );
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 0, result.size() );
}
);
}
@Test
public void testEmptyDisjunction(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
criteria.from( Product.class );
criteria.where( builder.disjunction() );
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 0, result.size() );
}
);
}
@Test
public void testEmptyDisjunctionIsTrue(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
criteria.from( Product.class );
criteria.where( builder.isTrue( builder.disjunction() ) );
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 0, result.size() );
}
);
}
@Test
public void testEmptyDisjunctionIsFalse(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
criteria.from( Product.class );
criteria.where( builder.isFalse( builder.disjunction() ) );
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 1, result.size() );
}
);
}
@Test
public void testDiff(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Integer> criteria = builder.createQuery( Integer.class );
criteria.from( Product.class );
criteria.select( builder.diff( builder.literal( 5 ), builder.literal( 2 ) ) );
Integer result = entityManager.createQuery( criteria ).getSingleResult();
assertEquals( Integer.valueOf( 3 ), result );
}
);
}
@Test
public void testDiffWithQuotient(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Number> criteria = builder.createQuery( Number.class );
criteria.from( Product.class );
criteria.select(
builder.quot(
builder.diff(
builder.literal( BigDecimal.valueOf( 2.0 ) ),
builder.literal( BigDecimal.valueOf( 1.0 ) )
),
BigDecimal.valueOf( 2.0 )
)
);
Number result = entityManager.createQuery( criteria ).getSingleResult();
assertEquals( 0.5d, result.doubleValue(), 0.1d );
}
);
}
@Test
public void testSumWithQuotient(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Number> criteria = builder.createQuery( Number.class );
criteria.from( Product.class );
criteria.select(
builder.quot(
builder.sum(
builder.literal( BigDecimal.valueOf( 0.0 ) ),
builder.literal( BigDecimal.valueOf( 1.0 ) )
),
BigDecimal.valueOf( 2.0 )
)
);
Number result = entityManager.createQuery( criteria ).getSingleResult();
assertEquals( 0.5d, result.doubleValue(), 0.1d );
}
);
}
@Test
@Jira( "https://hibernate.atlassian.net/browse/HHH-17223" )
public void testSumWithCoalesce(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final CriteriaQuery<Integer> criteria = builder.createQuery( Integer.class );
final Root<Product> root = criteria.from( Product.class );
criteria.select(
builder.sum(
builder.coalesce( root.get( "quantity" ), builder.literal( 5 ) )
)
).groupBy( root.get( "id" ) );
final Integer result = entityManager.createQuery( criteria ).getSingleResult();
assertEquals( 2, result );
}
);
}
@Test
@Jira( "https://hibernate.atlassian.net/browse/HHH-17260" )
public void testSumWithSubqueryPath(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
final HibernateCriteriaBuilder cb = entityManager.unwrap( Session.class ).getCriteriaBuilder();
final JpaCriteriaQuery<Integer> criteria = cb.createQuery( Integer.class );
final JpaSubQuery<Tuple> subquery = criteria.subquery( Tuple.class );
final Root<Product> product = subquery.from( Product.class );
subquery.multiselect(
product.get( "id" ).alias( "id" ),
product.get( "quantity" ).alias( "quantity" )
);
final JpaDerivedRoot<Tuple> root = criteria.from( subquery );
criteria.select( cb.sum( root.get( "quantity" ) ) );
final Integer result = entityManager.createQuery( criteria ).getSingleResult();
assertEquals( 2, result );
}
);
}
@Test
@SkipForDialect(dialectClass = PostgresPlusDialect.class, reason = "does not support extract(epoch)")
@SkipForDialect(dialectClass = AltibaseDialect.class, reason = "datediff overflow limits")
@SkipForDialect(dialectClass = GaussDBDialect.class, reason = "type:resolved.date multi overflows")
public void testDateTimeOperations(EntityManagerFactoryScope scope) {
HibernateCriteriaBuilder builder = (HibernateCriteriaBuilder) this.builder;
scope.inTransaction( entityManager -> {
CriteriaQuery<LocalDate> criteria = builder.createQuery(LocalDate.class);
criteria.select( builder.addDuration( builder.localDate(),
builder.duration(2, TemporalUnit.YEAR) ) );
entityManager.createQuery(criteria).getSingleResult();
}
);
scope.inTransaction( entityManager -> {
CriteriaQuery<LocalDate> criteria = builder.createQuery(LocalDate.class);
criteria.select( builder.addDuration(
// had to call literal() here because parameter-based binding caused error from
// database since it couldn't tell what sort of dateadd() function was being called
builder.literal( LocalDate.of(2000,1, 1) ),
builder.duration(2, TemporalUnit.YEAR) ) );
assertEquals( LocalDate.of(2002,1, 1),
entityManager.createQuery(criteria).getSingleResult() );
}
);
//SQL Server and others don't like this
// doInJPA(
// this::entityManagerFactory,
// entityManager -> {
// CriteriaQuery<LocalDate> criteria = builder.createQuery(LocalDate.class);
// criteria.select( builder.after( builder.localDate(), Duration.ofDays(2*365) ) );
// entityManager.createQuery(criteria).getSingleResult();
// }
// );
scope.inTransaction( entityManager -> {
CriteriaQuery<LocalDateTime> criteria = builder.createQuery(LocalDateTime.class);
criteria.select( builder.subtractDuration( builder.localDateTime(), Duration.ofMinutes(30) ) );
entityManager.createQuery(criteria).getSingleResult();
}
);
scope.inTransaction( entityManager -> {
CriteriaQuery<Duration> criteria = builder.createQuery(Duration.class);
criteria.select( builder.durationScaled( 5, builder.duration(2, TemporalUnit.HOUR ) ) );
assertEquals( Duration.ofHours(10), entityManager.createQuery(criteria).getSingleResult() );
}
);
scope.inTransaction( entityManager -> {
CriteriaQuery<Duration> criteria = builder.createQuery(Duration.class);
criteria.select( builder.durationSum( builder.duration(30, TemporalUnit.MINUTE ),
builder.duration(2, TemporalUnit.HOUR) ) );
assertEquals( Duration.ofMinutes(150), entityManager.createQuery(criteria).getSingleResult() );
}
);
scope.inTransaction( entityManager -> {
CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
criteria.select( builder.durationByUnit( TemporalUnit.SECOND,
builder.durationSum( builder.duration(30, TemporalUnit.MINUTE),
builder.duration(2, TemporalUnit.HOUR) ) ) );
assertEquals( 150*60L, entityManager.createQuery(criteria).getSingleResult() );
}
);
}
@Test
@SkipForDialect(dialectClass = SybaseDialect.class, matchSubTypes = true, reason = "numeric overflows")
@SkipForDialect(dialectClass = PostgresPlusDialect.class, reason = "does not support extract(epoch)")
void testDurationBetween(EntityManagerFactoryScope scope) {
HibernateCriteriaBuilder builder = (HibernateCriteriaBuilder) this.builder;
scope.inTransaction( entityManager -> {
CriteriaQuery<Duration> criteria = builder.createQuery(Duration.class);
criteria.select( builder.durationBetween( builder.localDate(),
LocalDate.of(2000,1, 1) ) );
entityManager.createQuery(criteria).getSingleResult();
}
);
scope.inTransaction( entityManager -> {
CriteriaQuery<Duration> criteria = builder.createQuery(Duration.class);
criteria.select( builder.durationBetween( builder.localDate(),
builder.subtractDuration( builder.localDate(),
builder.duration(2, TemporalUnit.DAY) ) ) );
assertEquals( Duration.ofDays(2), entityManager.createQuery(criteria).getSingleResult() );
}
);
scope.inTransaction( entityManager -> {
CriteriaQuery<Duration> criteria = builder.createQuery(Duration.class);
criteria.select( builder.durationBetween( builder.localDateTime(),
builder.subtractDuration( builder.localDateTime(),
builder.duration(20, TemporalUnit.HOUR) ) ) );
assertEquals( Duration.ofHours(20), entityManager.createQuery(criteria).getSingleResult() );
}
);
}
@Test
@SkipForDialect(dialectClass = DerbyDialect.class, reason = "By default, unless some kind of context enables inference," +
"a numeric/decimal parameter has the type DECIMAL(31,31) which might cause an overflow on certain arithmetics." +
"Fixing this would require a custom SqmToSqlAstConverter that creates a special JdbcParameter " +
"that is always rendered as literal. Since numeric literal + parameter arithmetic is rare, we skip this for now.")
@SkipForDialect(dialectClass = DB2Dialect.class, reason = "Same reason as for Derby")
public void testQuotientAndMultiply(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Number> criteria = builder.createQuery( Number.class );
criteria.from( Product.class );
criteria.select(
builder.quot(
builder.prod(
builder.literal( BigDecimal.valueOf( 10.0 ) ),
builder.literal( BigDecimal.valueOf( 5.0 ) )
),
BigDecimal.valueOf( 2.0 )
)
);
Number result = entityManager.createQuery( criteria ).getSingleResult();
assertEquals( 25.0d, result.doubleValue(), 0.1d );
criteria.select(
builder.prod(
builder.quot(
builder.literal( BigDecimal.valueOf( 10.0 ) ),
builder.literal( BigDecimal.valueOf( 5.0 ) )
),
BigDecimal.valueOf( 2.0 )
)
);
result = entityManager.createQuery( criteria ).getSingleResult();
assertEquals( 4.0d, result.doubleValue(), 0.1d );
}
);
}
@Test
public void testParameterReuse(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
Root<Product> from = criteria.from( Product.class );
ParameterExpression<String> param = builder.parameter( String.class );
Predicate predicate = builder.equal( from.get( Product_.id ), param );
Predicate predicate2 = builder.equal( from.get( Product_.name ), param );
criteria.where( builder.or( predicate, predicate2 ) );
assertEquals( 1, criteria.getParameters().size() );
TypedQuery<Product> query = entityManager.createQuery( criteria );
int hqlParamCount = countGeneratedParameters( query.unwrap( Query.class ) );
assertEquals( 1, hqlParamCount );
query.setParameter( param, "abc" ).getResultList();
}
);
}
private int countGeneratedParameters(Query<?> query) {
return query.getParameterMetadata().getParameterCount();
}
@Test
public void testInExplicitTupleList(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
Root<Product> from = criteria.from( Product.class );
criteria.where( from.get( Product_.partNumber )
.in( Collections.singletonList( ( (long) Integer.MAX_VALUE ) + 1 ) ) );
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 1, result.size() );
}
);
}
@Test
public void testInExplicitTupleListVarargs(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
Root<Product> from = criteria.from( Product.class );
criteria.where( from.get( Product_.partNumber ).in( ( (long) Integer.MAX_VALUE ) + 1 ) );
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 1, result.size() );
}
);
}
@Test
public void testInExpressionVarargs(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
Root<Product> from = criteria.from( Product.class );
criteria.where( from.get( Product_.partNumber ).in( from.get( Product_.partNumber ) ) );
List<Product> result = entityManager.createQuery( criteria ).getResultList();
assertEquals( 1, result.size() );
}
);
}
@Test
public void testJoinedElementCollectionValuesInTupleList(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
CriteriaQuery<Phone> criteria = builder.createQuery( Phone.class );
Root<Phone> from = criteria.from( Phone.class );
criteria.where(
from.join( "types" )
.in( Collections.singletonList( Phone.Type.WORK ) )
);
entityManager.createQuery( criteria ).getResultList();
}
);
}
}
| ExpressionsTest |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/load/resource/gif/GifDrawableEncoder.java | {
"start": 533,
"end": 1242
} | class ____ implements ResourceEncoder<GifDrawable> {
private static final String TAG = "GifEncoder";
@NonNull
@Override
public EncodeStrategy getEncodeStrategy(@NonNull Options options) {
return EncodeStrategy.SOURCE;
}
@Override
public boolean encode(
@NonNull Resource<GifDrawable> data, @NonNull File file, @NonNull Options options) {
GifDrawable drawable = data.get();
boolean success = false;
try {
ByteBufferUtil.toFile(drawable.getBuffer(), file);
success = true;
} catch (IOException e) {
if (Log.isLoggable(TAG, Log.WARN)) {
Log.w(TAG, "Failed to encode GIF drawable data", e);
}
}
return success;
}
}
| GifDrawableEncoder |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/convert/CoerceNaNStringToNumberTest.java | {
"start": 442,
"end": 4104
} | class ____ {
float _v;
public void setV(float v) { _v = v; }
}
private final ObjectMapper MAPPER = newJsonMapper();
private final ObjectMapper MAPPER_NO_COERCION = jsonMapperBuilder()
.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS)
.build();
/*
/**********************************************************************
/* Test methods for coercing from "NaN Strings": tricky edge case as
/* NaNs are not legal JSON tokens by default (although Jackson has options
/* to allow)... so with 2.12 we consider String as natural representation
/* and not coercible. This may need to be resolved in future but for now
/* this is needed for backwards-compatibility.
/**********************************************************************
*/
@Test
public void testDoublePrimitiveNonNumeric() throws Exception
{
// first, simple case:
// bit tricky with binary fps but...
double value = Double.POSITIVE_INFINITY;
DoubleBean result = MAPPER.readValue("{\"v\":\""+value+"\"}", DoubleBean.class);
assertEquals(value, result._v);
// should work with arrays too..
double[] array = MAPPER.readValue("[ \"Infinity\" ]", double[].class);
assertNotNull(array);
assertEquals(1, array.length);
assertEquals(Double.POSITIVE_INFINITY, array[0]);
}
@Test
public void testDoublePrimFromNaNCoercionDisabled() throws Exception
{
// first, simple case:
double value = Double.POSITIVE_INFINITY;
DoubleBean result = MAPPER_NO_COERCION.readValue("{\"v\":\""+value+"\"}", DoubleBean.class);
assertEquals(value, result._v);
// should work with arrays too..
double[] array = MAPPER_NO_COERCION.readValue("[ \"Infinity\" ]", double[].class);
assertNotNull(array);
assertEquals(1, array.length);
assertEquals(Double.POSITIVE_INFINITY, array[0]);
}
@Test
public void testDoubleWrapperFromNaNCoercionDisabled() throws Exception
{
double value = Double.POSITIVE_INFINITY;
Double dv = MAPPER_NO_COERCION.readValue(q(String.valueOf(value)), Double.class);
assertTrue(dv.isInfinite());
}
@Test
public void testFloatPrimitiveNonNumeric() throws Exception
{
// bit tricky with binary fps but...
float value = Float.POSITIVE_INFINITY;
FloatBean result = MAPPER.readValue("{\"v\":\""+value+"\"}", FloatBean.class);
assertEquals(value, result._v);
// should work with arrays too..
float[] array = MAPPER.readValue("[ \"Infinity\" ]", float[].class);
assertNotNull(array);
assertEquals(1, array.length);
assertEquals(Float.POSITIVE_INFINITY, array[0]);
}
@Test
public void testFloatPriFromNaNCoercionDisabled() throws Exception
{
// first, simple case:
float value = Float.POSITIVE_INFINITY;
FloatBean result = MAPPER_NO_COERCION.readValue("{\"v\":\""+value+"\"}", FloatBean.class);
assertEquals(value, result._v);
// should work with arrays too..
float[] array = MAPPER_NO_COERCION.readValue("[ \"Infinity\" ]", float[].class);
assertNotNull(array);
assertEquals(1, array.length);
assertEquals(Float.POSITIVE_INFINITY, array[0]);
}
@Test
public void testFloatWrapperFromNaNCoercionDisabled() throws Exception
{
float value = Float.POSITIVE_INFINITY;
Float dv = MAPPER_NO_COERCION.readValue(q(String.valueOf(value)), Float.class);
assertTrue(dv.isInfinite());
}
}
| FloatBean |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/legacy/api/TableColumn.java | {
"start": 1511,
"end": 6518
} | class ____ {
private final String name;
private final DataType type;
private TableColumn(String name, DataType type) {
this.name = name;
this.type = type;
}
/** Creates a regular table column that represents physical data. */
public static PhysicalColumn physical(String name, DataType type) {
Preconditions.checkNotNull(name, "Column name can not be null.");
Preconditions.checkNotNull(type, "Column type can not be null.");
return new PhysicalColumn(name, type);
}
/** Creates a computed column that is computed from the given SQL expression. */
public static ComputedColumn computed(String name, DataType type, String expression) {
Preconditions.checkNotNull(name, "Column name can not be null.");
Preconditions.checkNotNull(type, "Column type can not be null.");
Preconditions.checkNotNull(expression, "Column expression can not be null.");
return new ComputedColumn(name, type, expression);
}
/**
* Creates a metadata column from metadata of the given column name.
*
* <p>The column is not virtual by default.
*/
public static MetadataColumn metadata(String name, DataType type) {
return metadata(name, type, null, false);
}
/**
* Creates a metadata column from metadata of the given column name.
*
* <p>Allows to specify whether the column is virtual or not.
*/
public static MetadataColumn metadata(String name, DataType type, boolean isVirtual) {
return metadata(name, type, null, isVirtual);
}
/**
* Creates a metadata column from metadata of the given alias.
*
* <p>The column is not virtual by default.
*/
public static MetadataColumn metadata(String name, DataType type, String metadataAlias) {
Preconditions.checkNotNull(metadataAlias, "Metadata alias can not be null.");
return metadata(name, type, metadataAlias, false);
}
/**
* Creates a metadata column from metadata of the given column name or from metadata of the
* given alias (if not null).
*
* <p>Allows to specify whether the column is virtual or not.
*/
public static MetadataColumn metadata(
String name, DataType type, @Nullable String metadataAlias, boolean isVirtual) {
Preconditions.checkNotNull(name, "Column name can not be null.");
Preconditions.checkNotNull(type, "Column type can not be null.");
return new MetadataColumn(name, type, metadataAlias, isVirtual);
}
/**
* @deprecated Use {@link #physical(String, DataType)} instead.
*/
@Deprecated
public static TableColumn of(String name, DataType type) {
return physical(name, type);
}
/**
* @deprecated Use {@link #computed(String, DataType, String)} instead.
*/
@Deprecated
public static TableColumn of(String name, DataType type, String expression) {
return computed(name, type, expression);
}
/**
* Returns whether the given column is a physical column of a table; neither computed nor
* metadata.
*/
public abstract boolean isPhysical();
/** Returns whether the given column is persisted in a sink operation. */
public abstract boolean isPersisted();
/** Returns the data type of this column. */
public DataType getType() {
return this.type;
}
/** Returns the name of this column. */
public String getName() {
return name;
}
/** Returns a string that summarizes this column for printing to a console. */
public String asSummaryString() {
final StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append(": ");
sb.append(type);
explainExtras()
.ifPresent(
e -> {
sb.append(" ");
sb.append(e);
});
return sb.toString();
}
/** Returns an explanation of specific column extras next to name and type. */
public abstract Optional<String> explainExtras();
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TableColumn that = (TableColumn) o;
return Objects.equals(this.name, that.name) && Objects.equals(this.type, that.type);
}
@Override
public int hashCode() {
return Objects.hash(this.name, this.type);
}
@Override
public String toString() {
return asSummaryString();
}
// --------------------------------------------------------------------------------------------
// Specific kinds of columns
// --------------------------------------------------------------------------------------------
/** Representation of a physical column. */
@Internal
public static | TableColumn |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/MlMetrics.java | {
"start": 18200,
"end": 26758
} | class ____.
*/
private void memoryLimitClusterSettingUpdated() {
nativeMemLimit = findNativeMemoryLimit(clusterService.localNode(), clusterService.getClusterSettings());
nativeMemFree = findNativeMemoryFree(nativeMemLimit, nativeMemAdUsage, nativeMemDfaUsage, nativeMemTrainedModelUsage);
}
/**
* Returns up-to-date stats about the states of the ML entities that are persistent tasks.
* Currently this includes:
* - Anomaly detection jobs
* - Datafeeds
* - Data frame analytics jobs
* <p>
* In the future it could possibly also include model snapshot upgrade tasks.
* <p>
* These stats relate to the whole cluster and <em>not</em> just the current node.
* <p>
* The caller is expected to cache the returned stats to avoid unnecessary recalculation.
*/
static MlTaskStatusCounts findTaskStatuses(PersistentTasksCustomMetadata tasks) {
int adOpeningCount = 0;
int adOpenedCount = 0;
int adClosingCount = 0;
int adFailedCount = 0;
int datafeedStartingCount = 0;
int datafeedStartedCount = 0;
int datafeedStoppingCount = 0;
int dfaStartingCount = 0;
int dfaStartedCount = 0;
int dfaReindexingCount = 0;
int dfaAnalyzingCount = 0;
int dfaStoppingCount = 0;
int dfaFailedCount = 0;
for (PersistentTasksCustomMetadata.PersistentTask<?> task : tasks.tasks()) {
switch (task.getTaskName()) {
case JOB_TASK_NAME:
switch (MlTasks.getJobStateModifiedForReassignments(task)) {
case OPENING -> ++adOpeningCount;
case OPENED -> ++adOpenedCount;
case CLOSING -> ++adClosingCount;
case FAILED -> ++adFailedCount;
}
break;
case DATAFEED_TASK_NAME:
switch (MlTasks.getDatafeedState(task)) {
case STARTING -> ++datafeedStartingCount;
case STARTED -> ++datafeedStartedCount;
case STOPPING -> ++datafeedStoppingCount;
}
break;
case DATA_FRAME_ANALYTICS_TASK_NAME:
switch (MlTasks.getDataFrameAnalyticsState(task)) {
case STARTING -> ++dfaStartingCount;
case STARTED -> ++dfaStartedCount;
case REINDEXING -> ++dfaReindexingCount;
case ANALYZING -> ++dfaAnalyzingCount;
case STOPPING -> ++dfaStoppingCount;
case FAILED -> ++dfaFailedCount;
}
break;
case JOB_SNAPSHOT_UPGRADE_TASK_NAME:
// Not currently tracked
// TODO: consider in the future, especially when we're at the stage of needing to upgrade serverless model snapshots
break;
}
}
return new MlTaskStatusCounts(
adOpeningCount,
adOpenedCount,
adClosingCount,
adFailedCount,
datafeedStartingCount,
datafeedStartedCount,
datafeedStoppingCount,
dfaStartingCount,
dfaStartedCount,
dfaReindexingCount,
dfaAnalyzingCount,
dfaStoppingCount,
dfaFailedCount
);
}
/**
* Return the memory usage, in bytes, of the anomaly detection jobs that are running on the
* current node.
*/
static long findAdMemoryUsage(AutodetectProcessManager autodetectProcessManager) {
return autodetectProcessManager.getOpenProcessMemoryUsage().getBytes();
}
/**
* Return the memory usage, in bytes, of the data frame analytics jobs that are running on the
* current node.
*/
static long findDfaMemoryUsage(DataFrameAnalyticsManager dataFrameAnalyticsManager, PersistentTasksCustomMetadata tasks) {
return dataFrameAnalyticsManager.getActiveTaskMemoryUsage(tasks).getBytes();
}
/**
* Returns up-to-date stats about the numbers of allocations of ML trained models.
* <p>
* These stats relate to the whole cluster and <em>not</em> just the current node.
* <p>
* The caller is expected to cache the returned stats to avoid unnecessary recalculation.
*/
static TrainedModelAllocationCounts findTrainedModelAllocationCounts(TrainedModelAssignmentMetadata metadata) {
int trainedModelsTargetAllocations = 0;
int trainedModelsCurrentAllocations = 0;
int trainedModelsFailedAllocations = 0;
int deploymentsWithFixedAllocations = 0;
int deploymentsWithDisabledAdaptiveAllocations = 0;
for (TrainedModelAssignment trainedModelAssignment : metadata.allAssignments().values()) {
trainedModelsTargetAllocations += trainedModelAssignment.totalTargetAllocations();
trainedModelsFailedAllocations += trainedModelAssignment.totalFailedAllocations();
trainedModelsCurrentAllocations += trainedModelAssignment.totalCurrentAllocations();
if (trainedModelAssignment.getAdaptiveAllocationsSettings() == null) {
deploymentsWithFixedAllocations += 1;
} else if ((trainedModelAssignment.getAdaptiveAllocationsSettings().getEnabled() == null)
|| (trainedModelAssignment.getAdaptiveAllocationsSettings().getEnabled() == false)) {
deploymentsWithDisabledAdaptiveAllocations += 1;
}
}
return new TrainedModelAllocationCounts(
trainedModelsTargetAllocations,
trainedModelsCurrentAllocations,
trainedModelsFailedAllocations,
deploymentsWithFixedAllocations,
deploymentsWithDisabledAdaptiveAllocations
);
}
/**
* Return the memory usage, in bytes, of the trained models that are running on the
* current node.
*/
static long findTrainedModelMemoryUsage(TrainedModelAssignmentMetadata metadata, String localNodeId) {
long trainedModelMemoryUsageBytes = 0;
for (TrainedModelAssignment assignment : metadata.allAssignments().values()) {
if (Optional.ofNullable(assignment.getNodeRoutingTable().get(localNodeId))
.map(RoutingInfo::getState)
.orElse(RoutingState.STOPPED)
.consumesMemory()) {
trainedModelMemoryUsageBytes += assignment.getTaskParams().estimateMemoryUsageBytes();
}
}
return trainedModelMemoryUsageBytes;
}
/**
* Return the maximum amount of memory, in bytes, permitted for ML processes running on the
* current node.
*/
static long findNativeMemoryLimit(DiscoveryNode localNode, ClusterSettings settings) {
return NativeMemoryCalculator.allowedBytesForMl(localNode, settings).orElse(0L);
}
/**
* Return the amount of free memory, in bytes, that remains available for ML processes running on the
* current node.
*/
static long findNativeMemoryFree(long nativeMemLimit, long nativeMemAdUsage, long nativeMemDfaUsage, long nativeMemTrainedModelUsage) {
long totalUsage = nativeMemAdUsage + nativeMemDfaUsage + nativeMemTrainedModelUsage;
if (totalUsage > 0) {
totalUsage += NATIVE_EXECUTABLE_CODE_OVERHEAD.getBytes();
}
return nativeMemLimit - totalUsage;
}
record MlTaskStatusCounts(
int adOpeningCount,
int adOpenedCount,
int adClosingCount,
int adFailedCount,
int datafeedStartingCount,
int datafeedStartedCount,
int datafeedStoppingCount,
int dfaStartingCount,
int dfaStartedCount,
int dfaReindexingCount,
int dfaAnalyzingCount,
int dfaStoppingCount,
int dfaFailedCount
) {
static final MlTaskStatusCounts EMPTY = new MlTaskStatusCounts(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
record TrainedModelAllocationCounts(
int trainedModelsTargetAllocations,
int trainedModelsCurrentAllocations,
int trainedModelsFailedAllocations,
int deploymentsWithFixedAllocations,
int deploymentsWithDisabledAdaptiveAllocations
) {
static final TrainedModelAllocationCounts EMPTY = new TrainedModelAllocationCounts(0, 0, 0, 0, 0);
}
}
| performs |
java | apache__camel | components/camel-http/src/test/java/org/apache/camel/component/http/HttpSendDynamicAwareTest.java | {
"start": 1351,
"end": 3683
} | class ____ extends BaseHttpTest {
private HttpServer localServer;
@Override
public void setupResources() throws Exception {
localServer = ServerBootstrap.bootstrap()
.setCanonicalHostName("localhost").setHttpProcessor(getBasicHttpProcessor())
.setConnectionReuseStrategy(getConnectionReuseStrategy()).setResponseFactory(getHttpResponseFactory())
.setSslContext(getSSLContext())
.register("/moes", new DrinkValidationHandler(GET.name(), null, null, "drink"))
.register("/joes", new DrinkValidationHandler(GET.name(), null, null, "drink")).create();
localServer.start();
}
@Override
public void cleanupResources() {
if (localServer != null) {
localServer.stop();
}
}
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:moes")
.toD("http://localhost:" + localServer.getLocalPort()
+ "/moes?throwExceptionOnFailure=false&drink=${header.drink}");
from("direct:joes")
.toD("http://localhost:" + localServer.getLocalPort()
+ "/joes?throwExceptionOnFailure=false&drink=${header.drink}");
}
};
}
@Test
public void testDynamicAware() {
String out = fluentTemplate.to("direct:moes").withHeader("drink", "beer").request(String.class);
assertEquals("Drinking beer", out);
out = fluentTemplate.to("direct:joes").withHeader("drink", "wine").request(String.class);
assertEquals("Drinking wine", out);
@SuppressWarnings("unlikely-arg-type")
// NOTE: this the registry can check correctly the String type.
// and there should only be one http endpoint as they are both on same host
boolean found = context.getEndpointRegistry()
.containsKey("http://localhost:" + localServer.getLocalPort() + "?throwExceptionOnFailure=false");
assertTrue(found, "Should find static uri");
// we only have 2xdirect and 1xhttp
assertEquals(3, context.getEndpointRegistry().size());
}
}
| HttpSendDynamicAwareTest |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/instance/HardwareDescription.java | {
"start": 1225,
"end": 6152
} | class ____ implements Serializable {
private static final long serialVersionUID = 3380016608300325361L;
public static final String FIELD_NAME_CPU_CORES = "cpuCores";
public static final String FIELD_NAME_SIZE_PHYSICAL_MEMORY = "physicalMemory";
public static final String FIELD_NAME_SIZE_JVM_HEAP = "freeMemory";
public static final String FIELD_NAME_SIZE_MANAGED_MEMORY = "managedMemory";
/** The number of CPU cores available to the JVM on the compute node. */
@JsonProperty(FIELD_NAME_CPU_CORES)
private final int numberOfCPUCores;
/** The size of physical memory in bytes available on the compute node. */
@JsonProperty(FIELD_NAME_SIZE_PHYSICAL_MEMORY)
private final long sizeOfPhysicalMemory;
/** The size of the JVM heap memory */
@JsonProperty(FIELD_NAME_SIZE_JVM_HEAP)
private final long sizeOfJvmHeap;
/** The size of the memory managed by the system for caching, hashing, sorting, ... */
@JsonProperty(FIELD_NAME_SIZE_MANAGED_MEMORY)
private final long sizeOfManagedMemory;
/**
* Constructs a new hardware description object.
*
* @param numberOfCPUCores The number of CPU cores available to the JVM on the compute node.
* @param sizeOfPhysicalMemory The size of physical memory in bytes available on the compute
* node.
* @param sizeOfJvmHeap The size of the JVM heap memory.
* @param sizeOfManagedMemory The size of the memory managed by the system for caching, hashing,
* sorting, ...
*/
@JsonCreator
public HardwareDescription(
@JsonProperty(FIELD_NAME_CPU_CORES) int numberOfCPUCores,
@JsonProperty(FIELD_NAME_SIZE_PHYSICAL_MEMORY) long sizeOfPhysicalMemory,
@JsonProperty(FIELD_NAME_SIZE_JVM_HEAP) long sizeOfJvmHeap,
@JsonProperty(FIELD_NAME_SIZE_MANAGED_MEMORY) long sizeOfManagedMemory) {
this.numberOfCPUCores = numberOfCPUCores;
this.sizeOfPhysicalMemory = sizeOfPhysicalMemory;
this.sizeOfJvmHeap = sizeOfJvmHeap;
this.sizeOfManagedMemory = sizeOfManagedMemory;
}
/**
* Returns the number of CPU cores available to the JVM on the compute node.
*
* @return the number of CPU cores available to the JVM on the compute node
*/
public int getNumberOfCPUCores() {
return this.numberOfCPUCores;
}
/**
* Returns the size of physical memory in bytes available on the compute node.
*
* @return the size of physical memory in bytes available on the compute node
*/
public long getSizeOfPhysicalMemory() {
return this.sizeOfPhysicalMemory;
}
/**
* Returns the size of the JVM heap memory
*
* @return The size of the JVM heap memory
*/
public long getSizeOfJvmHeap() {
return this.sizeOfJvmHeap;
}
/**
* Returns the size of the memory managed by the system for caching, hashing, sorting, ...
*
* @return The size of the memory managed by the system.
*/
public long getSizeOfManagedMemory() {
return this.sizeOfManagedMemory;
}
// --------------------------------------------------------------------------------------------
// Utils
// --------------------------------------------------------------------------------------------
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
HardwareDescription that = (HardwareDescription) o;
return numberOfCPUCores == that.numberOfCPUCores
&& sizeOfPhysicalMemory == that.sizeOfPhysicalMemory
&& sizeOfJvmHeap == that.sizeOfJvmHeap
&& sizeOfManagedMemory == that.sizeOfManagedMemory;
}
@Override
public int hashCode() {
return Objects.hash(
numberOfCPUCores, sizeOfPhysicalMemory, sizeOfJvmHeap, sizeOfManagedMemory);
}
@Override
public String toString() {
return String.format(
"cores=%d, physMem=%d, heap=%d, managed=%d",
numberOfCPUCores, sizeOfPhysicalMemory, sizeOfJvmHeap, sizeOfManagedMemory);
}
// --------------------------------------------------------------------------------------------
// Factory
// --------------------------------------------------------------------------------------------
public static HardwareDescription extractFromSystem(long managedMemory) {
final int numberOfCPUCores = Hardware.getNumberCPUCores();
final long sizeOfJvmHeap = Runtime.getRuntime().maxMemory();
final long sizeOfPhysicalMemory = Hardware.getSizeOfPhysicalMemory();
return new HardwareDescription(
numberOfCPUCores, sizeOfPhysicalMemory, sizeOfJvmHeap, managedMemory);
}
}
| HardwareDescription |
java | google__dagger | javatests/dagger/internal/codegen/KeywordValidatorTest.java | {
"start": 8971,
"end": 9073
} | class ____ {",
" @Inject lateinit var myVar: volatile",
"}",
" | MyClass |
java | quarkusio__quarkus | extensions/redis-cache/deployment/src/test/java/io/quarkus/cache/redis/deployment/MultipleCachesTest.java | {
"start": 646,
"end": 2914
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot(jar -> jar.addClasses(CachedService.class, TestUtil.class))
.overrideConfigKey("quarkus.cache.redis.cache2.prefix", "dummy");
@Inject
CachedService cachedService;
@Test
public void test() {
RedisDataSource redisDataSource = Arc.container().select(RedisDataSource.class).get();
List<String> allKeysAtStart = TestUtil.allRedisKeys(redisDataSource);
String key1FromCache1 = cachedService.cache1("1");
assertEquals(key1FromCache1, cachedService.cache1("1"));
List<String> newKeys = TestUtil.allRedisKeys(redisDataSource);
assertEquals(allKeysAtStart.size() + 1, newKeys.size());
Assertions.assertThat(newKeys).contains(expectedCache1Key("1"));
String key2FromCache1 = cachedService.cache1("2");
assertNotEquals(key2FromCache1, key1FromCache1);
newKeys = TestUtil.allRedisKeys(redisDataSource);
assertEquals(allKeysAtStart.size() + 2,
newKeys.size());
Assertions.assertThat(newKeys).contains(expectedCache1Key("1"), expectedCache1Key("2"));
Double key1FromCache2 = cachedService.cache2(1d);
assertEquals(key1FromCache2, cachedService.cache2(1d));
newKeys = TestUtil.allRedisKeys(redisDataSource);
assertEquals(allKeysAtStart.size() + 3, newKeys.size());
Assertions.assertThat(newKeys).contains(expectedCache1Key("1"), expectedCache1Key("2"), expectedCache2Key("1.0"));
Double key2FromCache2 = cachedService.cache2(2d);
assertNotEquals(key2FromCache2, key1FromCache2);
newKeys = TestUtil.allRedisKeys(redisDataSource);
assertEquals(allKeysAtStart.size() + 4, newKeys.size());
Assertions.assertThat(newKeys).contains(expectedCache1Key("1"), expectedCache1Key("2"), expectedCache2Key("1.0"),
expectedCache2Key("2.0"));
}
private static String expectedCache1Key(String key) {
return "cache:" + CachedService.CACHE1 + ":" + key;
}
private static String expectedCache2Key(String key) {
return "dummy:" + key;
}
@ApplicationScoped
public static | MultipleCachesTest |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SpringRabbitmqComponentBuilderFactory.java | {
"start": 1415,
"end": 1962
} | interface ____ {
/**
* Spring RabbitMQ (camel-spring-rabbitmq)
* Send and receive messages from RabbitMQ using the Spring RabbitMQ client.
*
* Category: messaging
* Since: 3.8
* Maven coordinates: org.apache.camel:camel-spring-rabbitmq
*
* @return the dsl builder
*/
static SpringRabbitmqComponentBuilder springRabbitmq() {
return new SpringRabbitmqComponentBuilderImpl();
}
/**
* Builder for the Spring RabbitMQ component.
*/
| SpringRabbitmqComponentBuilderFactory |
java | quarkusio__quarkus | test-framework/arquillian/src/main/java/io/quarkus/arquillian/ClassLoaderExceptionTransformer.java | {
"start": 529,
"end": 1805
} | class ____ {
@Inject
@DeploymentScoped
Instance<QuarkusDeployment> deployment;
@Inject
Instance<TestResult> testResultInstance;
public void transform(@Observes(precedence = -1000) Test event) {
TestResult testResult = testResultInstance.get();
if (testResult != null) {
Throwable res = testResult.getThrowable();
if (res != null) {
try {
if (res.getClass().getClassLoader() != null
&& res.getClass().getClassLoader() != getClass().getClassLoader()) {
if (res.getClass() == deployment.get().getAppClassLoader().loadClass(res.getClass().getName())) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(out);
oo.writeObject(res);
res = (Throwable) new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())).readObject();
testResult.setThrowable(res);
}
}
} catch (Exception ignored) {
}
}
}
}
}
| ClassLoaderExceptionTransformer |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/AutoBuilderTest.java | {
"start": 10452,
"end": 11185
} | interface ____ {
Builder2 setAnInt(int x);
Builder2 setAString(String x);
Builder2 setABigInteger(BigInteger x);
Overload build();
}
}
@Test
public void overloadedConstructor() {
Overload actual1 = Overload.builder1().setAnInt(23).setAString("skidoo").build();
Overload expected1 = new Overload(23, "skidoo");
assertThat(actual1).isEqualTo(expected1);
BigInteger big17 = BigInteger.valueOf(17);
Overload actual2 =
Overload.builder2().setAnInt(17).setAString("17").setABigInteger(big17).build();
Overload expected2 = new Overload(17, "17", big17);
assertThat(actual2).isEqualTo(expected2);
}
@AutoBuilder(callMethod = "of", ofClass = Simple.class)
| Builder2 |
java | apache__rocketmq | broker/src/main/java/org/apache/rocketmq/broker/client/ConsumerIdsChangeListener.java | {
"start": 853,
"end": 989
} | interface ____ {
void handle(ConsumerGroupEvent event, String group, Object... args);
void shutdown();
}
| ConsumerIdsChangeListener |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/commands/CommandInterfacesIntegrationTests.java | {
"start": 1693,
"end": 2818
} | class ____ {
protected static RedisClient client;
protected static RedisCommands<String, String> redis;
protected CommandInterfacesIntegrationTests() {
RedisURI redisURI = RedisURI.Builder.redis("127.0.0.1").withPort(16379).build();
client = RedisClient.create(redisURI);
redis = client.connect().sync();
}
@BeforeEach
void setUp() {
this.redis.flushall();
}
@Test
void issue2612() {
CustomCommands commands = CustomCommands.instance(getConnection());
Flux<Boolean> flux = commands.insert("myBloomFilter", 10000, 0.01, new String[] { "1", "2", "3", });
List<Boolean> res = flux.collectList().block();
assertThat(res).hasSize(3);
assertThat(res).contains(true, true, true);
}
protected StatefulConnection<String, String> getConnection() {
StatefulRedisConnection<String, String> src = redis.getStatefulConnection();
Assumptions.assumeFalse(Proxy.isProxyClass(src.getClass()), "Redis connection is proxy, skipping.");
return src;
}
private | CommandInterfacesIntegrationTests |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/StreamingHttpOutputMessage.java | {
"start": 1271,
"end": 2284
} | interface ____ extends HttpOutputMessage {
/**
* Set the streaming body callback for this message.
* <p>Note that this is mutually exclusive with {@link #getBody()}, which
* may instead aggregate the request body before sending it.
* @param body the streaming body callback
*/
void setBody(Body body);
/**
* Variant of {@link #setBody(Body)} for a non-streaming write.
* @param body the content to write
* @throws IOException if an I/O exception occurs
* @since 7.0
*/
default void setBody(byte[] body) throws IOException {
setBody(new Body() {
@Override
public void writeTo(OutputStream outputStream) throws IOException {
StreamUtils.copy(body, outputStream);
}
@Override
public boolean repeatable() {
return true;
}
});
}
/**
* Contract to stream request body content to an {@link OutputStream}.
* In some HTTP client libraries this is only possible indirectly through a
* callback mechanism.
*/
@FunctionalInterface
| StreamingHttpOutputMessage |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/slive/Weights.java | {
"start": 3315,
"end": 3696
} | class ____ implements Weightable {
@Override // Weightable
public Double weight(int elapsed, int duration) {
double normalized = (double) elapsed / (double) duration;
double result = Math.pow((normalized - 1), 2);
if (result < 0) {
result = 0;
}
if (result > 1) {
result = 1;
}
return result;
}
}
}
| BeginWeight |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/window/groupwindow/operator/WindowOperatorTest.java | {
"start": 88443,
"end": 89797
} | class ____ extends SessionWindowAssigner {
private static final long serialVersionUID = 1L;
private final long sessionTimeout;
private PointSessionWindowAssigner(long sessionTimeout) {
super(sessionTimeout, true);
this.sessionTimeout = sessionTimeout;
}
private PointSessionWindowAssigner(long sessionTimeout, boolean isEventTime) {
super(sessionTimeout, isEventTime);
this.sessionTimeout = sessionTimeout;
}
@Override
@SuppressWarnings("unchecked")
public Collection<TimeWindow> assignWindows(RowData element, long timestamp) {
int second = element.getInt(1);
if (second == 33) {
return Collections.singletonList(new TimeWindow(timestamp, timestamp));
}
return Collections.singletonList(new TimeWindow(timestamp, timestamp + sessionTimeout));
}
@Override
public SessionWindowAssigner withEventTime() {
return new PointSessionWindowAssigner(sessionTimeout, true);
}
@Override
public SessionWindowAssigner withProcessingTime() {
return new PointSessionWindowAssigner(sessionTimeout, false);
}
}
// sum, count, window_start, window_end
private static | PointSessionWindowAssigner |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/logging/DelegatingLoggingSystemFactoryTests.java | {
"start": 1031,
"end": 2400
} | class ____ {
private final ClassLoader classLoader = getClass().getClassLoader();
@Test
void getLoggingSystemWhenDelegatesFunctionIsNullReturnsNull() {
DelegatingLoggingSystemFactory factory = new DelegatingLoggingSystemFactory(null);
assertThat(factory.getLoggingSystem(this.classLoader)).isNull();
}
@Test
void getLoggingSystemWhenDelegatesFunctionReturnsNullReturnsNull() {
DelegatingLoggingSystemFactory factory = new DelegatingLoggingSystemFactory((cl) -> null);
assertThat(factory.getLoggingSystem(this.classLoader)).isNull();
}
@Test
void getLoggingSystemReturnsFirstNonNullLoggingSystem() {
List<LoggingSystemFactory> delegates = new ArrayList<>();
delegates.add(mock(LoggingSystemFactory.class));
delegates.add(mock(LoggingSystemFactory.class));
delegates.add(mock(LoggingSystemFactory.class));
LoggingSystem result = mock(LoggingSystem.class);
given(delegates.get(1).getLoggingSystem(this.classLoader)).willReturn(result);
DelegatingLoggingSystemFactory factory = new DelegatingLoggingSystemFactory((cl) -> delegates);
assertThat(factory.getLoggingSystem(this.classLoader)).isSameAs(result);
then(delegates.get(0)).should().getLoggingSystem(this.classLoader);
then(delegates.get(1)).should().getLoggingSystem(this.classLoader);
then(delegates.get(2)).shouldHaveNoInteractions();
}
}
| DelegatingLoggingSystemFactoryTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/FindGraphCollectionOrderByTest.java | {
"start": 4286,
"end": 5067
} | class ____ {
@Id
Long id;
@ManyToOne( fetch = FetchType.LAZY )
@JoinColumn( name = "parent_id" )
private Level1 parent;
@OneToMany( fetch = FetchType.LAZY,
mappedBy = "parent",
cascade = CascadeType.PERSIST )
@OrderBy( "id" )
private Set<Level3> children = new LinkedHashSet<>();
public Level2() {
}
public Level2(Level1 parent, Long id) {
this.parent = parent;
this.id = id;
parent.getChildren().add( this );
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Level1 getParent() {
return parent;
}
public void setParent(Level1 parent) {
this.parent = parent;
}
public Set<Level3> getChildren() {
return children;
}
}
@Entity( name = "Level3" )
static | Level2 |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMasterServiceLeadershipRunner.java | {
"start": 3243,
"end": 22589
} | class ____ implements JobManagerRunner, LeaderContender {
private static final Logger LOG =
LoggerFactory.getLogger(JobMasterServiceLeadershipRunner.class);
private final Object lock = new Object();
private final JobMasterServiceProcessFactory jobMasterServiceProcessFactory;
private final LeaderElection leaderElection;
private final JobResultStore jobResultStore;
private final LibraryCacheManager.ClassLoaderLease classLoaderLease;
private final FatalErrorHandler fatalErrorHandler;
private final CompletableFuture<Void> terminationFuture = new CompletableFuture<>();
private final CompletableFuture<JobManagerRunnerResult> resultFuture =
new CompletableFuture<>();
@GuardedBy("lock")
private State state = State.RUNNING;
@GuardedBy("lock")
private CompletableFuture<Void> sequentialOperation = FutureUtils.completedVoidFuture();
@GuardedBy("lock")
private JobMasterServiceProcess jobMasterServiceProcess =
JobMasterServiceProcess.waitingForLeadership();
@GuardedBy("lock")
private CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = new CompletableFuture<>();
@GuardedBy("lock")
private boolean hasCurrentLeaderBeenCancelled = false;
public JobMasterServiceLeadershipRunner(
JobMasterServiceProcessFactory jobMasterServiceProcessFactory,
LeaderElection leaderElection,
JobResultStore jobResultStore,
LibraryCacheManager.ClassLoaderLease classLoaderLease,
FatalErrorHandler fatalErrorHandler) {
this.jobMasterServiceProcessFactory = jobMasterServiceProcessFactory;
this.leaderElection = leaderElection;
this.jobResultStore = jobResultStore;
this.classLoaderLease = classLoaderLease;
this.fatalErrorHandler = fatalErrorHandler;
}
@Override
public CompletableFuture<Void> closeAsync() {
final CompletableFuture<Void> processTerminationFuture;
synchronized (lock) {
if (state == State.STOPPED) {
return terminationFuture;
}
state = State.STOPPED;
LOG.debug("Terminating the leadership runner for job {}.", getJobID());
jobMasterGatewayFuture.completeExceptionally(
new FlinkException(
"JobMasterServiceLeadershipRunner is closed. Therefore, the corresponding JobMaster will never acquire the leadership."));
resultFuture.complete(
JobManagerRunnerResult.forSuccess(
createExecutionGraphInfoWithJobStatus(JobStatus.SUSPENDED)));
processTerminationFuture = jobMasterServiceProcess.closeAsync();
}
final CompletableFuture<Void> serviceTerminationFuture =
FutureUtils.runAfterwards(
processTerminationFuture,
() -> {
classLoaderLease.release();
leaderElection.close();
});
FutureUtils.forward(serviceTerminationFuture, terminationFuture);
terminationFuture.whenComplete(
(unused, throwable) ->
LOG.debug("Leadership runner for job {} has been terminated.", getJobID()));
return terminationFuture;
}
@Override
public void start() throws Exception {
LOG.debug("Start leadership runner for job {}.", getJobID());
leaderElection.startLeaderElection(this);
}
@Override
public CompletableFuture<JobMasterGateway> getJobMasterGateway() {
synchronized (lock) {
return jobMasterGatewayFuture;
}
}
@Override
public CompletableFuture<JobManagerRunnerResult> getResultFuture() {
return resultFuture;
}
@Override
public JobID getJobID() {
return jobMasterServiceProcessFactory.getJobId();
}
@Override
public CompletableFuture<Acknowledge> cancel(Duration timeout) {
synchronized (lock) {
hasCurrentLeaderBeenCancelled = true;
return getJobMasterGateway()
.thenCompose(jobMasterGateway -> jobMasterGateway.cancel(timeout))
.exceptionally(
e -> {
throw new CompletionException(
new JobCancellationFailedException(
"Cancellation failed.",
ExceptionUtils.stripCompletionException(e)));
});
}
}
@Override
public CompletableFuture<JobStatus> requestJobStatus(Duration timeout) {
return requestJob(timeout)
.thenApply(
executionGraphInfo ->
executionGraphInfo.getArchivedExecutionGraph().getState());
}
@Override
public CompletableFuture<JobDetails> requestJobDetails(Duration timeout) {
return requestJob(timeout)
.thenApply(
executionGraphInfo ->
JobDetails.createDetailsForJob(
executionGraphInfo.getArchivedExecutionGraph()));
}
@Override
public CompletableFuture<ExecutionGraphInfo> requestJob(Duration timeout) {
synchronized (lock) {
if (state == State.RUNNING) {
if (jobMasterServiceProcess.isInitializedAndRunning()) {
return getJobMasterGateway()
.thenCompose(jobMasterGateway -> jobMasterGateway.requestJob(timeout));
} else {
return CompletableFuture.completedFuture(
createExecutionGraphInfoWithJobStatus(
hasCurrentLeaderBeenCancelled
? JobStatus.CANCELLING
: JobStatus.INITIALIZING));
}
} else {
return resultFuture.thenApply(JobManagerRunnerResult::getExecutionGraphInfo);
}
}
}
@Override
public boolean isInitialized() {
synchronized (lock) {
return jobMasterServiceProcess.isInitializedAndRunning();
}
}
@Override
public void grantLeadership(UUID leaderSessionID) {
runIfStateRunning(
() -> startJobMasterServiceProcessAsync(leaderSessionID),
"starting a new JobMasterServiceProcess");
}
@GuardedBy("lock")
private void startJobMasterServiceProcessAsync(UUID leaderSessionId) {
sequentialOperation =
sequentialOperation.thenCompose(
unused ->
jobResultStore
.hasJobResultEntryAsync(getJobID())
.thenCompose(
hasJobResult -> {
if (hasJobResult) {
return handleJobAlreadyDoneIfValidLeader(
leaderSessionId);
} else {
return createNewJobMasterServiceProcessIfValidLeader(
leaderSessionId);
}
}));
handleAsyncOperationError(sequentialOperation, "Could not start the job manager.");
}
private CompletableFuture<Void> handleJobAlreadyDoneIfValidLeader(UUID leaderSessionId) {
return runIfValidLeader(
leaderSessionId, () -> jobAlreadyDone(leaderSessionId), "check completed job");
}
private CompletableFuture<Void> createNewJobMasterServiceProcessIfValidLeader(
UUID leaderSessionId) {
return runIfValidLeader(
leaderSessionId,
() ->
// the heavy lifting of the JobMasterServiceProcess instantiation is still
// done asynchronously (see
// DefaultJobMasterServiceFactory#createJobMasterService executing the logic
// on the leaderOperation thread in the DefaultLeaderElectionService should
// be, therefore, fine
ThrowingRunnable.unchecked(
() -> createNewJobMasterServiceProcess(leaderSessionId))
.run(),
"create new job master service process");
}
private void printLogIfNotValidLeader(String actionDescription, UUID leaderSessionId) {
LOG.debug(
"Ignore leader action '{}' because the leadership runner is no longer the valid leader for {}.",
actionDescription,
leaderSessionId);
}
private ExecutionGraphInfo createExecutionGraphInfoWithJobStatus(JobStatus jobStatus) {
return new ExecutionGraphInfo(
jobMasterServiceProcessFactory.createArchivedExecutionGraph(jobStatus, null));
}
private void jobAlreadyDone(UUID leaderSessionId) {
LOG.info(
"{} for job {} was granted leadership with leader id {}, but job was already done.",
getClass().getSimpleName(),
getJobID(),
leaderSessionId);
resultFuture.complete(
JobManagerRunnerResult.forSuccess(
new ExecutionGraphInfo(
jobMasterServiceProcessFactory.createArchivedExecutionGraph(
JobStatus.FAILED,
new JobAlreadyDoneException(getJobID())))));
}
@GuardedBy("lock")
private void createNewJobMasterServiceProcess(UUID leaderSessionId) {
Preconditions.checkState(jobMasterServiceProcess.closeAsync().isDone());
LOG.info(
"{} for job {} was granted leadership with leader id {}. Creating new {}.",
getClass().getSimpleName(),
getJobID(),
leaderSessionId,
JobMasterServiceProcess.class.getSimpleName());
jobMasterServiceProcess = jobMasterServiceProcessFactory.create(leaderSessionId);
forwardIfValidLeader(
leaderSessionId,
jobMasterServiceProcess.getJobMasterGatewayFuture(),
jobMasterGatewayFuture,
"JobMasterGatewayFuture from JobMasterServiceProcess");
forwardResultFuture(leaderSessionId, jobMasterServiceProcess.getResultFuture());
confirmLeadership(leaderSessionId, jobMasterServiceProcess.getLeaderAddressFuture());
}
private void confirmLeadership(
UUID leaderSessionId, CompletableFuture<String> leaderAddressFuture) {
FutureUtils.assertNoException(
leaderAddressFuture.thenCompose(
address ->
callIfRunning(
() -> {
LOG.debug(
"Confirm leadership {}.",
leaderSessionId);
return leaderElection.confirmLeadershipAsync(
leaderSessionId, address);
},
"confirming leadership")
.orElse(FutureUtils.completedVoidFuture())));
}
private void forwardResultFuture(
UUID leaderSessionId, CompletableFuture<JobManagerRunnerResult> resultFuture) {
resultFuture.whenComplete(
(jobManagerRunnerResult, throwable) ->
runIfValidLeader(
leaderSessionId,
() -> onJobCompletion(jobManagerRunnerResult, throwable),
"result future forwarding"));
}
@GuardedBy("lock")
private void onJobCompletion(
JobManagerRunnerResult jobManagerRunnerResult, Throwable throwable) {
state = State.JOB_COMPLETED;
LOG.debug("Completing the result for job {}.", getJobID());
if (throwable != null) {
resultFuture.completeExceptionally(throwable);
jobMasterGatewayFuture.completeExceptionally(
new FlinkException(
"Could not retrieve JobMasterGateway because the JobMaster failed.",
throwable));
} else {
if (!jobManagerRunnerResult.isSuccess()) {
jobMasterGatewayFuture.completeExceptionally(
new FlinkException(
"Could not retrieve JobMasterGateway because the JobMaster initialization failed.",
jobManagerRunnerResult.getInitializationFailure()));
}
resultFuture.complete(jobManagerRunnerResult);
}
}
@Override
public void revokeLeadership() {
runIfStateRunning(
this::stopJobMasterServiceProcessAsync,
"revoke leadership from JobMasterServiceProcess");
}
@GuardedBy("lock")
private void stopJobMasterServiceProcessAsync() {
sequentialOperation =
sequentialOperation.thenCompose(
ignored ->
callIfRunning(
this::stopJobMasterServiceProcess,
"stop leading JobMasterServiceProcess")
.orElse(FutureUtils.completedVoidFuture()));
handleAsyncOperationError(sequentialOperation, "Could not suspend the job manager.");
}
@GuardedBy("lock")
private CompletableFuture<Void> stopJobMasterServiceProcess() {
LOG.info(
"{} for job {} was revoked leadership with leader id {}. Stopping current {}.",
getClass().getSimpleName(),
getJobID(),
jobMasterServiceProcess.getLeaderSessionId(),
JobMasterServiceProcess.class.getSimpleName());
jobMasterGatewayFuture.completeExceptionally(
new FlinkException(
"Cannot obtain JobMasterGateway because the JobMaster lost leadership."));
jobMasterGatewayFuture = new CompletableFuture<>();
hasCurrentLeaderBeenCancelled = false;
return jobMasterServiceProcess.closeAsync();
}
@Override
public void handleError(Exception exception) {
fatalErrorHandler.onFatalError(exception);
}
private void handleAsyncOperationError(CompletableFuture<Void> operation, String message) {
operation.whenComplete(
(unused, throwable) -> {
if (throwable != null) {
runIfStateRunning(
() ->
handleJobMasterServiceLeadershipRunnerError(
new FlinkException(message, throwable)),
"handle JobMasterServiceLeadershipRunner error");
}
});
}
private void handleJobMasterServiceLeadershipRunnerError(Throwable cause) {
if (ExceptionUtils.isJvmFatalError(cause)) {
fatalErrorHandler.onFatalError(cause);
} else {
resultFuture.completeExceptionally(cause);
}
}
private void runIfStateRunning(Runnable action, String actionDescription) {
synchronized (lock) {
if (isRunning()) {
action.run();
} else {
LOG.debug(
"Ignore '{}' because the leadership runner is no longer running.",
actionDescription);
}
}
}
private <T> Optional<T> callIfRunning(
Supplier<? extends T> supplier, String supplierDescription) {
synchronized (lock) {
if (isRunning()) {
return Optional.of(supplier.get());
} else {
LOG.debug(
"Ignore '{}' because the leadership runner is no longer running.",
supplierDescription);
return Optional.empty();
}
}
}
@GuardedBy("lock")
private boolean isRunning() {
return state == State.RUNNING;
}
private CompletableFuture<Void> runIfValidLeader(
UUID expectedLeaderId, Runnable action, Runnable noLeaderFallback) {
synchronized (lock) {
if (isRunning() && leaderElection != null) {
return leaderElection
.hasLeadershipAsync(expectedLeaderId)
.thenAccept(
hasLeadership -> {
synchronized (lock) {
if (isRunning() && hasLeadership) {
action.run();
} else {
noLeaderFallback.run();
}
}
});
} else {
noLeaderFallback.run();
return FutureUtils.completedVoidFuture();
}
}
}
private CompletableFuture<Void> runIfValidLeader(
UUID expectedLeaderId, Runnable action, String noLeaderFallbackCommandDescription) {
return runIfValidLeader(
expectedLeaderId,
action,
() ->
printLogIfNotValidLeader(
noLeaderFallbackCommandDescription, expectedLeaderId));
}
private <T> void forwardIfValidLeader(
UUID expectedLeaderId,
CompletableFuture<? extends T> source,
CompletableFuture<T> target,
String forwardDescription) {
source.whenComplete(
(t, throwable) ->
runIfValidLeader(
expectedLeaderId,
() -> {
if (throwable != null) {
target.completeExceptionally(throwable);
} else {
target.complete(t);
}
},
forwardDescription));
}
| JobMasterServiceLeadershipRunner |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.