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 | apache__camel | components/camel-cxf/camel-cxf-rest/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfConverter.java | {
"start": 1862,
"end": 5530
} | class ____ {
private CxfConverter() {
// Helper class
}
@Converter
public static MessageContentsList toMessageContentsList(final Object[] array) {
if (array != null) {
return new MessageContentsList(array);
} else {
return new MessageContentsList();
}
}
@Converter
public static QName toQName(String qname) {
return QName.valueOf(qname);
}
@Converter
public static Object[] toArray(Object object) {
if (object instanceof Collection) {
return ((Collection<?>) object).toArray();
} else {
Object[] answer;
if (object == null) {
answer = new Object[0];
} else {
answer = new Object[1];
answer[0] = object;
}
return answer;
}
}
@Converter
public static String soapMessageToString(final SOAPMessage soapMessage, Exchange exchange)
throws SOAPException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
soapMessage.writeTo(baos);
return baos.toString(ExchangeHelper.getCharsetName(exchange));
}
@Converter
public static InputStream soapMessageToInputStream(final SOAPMessage soapMessage, Exchange exchange)
throws SOAPException, IOException {
CachedOutputStream cos = new CachedOutputStream(exchange);
soapMessage.writeTo(cos);
return cos.getInputStream();
}
@Converter
public static DataFormat toDataFormat(final String name) {
return DataFormat.valueOf(name.toUpperCase());
}
@Converter(allowNull = true)
public static InputStream toInputStream(Response response, Exchange exchange) {
Object obj = response.getEntity();
if (obj == null) {
return null;
}
if (obj instanceof InputStream) {
// short circuit the lookup
return (InputStream) obj;
}
TypeConverterRegistry registry = exchange.getContext().getTypeConverterRegistry();
TypeConverter tc = registry.lookup(InputStream.class, obj.getClass());
if (tc != null) {
return tc.convertTo(InputStream.class, exchange, obj);
}
return null;
}
@Converter(allowNull = true)
public static StreamCache toStreamCache(Response response, Exchange exchange) {
InputStream is = toInputStream(response, exchange);
TypeConverterRegistry registry = exchange.getContext().getTypeConverterRegistry();
TypeConverter tc = registry.lookup(StreamCache.class, is.getClass());
if (tc != null) {
return tc.convertTo(StreamCache.class, exchange, is);
}
return null;
}
/**
* Use a fallback type converter so we can convert the embedded list element if the value is MessageContentsList.
* The algorithm of this converter finds the first non-null list element from the list and applies conversion to the
* list element.
*
* @param type the desired type to be converted to
* @param exchange optional exchange which can be null
* @param value the object to be converted
* @param registry type converter registry
* @return the converted value of the desired type or null if no suitable converter found
*/
@SuppressWarnings("unchecked")
@Converter(fallback = true)
public static <T> T convertTo(
Class<T> type, Exchange exchange, Object value,
TypeConverterRegistry registry) {
// CXF-WS MessageContentsList | CxfConverter |
java | apache__flink | flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/functions/WindowReaderFunction.java | {
"start": 2468,
"end": 3708
} | interface ____<W extends Window> extends java.io.Serializable {
/** Returns the window that is being evaluated. */
W window();
/**
* Retrieves a {@link State} object that can be used to interact with fault-tolerant state
* that is scoped to the trigger which corresponds to the current window.
*
* @param descriptor The StateDescriptor that contains the name and type of the state that
* is being accessed.
* @param <S> The type of the state.
* @return The partitioned state object.
*/
<S extends State> S triggerState(StateDescriptor<S, ?> descriptor);
/** State accessor for per-key and per-window state. */
KeyedStateStore windowState();
/** State accessor for per-key global state. */
KeyedStateStore globalState();
/**
* @return All event time timers registered by a trigger for the current window.
*/
Set<Long> registeredEventTimeTimers() throws Exception;
/**
* @return All processing time timers registered by a trigger for the current window.
*/
Set<Long> registeredProcessingTimeTimers() throws Exception;
}
}
| Context |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/strings/Strings_assertContainsOnlyDigits_Test.java | {
"start": 1235,
"end": 2392
} | class ____ extends StringsBaseTest {
@Test
void should_pass_if_actual_contains_only_digits() {
strings.assertContainsOnlyDigits(someInfo(), "10");
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertContainsOnlyDigits(someInfo(), null))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_contains_any_non_digit_character() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertContainsOnlyDigits(someInfo(), "10$"))
.withMessage(shouldContainOnlyDigits("10$", '$', 2).create());
}
// See https://github.com/assertj/assertj/pull/342 - discussion on failing the assertion for empty CharSequence
@Test
void should_fail_if_actual_is_empty() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertContainsOnlyDigits(someInfo(), ""))
.withMessage(shouldContainOnlyDigits("").create());
}
}
| Strings_assertContainsOnlyDigits_Test |
java | netty__netty | codec-classes-quic/src/main/java/io/netty/handler/codec/quic/BoringSSLCertificateCallbackTask.java | {
"start": 778,
"end": 2838
} | class ____ extends BoringSSLTask {
private final byte[] keyTypeBytes;
private final byte[][] asn1DerEncodedPrincipals;
private final String[] authMethods;
private final BoringSSLCertificateCallback callback;
// Accessed via JNI.
private long key;
private long chain;
BoringSSLCertificateCallbackTask(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals,
String[] authMethods, BoringSSLCertificateCallback callback) {
// It is important that this constructor never throws. Be sure to not change this!
super(ssl);
// It's ok to not clone the arrays as we create these in JNI and not-reuse.
this.keyTypeBytes = keyTypeBytes;
this.asn1DerEncodedPrincipals = asn1DerEncodedPrincipals;
this.authMethods = authMethods;
this.callback = callback;
}
// See https://www.openssl.org/docs/man1.0.2/man3/SSL_set_cert_cb.html.
@Override
protected void runTask(long ssl, TaskCallback taskCallback) {
try {
long[] result = callback.handle(ssl, keyTypeBytes, asn1DerEncodedPrincipals, authMethods);
if (result == null) {
taskCallback.onResult(ssl, 0);
} else {
this.key = result[0];
this.chain = result[1];
taskCallback.onResult(ssl, 1);
}
} catch (Exception e) {
// Just catch the exception and return 0 to fail the handshake.
// The problem is that rethrowing here is really "useless" as we will process it as part of an openssl
// c callback which needs to return 0 for an error to abort the handshake.
taskCallback.onResult(ssl, 0);
}
}
@Override
protected void destroy() {
if (key != 0) {
BoringSSL.EVP_PKEY_free(key);
key = 0;
}
if (chain != 0) {
BoringSSL.CRYPTO_BUFFER_stack_free(chain);
chain = 0;
}
}
}
| BoringSSLCertificateCallbackTask |
java | alibaba__nacos | console/src/main/java/com/alibaba/nacos/console/handler/impl/noop/ai/McpNoopHandler.java | {
"start": 1752,
"end": 4326
} | class ____ implements McpHandler {
private static final String MCP_NOT_ENABLED_MESSAGE = "Nacos AI MCP module and API required both `naming` and `config` module.";
@Override
public Page<McpServerBasicInfo> listMcpServers(String namespaceId, String mcpName, String search, int pageNo,
int pageSize) throws NacosException {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public McpServerDetailInfo getMcpServer(String namespaceId, String mcpName, String mcpId, String version)
throws NacosException {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public String createMcpServer(String namespaceId, McpServerBasicInfo serverSpecification,
McpToolSpecification toolSpecification, McpEndpointSpec endpointSpecification) throws NacosException {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public void updateMcpServer(String namespaceId, boolean isPublish, McpServerBasicInfo serverSpecification,
McpToolSpecification toolSpecification, McpEndpointSpec endpointSpecification, boolean overrideExisting) throws NacosException {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public void deleteMcpServer(String namespaceId, String mcpName, String mcpId, String version)
throws NacosException {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public McpServerImportValidationResult validateImport(String namespaceId, McpServerImportRequest request) throws NacosException {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
@Override
public McpServerImportResponse executeImport(String namespaceId, McpServerImportRequest request) throws NacosException {
throw new NacosApiException(NacosException.SERVER_NOT_IMPLEMENTED, ErrorCode.API_FUNCTION_DISABLED,
MCP_NOT_ENABLED_MESSAGE);
}
}
| McpNoopHandler |
java | google__auto | value/src/main/java/com/google/auto/value/processor/SimpleMethod.java | {
"start": 1270,
"end": 2505
} | class ____ {
private final String access;
private final String name;
private final String throwsString;
SimpleMethod(ExecutableElement method) {
this.access = access(method);
this.name = method.getSimpleName().toString();
this.throwsString = throwsString(method);
}
public String getAccess() {
return access;
}
public String getName() {
return name;
}
public String getThrows() {
return throwsString;
}
/**
* Returns an appropriate string to be used in code for the access specification of the given
* method. This will be {@code public} or {@code protected} followed by a space, or the empty
* string for default access.
*/
static String access(ExecutableElement method) {
Set<Modifier> mods = method.getModifiers();
if (mods.contains(Modifier.PUBLIC)) {
return "public ";
} else if (mods.contains(Modifier.PROTECTED)) {
return "protected ";
} else {
return "";
}
}
private static String throwsString(ExecutableElement method) {
if (method.getThrownTypes().isEmpty()) {
return "";
}
return "throws "
+ method.getThrownTypes().stream().map(TypeEncoder::encode).collect(joining(", "));
}
}
| SimpleMethod |
java | elastic__elasticsearch | x-pack/plugin/ml/qa/single-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/InferencePipelineAggIT.java | {
"start": 637,
"end": 10269
} | class ____ extends InferenceTestCase {
private static final String MODEL_ID = "a-complex-regression-model";
private static final String INDEX_NAME = "store";
@Before
public void setupModelAndData() throws IOException {
putRegressionModel(MODEL_ID, """
{
"description": "super complex model for tests",
"input": {"field_names": ["avg_cost", "item"]},
"inference_config": {
"regression": {
"results_field": "regression-value",
"num_top_feature_importance_values": 2
}
},
"definition": {
"preprocessors" : [{
"one_hot_encoding": {
"field": "product_type",
"hot_map": {
"TV": "type_tv",
"VCR": "type_vcr",
"Laptop": "type_laptop"
}
}
}],
"trained_model": {
"ensemble": {
"feature_names": [],
"target_type": "regression",
"trained_models": [
{
"tree": {
"feature_names": [
"avg_cost", "type_tv", "type_vcr", "type_laptop"
],
"tree_structure": [
{
"node_index": 0,
"split_feature": 0,
"split_gain": 12,
"threshold": 38,
"decision_type": "lte",
"default_left": true,
"left_child": 1,
"right_child": 2
},
{
"node_index": 1,
"leaf_value": 5.0
},
{
"node_index": 2,
"leaf_value": 2.0
}
],
"target_type": "regression"
}
}
]
}
}
}
}""");
createIndex(INDEX_NAME, Settings.EMPTY, """
"properties":{
"product":{"type": "keyword"},
"cost":{"type": "integer"},
"time": {"type": "date"}}""");
indexData("{ \"product\": \"TV\", \"cost\": 300, \"time\": 1587501233000 }");
indexData("{ \"product\": \"TV\", \"cost\": 400, \"time\": 1587501233000}");
indexData("{ \"product\": \"VCR\", \"cost\": 150, \"time\": 1587501233000 }");
indexData("{ \"product\": \"VCR\", \"cost\": 180, \"time\": 1587501233000 }");
indexData("{ \"product\": \"Laptop\", \"cost\": 15000, \"time\": 1587501233000 }");
adminClient().performRequest(new Request("POST", INDEX_NAME + "/_refresh"));
}
private void indexData(String data) throws IOException {
Request request = new Request("POST", INDEX_NAME + "/_doc");
request.setJsonEntity(data);
client().performRequest(request);
}
private Response search(String searchBody) throws IOException {
Request request = new Request("POST", INDEX_NAME + "/_search");
request.setJsonEntity(searchBody);
return client().performRequest(request);
}
@SuppressWarnings("unchecked")
public void testPipelineRegressionSimple() throws Exception {
Response searchResponse = search("""
{
"size": 0,
"aggs": {
"good": {
"terms": {
"field": "product",
"size": 10
},
"aggs": {
"avg_cost_agg": {
"avg": {
"field": "cost"
}
},
"regression_agg": {
"inference": {
"model_id": "a-complex-regression-model",
"inference_config": {
"regression": {
"results_field": "value"
}
},
"buckets_path": {
"avg_cost": "avg_cost_agg"
}
}
}
}
}
}
}""");
assertThat(
(List<Double>) XContentMapValues.extractValue("aggregations.good.buckets.regression_agg.value", responseAsMap(searchResponse)),
contains(2.0, 2.0, 2.0)
);
}
@SuppressWarnings("unchecked")
public void testPipelineAggReferencingSingleBucket() throws Exception {
Response searchResponse = search("""
{
"size": 0,
"query": {
"match_all": {}
},
"aggs": {
"date_histo": {
"date_histogram": {
"field": "time",
"fixed_interval": "1d"
},
"aggs": {
"good": {
"terms": {
"field": "product",
"size": 10
},
"aggs": {
"avg_cost_agg": {
"avg": {
"field": "cost"
}
}
}
},
"regression_agg": {
"inference": {
"model_id": "a-complex-regression-model",
"buckets_path": {
"avg_cost": "good['TV']>avg_cost_agg",
"product_type": "good['TV']"
}
}
}
}
}
}
}""");
assertThat(
(List<Double>) XContentMapValues.extractValue(
"aggregations.date_histo.buckets.regression_agg.value",
responseAsMap(searchResponse)
),
contains(2.0)
);
}
@SuppressWarnings("unchecked")
public void testAllFieldsMissingWarning() throws IOException {
Response searchResponse = search("""
{
"size": 0,
"query": { "match_all" : { } },
"aggs": {
"good": {
"terms": {
"field": "product",
"size": 10
},
"aggs": {
"avg_cost_agg": {
"avg": {
"field": "cost"
}
},
"regression_agg" : {
"inference": {
"model_id": "a-complex-regression-model",
"buckets_path": {
"cost" : "avg_cost_agg"
}
}
}
}
}
}
}""");
assertThat(
(List<String>) XContentMapValues.extractValue(
"aggregations.good.buckets.regression_agg.warning",
responseAsMap(searchResponse)
),
contains(
"Model [a-complex-regression-model] could not be inferred as all fields were missing",
"Model [a-complex-regression-model] could not be inferred as all fields were missing",
"Model [a-complex-regression-model] could not be inferred as all fields were missing"
)
);
}
}
| InferencePipelineAggIT |
java | redisson__redisson | redisson/src/main/java/org/redisson/spring/cache/CacheConfigSupport.java | {
"start": 1134,
"end": 2445
} | class ____ {
private final Yaml yamlParser;
private final Yaml jsonParser;
public CacheConfigSupport() {
LoaderOptions yamlLoaderOptions = new LoaderOptions();
yamlLoaderOptions.setTagInspector(tag -> true); // Allow all tags
DumperOptions yamlDumperOptions = new DumperOptions();
yamlDumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlDumperOptions.setPrettyFlow(true);
yamlDumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
yamlDumperOptions.setIndent(2);
CustomConstructor yamlConstructor = new CustomConstructor(yamlLoaderOptions);
this.yamlParser = new Yaml(yamlConstructor, new Representer(yamlDumperOptions), yamlDumperOptions, yamlLoaderOptions);
DumperOptions jsonDumperOptions = new DumperOptions();
jsonDumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW);
jsonDumperOptions.setPrettyFlow(false);
jsonDumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED);
Representer representer = new Representer(jsonDumperOptions);
representer.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW);
this.jsonParser = new Yaml(representer, jsonDumperOptions);
}
private static | CacheConfigSupport |
java | apache__camel | components/camel-jetty/src/test/java/org/apache/camel/component/jetty/MultiPartFormBigFileTest.java | {
"start": 1804,
"end": 4465
} | class ____ extends BaseJettyTest {
@TempDir
File tempDir;
private HttpEntity createMultipartRequestEntityWithBigFile() {
return MultipartEntityBuilder.create()
.addTextBody("comment", "A binary file of some kind").build();
}
@Test
void testSendMultiPartFormWithBigFile() throws Exception {
HttpPost post = new HttpPost("http://localhost:" + getPort() + "/test");
post.setEntity(createMultipartRequestEntityWithBigFile());
try (CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(post)) {
int status = response.getCode();
assertEquals(200, status, "Get a wrong response status");
String result = IOHelper.loadText(response.getEntity().getContent()).trim();
assertEquals(Integer.toString("A binary file of some kind".length()), result, "Get a wrong result");
}
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
fromF("jetty://http://localhost:{{port}}/test?filesLocation=%s&fileSizeThreshold=1",
tempDir.getAbsolutePath())
.process(new Processor() {
public void process(Exchange exchange) {
AttachmentMessage in = exchange.getIn(AttachmentMessage.class);
assertEquals(1, in.getAttachments().size(), "Get a wrong attachment size");
// The file name is attachment id
DataHandler data = in.getAttachment("comment");
assertNotNull(data, "Should get the DataHandle comment");
assertTrue(tempDir.exists());
int received = 0;
try (InputStream files = data.getInputStream()) {
byte[] buffer = new byte[256];
int b;
while ((b = files.read(buffer)) != -1) {
received += b;
}
exchange.getMessage().setBody(Integer.toString(received));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
});
}
};
}
}
| MultiPartFormBigFileTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadePersistTest.java | {
"start": 389,
"end": 851
} | class ____ {
@Test
public void persistTest(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
//tag::pc-cascade-persist-example[]
Person person = new Person();
person.setId(1L);
person.setName("John Doe");
Phone phone = new Phone();
phone.setId(1L);
phone.setNumber("123-456-7890");
person.addPhone(phone);
entityManager.persist(person);
//end::pc-cascade-persist-example[]
});
}
}
| CascadePersistTest |
java | apache__avro | lang/java/ipc/src/test/java/org/apache/avro/io/Perf.java | {
"start": 45538,
"end": 45914
} | class ____ extends GenericTest {
public GenericOneTimeUse() throws IOException {
super("GenericOneTimeUse_");
isWriteTest = false;
}
@Override
protected GenericDatumReader<Object> getReader() {
return newReader();
}
@Override
protected Decoder getDecoder() {
return newDecoder();
}
}
static abstract | GenericOneTimeUse |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/scenario/ConnectionInterruptionReactiveTest.java | {
"start": 6894,
"end": 10170
} | class
____ tracker = ReconnectionTimingTracker.withName("PubSub").trackWithEventBus(subscriberClient);
StatefulRedisPubSubConnection<String, String> pubSubConnection = subscriberClient.connectPubSub(uri);
// Also track with state listener for comparison
tracker.trackWithStateListener(pubSubConnection);
RedisPubSubReactiveCommands<String, String> pubSubReactive = pubSubConnection.reactive();
pubSubConnection.addListener(new RedisPubSubAdapter<String, String>() {
@Override
public void message(String channel, String message) {
log.debug("Received message: {}", message);
messagesReceived.incrementAndGet();
receivedMessages.add(message);
}
});
StepVerifier.create(pubSubReactive.subscribe("test")).verifyComplete();
Disposable publisherSubscription = Flux.interval(Duration.ofMillis(200)).flatMap(
i -> publisherReactive.publish("test", String.valueOf(messagesSent.getAndIncrement())).onErrorResume(e -> {
log.warn("Error publishing message", e);
subscriberExceptions.add(e);
return Mono.empty();
})).subscribe();
// Wait for messages to be sent and processed
Wait.untilTrue(() -> messagesReceived.get() > 0).waitOrTimeout();
// Trigger the fault injection
Map<String, Object> params = new HashMap<>();
params.put("bdb_id", standalone.getBdbId());
Mono<Boolean> actionCompleted = faultClient.triggerActionAndWait(triggerAction, params, CHECK_INTERVAL, DELAY_AFTER,
DEFAULT_TIMEOUT);
StepVerifier.create(actionCompleted).expectNext(true).verifyComplete();
// Stop the publisher
publisherSubscription.dispose();
log.info("Messages sent: {}, messages received: {}", messagesSent.get(), messagesReceived.get());
log.info("Received messages: {}", receivedMessages);
assertThat(messagesReceived.get()).isGreaterThan(0);
assertThat(messagesReceived.get()).isLessThanOrEqualTo(messagesSent.get());
// Assert that the last received message has an ID equal to the number of sent messages minus one
assertThat(receivedMessages).isNotEmpty();
String lastMessage = receivedMessages.get(receivedMessages.size() - 1);
log.info("Last received message: {}, expected ID: {}", lastMessage, messagesSent.get() - 1);
log.info("Captured exceptions: {}", subscriberExceptions);
// Log and assert reconnection timing metrics using the tracker
tracker.logStats();
assertThat(tracker.hasReconnections()).isTrue();
assertThat(tracker.getStats().getAverageEventBusReconnectionTime())
.isLessThan(Duration.ofSeconds(expectedReconnectionDurationInSeconds));
assertThat(tracker.getStats().getAverageStateListenerReconnectionTime())
.isLessThan(Duration.ofSeconds(expectedReconnectionDurationInSeconds));
tracker.dispose();
pubSubConnection.close();
publisherConnection.close();
publisherClient.shutdown();
subscriberClient.shutdown();
}
}
| ReconnectionTimingTracker |
java | apache__flink | flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/TumbleWithSize.java | {
"start": 1255,
"end": 2029
} | class ____ {
/** The size of the window either as time or row-count interval. */
private final Expression size;
TumbleWithSize(Expression size) {
this.size = ApiExpressionUtils.unwrapFromApi(size);
}
/**
* Specifies the time attribute on which rows are grouped.
*
* <p>For streaming tables you can specify grouping by a event-time or processing-time
* attribute.
*
* <p>For batch tables you can specify grouping on a timestamp or long attribute.
*
* @param timeField time attribute for streaming and batch tables
* @return a tumbling window on event-time
*/
public TumbleWithSizeOnTime on(Expression timeField) {
return new TumbleWithSizeOnTime(timeField, size);
}
}
| TumbleWithSize |
java | apache__camel | components/camel-aws/camel-aws2-athena/src/test/java/org/apache/camel/component/aws2/athena/Athena2QueryHelperTest.java | {
"start": 1612,
"end": 11628
} | class ____ {
@Test
public void parameterDefaults() {
Athena2QueryHelper helper = defaultAthena2QueryHelper();
// configuration ======================
assertEquals(0, helper.getWaitTimeout());
assertEquals(2_000, helper.getDelay());
assertEquals(1, helper.getMaxAttempts());
assertEquals(new HashSet<>(Collections.singletonList("never")), helper.getRetry());
assertTrue(helper.isResetWaitTimeoutOnAttempt());
assertTrue(helper.getAbsoluteStartMs() <= System.currentTimeMillis());
// state ==============================
assertEquals(1_000, helper.getCurrentDelay());
assertEquals(0, helper.getAttempts());
assertFalse(helper.isFailure());
assertFalse(helper.isSuccess());
assertFalse(helper.isRetry());
assertEquals(0, helper.getStartMs());
assertFalse(helper.isInterrupted());
}
@Test
public void determineRetryWhenNotSet() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry(null);
assertEquals(new HashSet<>(Collections.singletonList("never")), helper.getRetry());
}
@Test
public void determineRetryWhenSetToNever() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("never");
assertEquals(new HashSet<>(Collections.singletonList("never")), helper.getRetry());
}
@Test
public void determineRetryWhenSetToAlways() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("always");
assertEquals(new HashSet<>(Collections.singletonList("always")), helper.getRetry());
}
@Test
public void determineRetryWhenSetToRetryable() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("retryable");
assertEquals(new HashSet<>(Collections.singletonList("retryable")), helper.getRetry());
}
@Test
public void determineRetryWhenSetToGeneric() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("generic");
assertEquals(new HashSet<>(Collections.singletonList("generic")), helper.getRetry());
}
@Test
public void determineRetryWhenSetToExhausted() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("exhausted");
assertEquals(new HashSet<>(Collections.singletonList("exhausted")), helper.getRetry());
}
@Test
public void determineRetryWhenSetToMultiple() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("exhausted,generic");
assertEquals(new HashSet<>(Arrays.asList("exhausted", "generic")), helper.getRetry());
}
@Test
public void determineRetryDoesNotAllowMutuallyExclusiveValues() {
assertThrows(IllegalArgumentException.class, () -> athena2QueryHelperWithRetry("always,never"));
}
@Test
public void determineRetryDoesNotAllowUnknownValues() {
assertThrows(IllegalArgumentException.class, () -> athena2QueryHelperWithRetry("foo"));
}
@Test
public void markAttemptIncrementsAttemptsAndResetsStatuses() {
Athena2QueryHelper helper = defaultAthena2QueryHelper();
assertEquals(0, helper.getAttempts());
assertFalse(helper.isSuccess());
helper.setStatusFrom(newGetQueryExecutionResponse(QueryExecutionState.SUCCEEDED));
assertTrue(helper.isSuccess());
helper.markAttempt();
assertFalse(helper.isSuccess());
assertEquals(1, helper.getAttempts());
}
@Test
public void testStartQueryExecutionHappyPath() {
Athena2Configuration configuration = new Athena2Configuration();
configuration.setMaxAttempts(3);
configuration.setWaitTimeout(2_000);
configuration.setInitialDelay(1);
configuration.setDelay(1);
Athena2QueryHelper helper = new Athena2QueryHelper(
new DefaultExchange(new DefaultCamelContext()),
configuration);
assertTrue(helper.shouldAttempt());
helper.markAttempt();
assertTrue(helper.shouldWait());
helper.doWait();
helper.setStatusFrom(newGetQueryExecutionResponse(QueryExecutionState.SUCCEEDED));
assertFalse(helper.shouldWait());
assertTrue(helper.isSuccess());
assertFalse(helper.isFailure());
assertFalse(helper.isRetry());
assertFalse(helper.isInterrupted());
assertFalse(helper.shouldAttempt());
}
@Test
public void isComplete() {
Athena2QueryHelper helper = defaultAthena2QueryHelper();
assertTrue(helper.isComplete(newGetQueryExecutionResponse(QueryExecutionState.SUCCEEDED)));
assertTrue(helper.isComplete(newGetQueryExecutionResponse(QueryExecutionState.FAILED)));
assertTrue(helper.isComplete(newGetQueryExecutionResponse(QueryExecutionState.CANCELLED)));
assertTrue(helper.isComplete(newGetQueryExecutionResponse(QueryExecutionState.UNKNOWN_TO_SDK_VERSION)));
assertFalse(helper.isComplete(newGetQueryExecutionResponse(QueryExecutionState.QUEUED)));
assertFalse(helper.isComplete(newGetQueryExecutionResponse(QueryExecutionState.RUNNING)));
}
@Test
public void wasSuccessful() {
Athena2QueryHelper helper = defaultAthena2QueryHelper();
assertTrue(helper.wasSuccessful(newGetQueryExecutionResponse(QueryExecutionState.SUCCEEDED)));
assertFalse(helper.wasSuccessful(newGetQueryExecutionResponse(QueryExecutionState.FAILED)));
assertFalse(helper.wasSuccessful(newGetQueryExecutionResponse(QueryExecutionState.CANCELLED)));
assertFalse(helper.wasSuccessful(newGetQueryExecutionResponse(QueryExecutionState.UNKNOWN_TO_SDK_VERSION)));
assertFalse(helper.wasSuccessful(newGetQueryExecutionResponse(QueryExecutionState.QUEUED)));
assertFalse(helper.wasSuccessful(newGetQueryExecutionResponse(QueryExecutionState.RUNNING)));
}
@Test
public void setStatusFromWhenQuerySucceeded() {
Athena2QueryHelper helper = defaultAthena2QueryHelper();
assertFalse(helper.isSuccess());
assertFalse(helper.isRetry());
assertFalse(helper.isFailure());
helper.setStatusFrom(newGetQueryExecutionResponse(QueryExecutionState.SUCCEEDED));
assertTrue(helper.isSuccess());
assertFalse(helper.isRetry());
assertFalse(helper.isFailure());
}
@Test
public void setStatusFromWhenQueryShouldRetry() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("always");
assertFalse(helper.isRetry());
assertFalse(helper.isRetry());
assertFalse(helper.isFailure());
helper.setStatusFrom(newGetQueryExecutionResponse(QueryExecutionState.CANCELLED));
assertFalse(helper.isSuccess());
assertTrue(helper.isRetry());
assertFalse(helper.isFailure());
}
@Test
public void setStatusFromWhenRetryIsNever() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("never");
assertFalse(helper.isRetry());
assertFalse(helper.isRetry());
assertFalse(helper.isFailure());
helper.setStatusFrom(newGetQueryExecutionResponse(QueryExecutionState.CANCELLED));
assertFalse(helper.isSuccess());
assertFalse(helper.isRetry());
assertTrue(helper.isFailure());
}
@Test
public void shouldRetryReturnsFalseWhenRetryIsNever() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("never");
assertFalse(helper.shouldRetry(newGetQueryExecutionResponse(QueryExecutionState.FAILED, "GENERIC_INTERNAL_ERROR")));
}
@Test
void shouldRetryReturnsTrueWhenRetryIsAlways() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("always");
assertTrue(helper.shouldRetry(newGetQueryExecutionResponse(QueryExecutionState.FAILED, null)));
}
@Test
public void shouldRetryReturnsTrueForGenericInternalError() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("retryable");
assertTrue(helper.shouldRetry(newGetQueryExecutionResponse(QueryExecutionState.FAILED, "GENERIC_INTERNAL_ERROR")));
}
@Test
public void shouldRetryReturnsTrueForExhaustedResourcedError() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("retryable");
assertTrue(helper.shouldRetry(
newGetQueryExecutionResponse(QueryExecutionState.FAILED, "exhausted resources at this scale factor")));
}
@Test
public void shouldRetryReturnsFalseForUnexpectedError() {
Athena2QueryHelper helper = athena2QueryHelperWithRetry("retryable");
assertFalse(helper.shouldRetry(newGetQueryExecutionResponse(QueryExecutionState.FAILED, "unexpected")));
}
private Athena2QueryHelper defaultAthena2QueryHelper() {
return new Athena2QueryHelper(
new DefaultExchange(new DefaultCamelContext()),
new Athena2Configuration());
}
private Athena2QueryHelper athena2QueryHelperWithRetry(String retry) {
Athena2Configuration configuration = new Athena2Configuration();
configuration.setRetry(retry);
return new Athena2QueryHelper(
new DefaultExchange(new DefaultCamelContext()),
configuration);
}
private GetQueryExecutionResponse newGetQueryExecutionResponse(QueryExecutionState queryExecutionState) {
return newGetQueryExecutionResponse(queryExecutionState, null);
}
private GetQueryExecutionResponse newGetQueryExecutionResponse(
QueryExecutionState queryExecutionState,
String stateChangeReason) {
return GetQueryExecutionResponse.builder()
.queryExecution(QueryExecution.builder()
.status(QueryExecutionStatus.builder()
.state(queryExecutionState)
.stateChangeReason(stateChangeReason)
.build())
.build())
.build();
}
}
| Athena2QueryHelperTest |
java | apache__camel | components/camel-twitter/src/test/java/org/apache/camel/component/twitter/DirectMessageProducerIT.java | {
"start": 1701,
"end": 3351
} | class ____ extends CamelTwitterITSupport {
private static final Logger LOG = LoggerFactory.getLogger(DirectMessageProducerIT.class);
@EndpointInject("mock:result")
protected MockEndpoint resultEndpoint;
@Test
public void testDirectMessage() throws Exception {
Date now = new Date();
String tweet = "Test a tweet posted on " + now.toString();
LOG.info("Tweet: {}", tweet);
ProducerTemplate producerTemplate = context.createProducerTemplate();
// send tweet to the twitter endpoint
producerTemplate.sendBody("direct:tweets", tweet);
resultEndpoint.expectedMessageCount(1);
resultEndpoint.expectedBodyReceived().body(String.class);
// Message headers should be preserved
resultEndpoint.assertIsSatisfied();
List<Exchange> tweets = resultEndpoint.getExchanges();
assertNotNull(tweets);
assertThat(tweets.size(), is(1));
String receivedTweet = tweets.get(0).getIn().getBody(String.class);
assertThat(receivedTweet, is(tweet));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:tweets")
//.to("log:org.apache.camel.component.twitter?level=INFO&showAll=true&multiline=true")
.to("twitter-directmessage:cameltweet?" + getUriTokens())
//.to("log:org.apache.camel.component.twitter?level=INFO&showAll=true&multiline=true")
.to("mock:result");
}
};
}
}
| DirectMessageProducerIT |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/requests/TxnOffsetCommitResponseTest.java | {
"start": 1174,
"end": 2972
} | class ____ extends OffsetCommitResponseTest {
@Test
@Override
public void testConstructorWithErrorResponse() {
TxnOffsetCommitResponse response = new TxnOffsetCommitResponse(throttleTimeMs, errorsMap);
assertEquals(errorsMap, response.errors());
assertEquals(expectedErrorCounts, response.errorCounts());
assertEquals(throttleTimeMs, response.throttleTimeMs());
}
@Test
@Override
public void testParse() {
TxnOffsetCommitResponseData data = new TxnOffsetCommitResponseData()
.setThrottleTimeMs(throttleTimeMs)
.setTopics(Arrays.asList(
new TxnOffsetCommitResponseData.TxnOffsetCommitResponseTopic().setPartitions(
Collections.singletonList(new TxnOffsetCommitResponseData.TxnOffsetCommitResponsePartition()
.setPartitionIndex(partitionOne)
.setErrorCode(errorOne.code()))),
new TxnOffsetCommitResponseData.TxnOffsetCommitResponseTopic().setPartitions(
Collections.singletonList(new TxnOffsetCommitResponseData.TxnOffsetCommitResponsePartition()
.setPartitionIndex(partitionTwo)
.setErrorCode(errorTwo.code())))
));
for (short version : ApiKeys.TXN_OFFSET_COMMIT.allVersions()) {
TxnOffsetCommitResponse response = TxnOffsetCommitResponse.parse(
MessageUtil.toByteBufferAccessor(data, version), version);
assertEquals(expectedErrorCounts, response.errorCounts());
assertEquals(throttleTimeMs, response.throttleTimeMs());
assertEquals(version >= 1, response.shouldClientThrottle(version));
}
}
}
| TxnOffsetCommitResponseTest |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/env/yaml/CustomSafeConstructor.java | {
"start": 1099,
"end": 1581
} | class ____ extends SafeConstructor {
CustomSafeConstructor() {
super(new LoaderOptions());
yamlConstructors.put(Tag.TIMESTAMP, new ConstructIsoTimestampString());
}
@Override
protected Map<Object, Object> newMap(MappingNode node) {
return createDefaultMap(node.getValue().size());
}
@Override
protected List<Object> newList(SequenceNode node) {
return createDefaultList(node.getValue().size());
}
}
| CustomSafeConstructor |
java | apache__camel | components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorReference.java | {
"start": 1976,
"end": 18335
} | class ____ {
private static final Logger LOGGER = LoggerFactory.getLogger(DisruptorReference.class);
private final Set<DisruptorEndpoint> endpoints = Collections
.newSetFromMap(new WeakHashMap<DisruptorEndpoint, Boolean>(4));
private final DisruptorComponent component;
private final String uri;
private final String name;
//The mark on the reference indicates if we are in the process of reconfiguring the Disruptor:
//(ref, mark) : Description
//(null, false) : not started or completely shut down
//(null, true) : in process of reconfiguring
//( x , false) : normally functioning Disruptor
//( x , true) : never set
private final AtomicMarkableReference<Disruptor<ExchangeEvent>> disruptor = new AtomicMarkableReference<>(null, false);
private final DelayedExecutor delayedExecutor = new DelayedExecutor();
private final DisruptorProducerType producerType;
private final int size;
private final DisruptorWaitStrategy waitStrategy;
private final Queue<Exchange> temporaryExchangeBuffer;
private final Lock lock = new ReentrantLock();
//access guarded by this
private ExecutorService executor;
private LifecycleAwareExchangeEventHandler[] handlers = new LifecycleAwareExchangeEventHandler[0];
private int uniqueConsumerCount;
DisruptorReference(final DisruptorComponent component, final String uri, final String name, final int size,
final DisruptorProducerType producerType, final DisruptorWaitStrategy waitStrategy) throws Exception {
this.component = component;
this.uri = uri;
this.name = name;
this.size = size;
this.producerType = producerType;
this.waitStrategy = waitStrategy;
temporaryExchangeBuffer = new ArrayBlockingQueue<>(size);
reconfigure();
}
public boolean hasNullReference() {
return disruptor.getReference() == null;
}
private Disruptor<ExchangeEvent> getCurrentDisruptor() throws DisruptorNotStartedException {
Disruptor<ExchangeEvent> currentDisruptor = disruptor.getReference();
if (currentDisruptor == null) {
// no current Disruptor reference, we may be reconfiguring or it was not started
// check which by looking at the reference mark...
boolean[] changeIsPending = new boolean[1];
while (currentDisruptor == null) {
currentDisruptor = disruptor.get(changeIsPending);
//Check if we are reconfiguring
if (currentDisruptor == null && !changeIsPending[0]) {
throw new DisruptorNotStartedException(
"Disruptor is not yet started or already shut down.");
} else if (currentDisruptor == null && changeIsPending[0]) {
//We should be back shortly...keep trying but spare CPU resources
LockSupport.parkNanos(1L);
}
}
}
return currentDisruptor;
}
public void tryPublish(final Exchange exchange) throws DisruptorNotStartedException, InsufficientCapacityException {
tryPublishExchangeOnRingBuffer(exchange, getCurrentDisruptor().getRingBuffer());
}
public void publish(final Exchange exchange) throws DisruptorNotStartedException {
publishExchangeOnRingBuffer(exchange, getCurrentDisruptor().getRingBuffer());
}
private void publishExchangeOnRingBuffer(
final Exchange exchange,
final RingBuffer<ExchangeEvent> ringBuffer) {
final long sequence = ringBuffer.next();
ringBuffer.get(sequence).setExchange(exchange, uniqueConsumerCount);
ringBuffer.publish(sequence);
}
private void tryPublishExchangeOnRingBuffer(final Exchange exchange, final RingBuffer<ExchangeEvent> ringBuffer)
throws InsufficientCapacityException {
final long sequence = ringBuffer.tryNext();
ringBuffer.get(sequence).setExchange(exchange, uniqueConsumerCount);
ringBuffer.publish(sequence);
}
public void reconfigure() throws Exception {
lock.lock();
try {
LOGGER.debug("Reconfiguring disruptor {}", this);
shutdownDisruptor(true);
start();
} finally {
lock.unlock();
}
}
private void start() throws Exception {
LOGGER.debug("Starting disruptor {}", this);
Disruptor<ExchangeEvent> newDisruptor = createDisruptor();
newDisruptor.start();
if (executor != null) {
//and use our delayed executor to really really execute the event handlers now
delayedExecutor.executeDelayedCommands(executor);
}
//make sure all event handlers are correctly started before we continue
for (final LifecycleAwareExchangeEventHandler handler : handlers) {
boolean eventHandlerStarted = false;
while (!eventHandlerStarted) {
try {
//The disruptor start command executed above should have triggered a start signal to all
//event processors which, in their death, should notify our event handlers. They respond by
//switching a latch and we want to await that latch here to make sure they are started.
if (!handler.awaitStarted(10, TimeUnit.SECONDS)) {
//we wait for a relatively long, but limited amount of time to prevent an application using
//this component from hanging indefinitely
//Please report a bug if you can reproduce this
LOGGER.error("Disruptor/event handler failed to start properly, PLEASE REPORT");
}
eventHandlerStarted = true;
} catch (InterruptedException e) {
LOGGER.info("Interrupted while waiting for the startup to complete");
Thread.currentThread().interrupt();
}
}
}
publishBufferedExchanges(newDisruptor);
disruptor.set(newDisruptor, false);
}
private Disruptor<ExchangeEvent> createDisruptor() throws Exception {
//create a new Disruptor
final Disruptor<ExchangeEvent> newDisruptor = new Disruptor<>(
ExchangeEventFactory.INSTANCE, size, delayedExecutor, producerType.getProducerType(),
waitStrategy.createWaitStrategyInstance());
//determine the list of eventhandlers to be associated to the Disruptor
final ArrayList<LifecycleAwareExchangeEventHandler> eventHandlers = new ArrayList<>();
uniqueConsumerCount = 0;
for (final DisruptorEndpoint endpoint : endpoints) {
final Map<DisruptorConsumer, Collection<LifecycleAwareExchangeEventHandler>> consumerEventHandlers
= endpoint.createConsumerEventHandlers();
if (consumerEventHandlers != null) {
uniqueConsumerCount += consumerEventHandlers.keySet().size();
for (Collection<LifecycleAwareExchangeEventHandler> lifecycleAwareExchangeEventHandlers : consumerEventHandlers
.values()) {
eventHandlers.addAll(lifecycleAwareExchangeEventHandlers);
}
}
}
LOGGER.debug("Disruptor created with {} event handlers", eventHandlers.size());
handleEventsWith(newDisruptor,
eventHandlers.toArray(new LifecycleAwareExchangeEventHandler[0]));
return newDisruptor;
}
private void handleEventsWith(
Disruptor<ExchangeEvent> newDisruptor,
final LifecycleAwareExchangeEventHandler[] newHandlers) {
if (newHandlers == null || newHandlers.length == 0) {
handlers = new LifecycleAwareExchangeEventHandler[1];
handlers[0] = new BlockingExchangeEventHandler();
} else {
handlers = newHandlers;
}
resizeThreadPoolExecutor(handlers.length);
newDisruptor.handleEventsWith(handlers);
}
private void publishBufferedExchanges(Disruptor<ExchangeEvent> newDisruptor) {
//now empty out all buffered Exchange if we had any
final List<Exchange> exchanges = new ArrayList<>(temporaryExchangeBuffer.size());
while (!temporaryExchangeBuffer.isEmpty()) {
exchanges.add(temporaryExchangeBuffer.remove());
}
RingBuffer<ExchangeEvent> ringBuffer = newDisruptor.getRingBuffer();
//and offer them again to our new ringbuffer
for (final Exchange exchange : exchanges) {
publishExchangeOnRingBuffer(exchange, ringBuffer);
}
}
private void resizeThreadPoolExecutor(final int newSize) {
if (executor == null && newSize > 0) {
LOGGER.debug("Creating new executor with {} threads", newSize);
//no thread pool executor yet, create a new one
executor = component.getCamelContext().getExecutorServiceManager().newFixedThreadPool(this, uri,
newSize);
} else if (executor != null && newSize <= 0) {
LOGGER.debug("Shutting down executor");
//we need to shut down our executor
component.getCamelContext().getExecutorServiceManager().shutdown(executor);
executor = null;
} else if (executor instanceof ThreadPoolExecutor threadPoolExecutor) {
LOGGER.debug("Resizing existing executor to {} threads", newSize);
//our thread pool executor is of type ThreadPoolExecutor, we know how to resize it
//Java 9 support, checkout http://download.java.net/java/jdk9/docs/api/java/util/concurrent/ThreadPoolExecutor.html#setCorePoolSize-int-
// and http://download.java.net/java/jdk9/docs/api/java/util/concurrent/ThreadPoolExecutor.html#setMaximumPoolSize-int-
//for more information
if (newSize <= threadPoolExecutor.getCorePoolSize()) {
threadPoolExecutor.setCorePoolSize(newSize);
threadPoolExecutor.setMaximumPoolSize(newSize);
} else {
threadPoolExecutor.setMaximumPoolSize(newSize);
threadPoolExecutor.setCorePoolSize(newSize);
}
} else if (newSize > 0) {
LOGGER.debug("Shutting down old and creating new executor with {} threads", newSize);
//hmmm...no idea what kind of executor this is...just kill it and start fresh
component.getCamelContext().getExecutorServiceManager().shutdown(executor);
executor = component.getCamelContext().getExecutorServiceManager().newFixedThreadPool(this, uri,
newSize);
}
}
private void shutdownDisruptor(boolean isReconfiguring) {
lock.lock();
try {
LOGGER.debug("Shutting down disruptor {}, reconfiguring: {}", this, isReconfiguring);
Disruptor<ExchangeEvent> currentDisruptor = disruptor.getReference();
disruptor.set(null, isReconfiguring);
if (currentDisruptor != null) {
//check if we had a blocking event handler to keep an empty disruptor 'busy'
if (handlers != null && handlers.length == 1
&& handlers[0] instanceof BlockingExchangeEventHandler blockingExchangeEventHandler) {
// yes we did, unblock it so we can get rid of our backlog,
// The eventhandler will empty its pending exchanges in our temporary buffer
blockingExchangeEventHandler.unblock();
}
currentDisruptor.shutdown();
//they have already been given a trigger to halt when they are done by shutting down the disruptor
//we do however want to await their completion before they are scheduled to process events from the new
for (final LifecycleAwareExchangeEventHandler eventHandler : handlers) {
boolean eventHandlerFinished = false;
//the disruptor is now empty and all consumers are either done or busy processing their last exchange
while (!eventHandlerFinished) {
try {
//The disruptor shutdown command executed above should have triggered a halt signal to all
//event processors which, in their death, should notify our event handlers. They respond by
//switching a latch and we want to await that latch here to make sure they are done.
if (!eventHandler.awaitStopped(10, TimeUnit.SECONDS)) {
//we wait for a relatively long, but limited amount of time to prevent an application using
//this component from hanging indefinitely
//Please report a bug if you can repruduce this
LOGGER.error("Disruptor/event handler failed to shut down properly, PLEASE REPORT");
}
eventHandlerFinished = true;
} catch (InterruptedException e) {
LOGGER.info("Interrupted while waiting for the shutdown to complete");
Thread.currentThread().interrupt();
}
}
}
handlers = new LifecycleAwareExchangeEventHandler[0];
}
} finally {
lock.unlock();
}
}
private void shutdownExecutor() {
lock.lock();
try {
resizeThreadPoolExecutor(0);
} finally {
lock.unlock();
}
}
public String getName() {
return name;
}
public long getRemainingCapacity() throws DisruptorNotStartedException {
return getCurrentDisruptor().getRingBuffer().remainingCapacity();
}
public DisruptorWaitStrategy getWaitStrategy() {
return waitStrategy;
}
DisruptorProducerType getProducerType() {
return producerType;
}
public int getBufferSize() {
return size;
}
public int getPendingExchangeCount() {
try {
if (!hasNullReference()) {
return (int) (getBufferSize() - getRemainingCapacity() + temporaryExchangeBuffer.size());
}
} catch (DisruptorNotStartedException e) {
//fall through...
}
return temporaryExchangeBuffer.size();
}
public void addEndpoint(final DisruptorEndpoint disruptorEndpoint) {
lock.lock();
try {
LOGGER.debug("Adding Endpoint: {}", disruptorEndpoint);
endpoints.add(disruptorEndpoint);
LOGGER.debug("Endpoint added: {}, new total endpoints {}", disruptorEndpoint, endpoints.size());
} finally {
lock.unlock();
}
}
public void removeEndpoint(final DisruptorEndpoint disruptorEndpoint) {
lock.lock();
try {
LOGGER.debug("Removing Endpoint: {}", disruptorEndpoint);
if (getEndpointCount() == 1) {
LOGGER.debug("Last Endpoint removed, shutdown disruptor");
//Shutdown our disruptor
shutdownDisruptor(false);
//As there are no endpoints dependent on this Disruptor, we may also shutdown our executor
shutdownExecutor();
}
endpoints.remove(disruptorEndpoint);
LOGGER.debug("Endpoint removed: {}, new total endpoints {}", disruptorEndpoint, getEndpointCount());
} finally {
lock.unlock();
}
}
public int getEndpointCount() {
lock.lock();
try {
return endpoints.size();
} finally {
lock.unlock();
}
}
@Override
public String toString() {
return "DisruptorReference{" + "uri='" + uri + '\'' + ", endpoint count=" + endpoints.size()
+ ", handler count=" + handlers.length + '}';
}
/**
* Implementation of the {@link LifecycleAwareExchangeEventHandler} | DisruptorReference |
java | alibaba__nacos | client/src/test/java/com/alibaba/nacos/client/redo/service/AbstractRedoServiceTest.java | {
"start": 1581,
"end": 6332
} | class ____ {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRedoServiceTest.class);
@Mock
private AbstractRedoTask redoTask;
MockRedoService redoService;
@BeforeEach
void setUp() {
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.REDO_DELAY_TIME, "300");
NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties);
redoService = new MockRedoService(LOGGER, clientProperties);
redoService.startRedoTask();
}
@AfterEach
void tearDown() {
redoService.shutdown();
}
@Test
void testRemoveForNonExistedData() {
assertDoesNotThrow(() -> redoService.removeRedoData("test", String.class));
}
@Test
void testMarkRegisteredForNonExistedData() {
assertDoesNotThrow(() -> redoService.dataRegistered("test", String.class));
}
@Test
void testMarkUnregisterForNonExistedData() {
assertDoesNotThrow(() -> redoService.dataDeregister("test", String.class));
}
@Test
void testMarkUnregisteredForNonExistedData() {
assertDoesNotThrow(() -> redoService.dataDeregistered("test", String.class));
}
@Test
void testIsDataRegisteredForNonExistedData() {
assertFalse(redoService.isDataRegistered("test", String.class));
}
@Test
void testGetNonExistedData() {
assertNull(redoService.getRedoData("test", String.class));
}
@Test
void testFindNonExistedData() {
assertTrue(redoService.findRedoData(String.class).isEmpty());
}
@Test
void testCacheRedoDataAndMarkRegistered() {
MockRedoData redoData = new MockRedoData();
redoData.set("test");
redoService.cachedRedoData("test", redoData, String.class);
RedoData<String> redoData1 = redoService.getRedoData("test", String.class);
assertEquals(redoData, redoData1);
assertFalse(redoData1.isRegistered());
assertTrue(redoData1.isNeedRedo());
assertFalse(redoData1.isUnregistering());
assertFalse(redoService.isDataRegistered("test", String.class));
redoService.dataRegistered("test", String.class);
assertTrue(redoData1.isRegistered());
assertFalse(redoData1.isNeedRedo());
assertFalse(redoData1.isUnregistering());
assertTrue(redoService.isDataRegistered("test", String.class));
redoService.dataDeregister("test", String.class);
assertTrue(redoData1.isRegistered());
assertTrue(redoData1.isUnregistering());
assertTrue(redoService.isDataRegistered("test", String.class));
redoService.dataDeregistered("test", String.class);
assertFalse(redoData1.isRegistered());
assertTrue(redoData1.isUnregistering());
assertFalse(redoService.isDataRegistered("test", String.class));
redoService.removeRedoData("test", String.class);
assertNull(redoService.getRedoData("test", String.class));
}
@Test
void testRemoveExpectedRegisteredData() {
MockRedoData redoData = new MockRedoData();
redoData.set("test");
redoService.cachedRedoData("test", redoData, String.class);
redoData.setExpectedRegistered(true);
redoService.removeRedoData("test", String.class);
assertNotNull(redoService.getRedoData("test", String.class));
}
@Test
void testOnConnectedAndOnDisconnected() {
assertFalse(redoService.isConnected());
redoService.onConnected(null);
assertTrue(redoService.isConnected());
MockRedoData redoData = new MockRedoData();
redoData.set("test");
redoData.setRegistered(true);
redoService.cachedRedoData("test", redoData, String.class);
redoService.onDisConnect(null);
assertFalse(redoService.isConnected());
assertFalse(redoData.isRegistered());
}
@Test
void testFindAllNeedRedoData() {
MockRedoData noNeedRedoData = new MockRedoData();
noNeedRedoData.setRegistered(true);
noNeedRedoData.setExpectedRegistered(true);
MockRedoData needRedoData = new MockRedoData();
needRedoData.setRegistered(false);
needRedoData.setExpectedRegistered(true);
redoService.cachedRedoData("noNeedRedoData", noNeedRedoData, String.class);
redoService.cachedRedoData("needRedoData", needRedoData, String.class);
Set<RedoData<String>> redoDataSet = redoService.findRedoData(String.class);
assertEquals(1, redoDataSet.size());
assertEquals(needRedoData, redoDataSet.iterator().next());
}
private | AbstractRedoServiceTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/type/descriptor/java/spi/FormatMapperBasedJavaType.java | {
"start": 913,
"end": 3549
} | class ____<T> extends AbstractJavaType<T> implements MutabilityPlan<T> {
private final TypeConfiguration typeConfiguration;
public FormatMapperBasedJavaType(
Type type,
MutabilityPlan<T> mutabilityPlan,
TypeConfiguration typeConfiguration) {
super( type, mutabilityPlan );
this.typeConfiguration = typeConfiguration;
}
protected abstract FormatMapper getFormatMapper(TypeConfiguration typeConfiguration);
@Override
public JdbcType getRecommendedJdbcType(JdbcTypeIndicators context) {
throw new JdbcTypeRecommendationException(
"Could not determine recommended JdbcType for Java type '" + getTypeName() + "'"
);
}
private WrapperOptions getWrapperOptions() {
return typeConfiguration.getSessionFactory().getWrapperOptions();
}
@Override
public String toString(T value) {
return getFormatMapper( typeConfiguration )
.toString( value, this, getWrapperOptions() );
}
@Override
public T fromString(CharSequence string) {
return getFormatMapper( typeConfiguration )
.fromString( string, this, getWrapperOptions() );
}
@Override
public <X> X unwrap(T value, Class<X> type, WrapperOptions options) {
if ( type.isAssignableFrom( getJavaTypeClass() ) ) {
//noinspection unchecked
return (X) value;
}
else if ( type == String.class ) {
//noinspection unchecked
return (X) getFormatMapper( typeConfiguration )
.toString( value, this, options );
}
throw new UnsupportedOperationException(
"Unwrap strategy not known for this Java type: " + getTypeName()
);
}
@Override
public <X> T wrap(X value, WrapperOptions options) {
if ( getJavaTypeClass().isInstance( value ) ) {
//noinspection unchecked
return (T) value;
}
else if ( value instanceof String string ) {
return getFormatMapper( typeConfiguration )
.fromString( string, this, options );
}
throw new UnsupportedOperationException(
"Wrap strategy not known for this Java type: " + getTypeName()
);
}
@Override
public MutabilityPlan<T> getMutabilityPlan() {
final var mutabilityPlan = super.getMutabilityPlan();
return mutabilityPlan == null ? this : mutabilityPlan;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public T deepCopy(T value) {
return value == null ? null : fromString( toString( value ) );
}
@Override
public Serializable disassemble(T value, SharedSessionContract session) {
return value == null ? null : toString( value );
}
@Override
public T assemble(Serializable cached, SharedSessionContract session) {
return cached == null ? null : fromString( (CharSequence) cached );
}
}
| FormatMapperBasedJavaType |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpSecurityRequestMatchersTests.java | {
"start": 13004,
"end": 13713
} | class ____ {
@Bean
PathPatternRequestMatcherBuilderFactoryBean requestMatcherBuilder() {
return new PathPatternRequestMatcherBuilderFactoryBean();
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http, PathPatternRequestMatcher.Builder builder) throws Exception {
// @formatter:off
http
.securityMatchers((secure) -> secure
.requestMatchers(builder.basePath("/spring").matcher("/path"))
.requestMatchers("/never-match")
)
.httpBasic(withDefaults())
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().denyAll()
);
return http.build();
// @formatter:on
}
@RestController
static | RequestMatchersMvcMatcherServletPathInLambdaConfig |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/plugins/ModuleSupport.java | {
"start": 1428,
"end": 5649
} | class ____ {
private ModuleSupport() {
throw new AssertionError("Utility class, should not be instantiated");
}
static ModuleFinder ofSyntheticPluginModule(
String name,
Path[] jarPaths,
Set<String> requires,
Set<String> uses,
Predicate<String> isPackageInParentLayers
) {
try {
return new InMemoryModuleFinder(
new InMemoryModuleReference(
createModuleDescriptor(name, jarPaths, requires, uses, isPackageInParentLayers),
URI.create("module:/" + name)
)
);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@SuppressForbidden(reason = "need access to the jar file")
static ModuleDescriptor createModuleDescriptor(
String name,
Path[] jarPaths,
Set<String> requires,
Set<String> uses,
Predicate<String> isPackageInParentLayers
) throws IOException {
var builder = ModuleDescriptor.newOpenModule(name); // open module, for now
requires.forEach(builder::requires);
uses.forEach(builder::uses);
// scan the names of the entries in the JARs
Set<String> pkgs = new HashSet<>();
Map<String, List<String>> allBundledProviders = new HashMap<>();
Set<String> servicesUsedInBundle = new HashSet<>();
for (Path path : jarPaths) {
assert path.getFileName().toString().endsWith(".jar") : "expected jars suffix, in path: " + path;
try (JarFile jf = new JarFile(path.toFile(), true, ZipFile.OPEN_READ, Runtime.version())) {
// if we have a module declaration, trust its uses/provides
JarEntry moduleInfo = jf.getJarEntry("module-info.class");
if (moduleInfo != null) {
var descriptor = getDescriptorForModularJar(path);
pkgs.addAll(descriptor.packages());
servicesUsedInBundle.addAll(descriptor.uses());
for (ModuleDescriptor.Provides p : descriptor.provides()) {
String serviceName = p.service();
List<String> providersInModule = p.providers();
allBundledProviders.compute(serviceName, (k, v) -> createListOrAppend(v, providersInModule));
servicesUsedInBundle.add(serviceName);
}
} else {
var scan = scan(jf);
scan.classFiles().stream().map(cf -> toPackageName(cf, "/")).flatMap(Optional::stream).forEach(pkgs::add);
// read providers from the list of service files
for (String serviceFileName : scan.serviceFiles()) {
String serviceName = getServiceName(serviceFileName);
List<String> providersInJar = getProvidersFromServiceFile(jf, serviceFileName);
allBundledProviders.compute(serviceName, (k, v) -> createListOrAppend(v, providersInJar));
servicesUsedInBundle.add(serviceName);
}
}
}
}
builder.packages(pkgs);
// we don't want to add any services we already got from the parent layer
servicesUsedInBundle.removeAll(uses);
// Services that aren't exported in the parent layer or defined in our
// bundle. This can happen for optional (compile-time) dependencies
Set<String> missingServices = servicesUsedInBundle.stream()
.filter(s -> isPackageInParentLayers.test(toPackageName(s, ".").orElseThrow()) == false)
.filter(s -> pkgs.contains(toPackageName(s, ".").orElseThrow()) == false)
.collect(Collectors.toSet());
servicesUsedInBundle.stream().filter(s -> missingServices.contains(s) == false).forEach(builder::uses);
allBundledProviders.entrySet()
.stream()
.filter(e -> missingServices.contains(e.getKey()) == false)
.forEach(e -> builder.provides(e.getKey(), e.getValue()));
return builder.build();
}
static | ModuleSupport |
java | google__guava | android/guava/src/com/google/common/collect/RangeSet.java | {
"start": 2294,
"end": 9993
} | interface ____<C extends Comparable> {
// Query methods
/** Determines whether any of this range set's member ranges contains {@code value}. */
boolean contains(C value);
/**
* Returns the unique range from this range set that {@linkplain Range#contains contains} {@code
* value}, or {@code null} if this range set does not contain {@code value}.
*/
@Nullable Range<C> rangeContaining(C value);
/**
* Returns {@code true} if there exists a non-empty range enclosed by both a member range in this
* range set and the specified range. This is equivalent to calling {@code
* subRangeSet(otherRange)} and testing whether the resulting range set is non-empty.
*
* @since 20.0
*/
boolean intersects(Range<C> otherRange);
/**
* Returns {@code true} if there exists a member range in this range set which {@linkplain
* Range#encloses encloses} the specified range.
*/
boolean encloses(Range<C> otherRange);
/**
* Returns {@code true} if for each member range in {@code other} there exists a member range in
* this range set which {@linkplain Range#encloses encloses} it. It follows that {@code
* this.contains(value)} whenever {@code other.contains(value)}. Returns {@code true} if {@code
* other} is empty.
*
* <p>This is equivalent to checking if this range set {@link #encloses} each of the ranges in
* {@code other}.
*/
boolean enclosesAll(RangeSet<C> other);
/**
* Returns {@code true} if for each range in {@code other} there exists a member range in this
* range set which {@linkplain Range#encloses encloses} it. Returns {@code true} if {@code other}
* is empty.
*
* <p>This is equivalent to checking if this range set {@link #encloses} each range in {@code
* other}.
*
* @since 21.0
*/
boolean enclosesAll(Iterable<Range<C>> other);
/** Returns {@code true} if this range set contains no ranges. */
boolean isEmpty();
/**
* Returns the minimal range which {@linkplain Range#encloses(Range) encloses} all ranges in this
* range set.
*
* @throws NoSuchElementException if this range set is {@linkplain #isEmpty() empty}
*/
Range<C> span();
// Views
/**
* Returns a view of the {@linkplain Range#isConnected disconnected} ranges that make up this
* range set. The returned set may be empty. The iterators returned by its {@link
* Iterable#iterator} method return the ranges in increasing order of lower bound (equivalently,
* of upper bound).
*/
Set<Range<C>> asRanges();
/**
* Returns a descending view of the {@linkplain Range#isConnected disconnected} ranges that make
* up this range set. The returned set may be empty. The iterators returned by its {@link
* Iterable#iterator} method return the ranges in decreasing order of lower bound (equivalently,
* of upper bound).
*
* @since 19.0
*/
Set<Range<C>> asDescendingSetOfRanges();
/**
* Returns a view of the complement of this {@code RangeSet}.
*
* <p>The returned view supports the {@link #add} operation if this {@code RangeSet} supports
* {@link #remove}, and vice versa.
*/
RangeSet<C> complement();
/**
* Returns a view of the intersection of this {@code RangeSet} with the specified range.
*
* <p>The returned view supports all optional operations supported by this {@code RangeSet}, with
* the caveat that an {@link IllegalArgumentException} is thrown on an attempt to {@linkplain
* #add(Range) add} any range not {@linkplain Range#encloses(Range) enclosed} by {@code view}.
*/
RangeSet<C> subRangeSet(Range<C> view);
// Modification
/**
* Adds the specified range to this {@code RangeSet} (optional operation). That is, for equal
* range sets a and b, the result of {@code a.add(range)} is that {@code a} will be the minimal
* range set for which both {@code a.enclosesAll(b)} and {@code a.encloses(range)}.
*
* <p>Note that {@code range} will be {@linkplain Range#span(Range) coalesced} with any ranges in
* the range set that are {@linkplain Range#isConnected(Range) connected} with it. Moreover, if
* {@code range} is empty, this is a no-op.
*
* @throws UnsupportedOperationException if this range set does not support the {@code add}
* operation
*/
void add(Range<C> range);
/**
* Removes the specified range from this {@code RangeSet} (optional operation). After this
* operation, if {@code range.contains(c)}, {@code this.contains(c)} will return {@code false}.
*
* <p>If {@code range} is empty, this is a no-op.
*
* @throws UnsupportedOperationException if this range set does not support the {@code remove}
* operation
*/
void remove(Range<C> range);
/**
* Removes all ranges from this {@code RangeSet} (optional operation). After this operation,
* {@code this.contains(c)} will return false for all {@code c}.
*
* <p>This is equivalent to {@code remove(Range.all())}.
*
* @throws UnsupportedOperationException if this range set does not support the {@code clear}
* operation
*/
void clear();
/**
* Adds all of the ranges from the specified range set to this range set (optional operation).
* After this operation, this range set is the minimal range set that {@linkplain
* #enclosesAll(RangeSet) encloses} both the original range set and {@code other}.
*
* <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code addAll}
* operation
*/
void addAll(RangeSet<C> other);
/**
* Adds all of the specified ranges to this range set (optional operation). After this operation,
* this range set is the minimal range set that {@linkplain #enclosesAll(RangeSet) encloses} both
* the original range set and each range in {@code other}.
*
* <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code addAll}
* operation
* @since 21.0
*/
void addAll(Iterable<Range<C>> ranges);
/**
* Removes all of the ranges from the specified range set from this range set (optional
* operation). After this operation, if {@code other.contains(c)}, {@code this.contains(c)} will
* return {@code false}.
*
* <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in
* turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code removeAll}
* operation
*/
void removeAll(RangeSet<C> other);
/**
* Removes all of the specified ranges from this range set (optional operation).
*
* <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in
* turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code removeAll}
* operation
* @since 21.0
*/
void removeAll(Iterable<Range<C>> ranges);
// Object methods
/**
* Returns {@code true} if {@code obj} is another {@code RangeSet} that contains the same ranges
* according to {@link Range#equals(Object)}.
*/
@Override
boolean equals(@Nullable Object obj);
/** Returns {@code asRanges().hashCode()}. */
@Override
int hashCode();
/**
* Returns a readable string representation of this range set. For example, if this {@code
* RangeSet} consisted of {@code Range.closed(1, 3)} and {@code Range.greaterThan(4)}, this might
* return {@code " [1..3](4..+∞)}"}.
*/
@Override
String toString();
}
| RangeSet |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/IterableDiff_Test.java | {
"start": 6541,
"end": 7105
} | class ____ {
private final int id;
private final String name;
private final String secondName;
private final String street;
private final String postCode;
public AddressDto(int id, String name, String secondName, String street, String postCode) {
this.id = id;
this.name = name;
this.secondName = secondName;
this.street = street;
this.postCode = postCode;
}
static AddressDto from(Address le) {
return new AddressDto(le.id, le.name, le.secondName, le.street, le.postCode);
}
}
}
| AddressDto |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/url/UrlOnStringParameterTest.java | {
"start": 1484,
"end": 1621
} | interface ____ {
@Path("count")
@GET
String test(@Url String uri);
}
@Path("test")
public static | Client |
java | spring-projects__spring-security | saml2/saml2-service-provider/src/opensaml5Main/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml5AuthenticationProvider.java | {
"start": 19170,
"end": 19841
} | class ____ {
private final Saml2AuthenticationToken token;
private final Response response;
ResponseToken(Response response, Saml2AuthenticationToken token) {
this.token = token;
this.response = response;
}
ResponseToken(BaseOpenSamlAuthenticationProvider.ResponseToken token) {
this.token = token.getToken();
this.response = token.getResponse();
}
public Response getResponse() {
return this.response;
}
public Saml2AuthenticationToken getToken() {
return this.token;
}
}
/**
* A tuple containing an OpenSAML {@link Assertion} and its associated authentication
* token.
*
* @since 5.4
*/
public static | ResponseToken |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/bigquery/ast/BigQuerySelectQueryBlock.java | {
"start": 1543,
"end": 3328
} | class ____
extends SQLObjectImpl implements BigQueryObject {
private final List<SQLAssignItem> options = new ArrayList<>();
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
DifferentialPrivacy that = (DifferentialPrivacy) object;
return options.equals(that.options);
}
public List<SQLAssignItem> getOptions() {
return options;
}
@Override
public int hashCode() {
return Objects.hash(options);
}
@Override
public void accept0(SQLASTVisitor v) {
if (v instanceof BigQueryVisitor) {
accept0((BigQueryVisitor) v);
}
}
@Override
public void accept0(BigQueryVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, options);
}
visitor.endVisit(this);
}
@Override
public DifferentialPrivacy clone() {
DifferentialPrivacy x = new DifferentialPrivacy();
for (SQLAssignItem option : options) {
SQLAssignItem cloned = option.clone();
x.options.add(cloned);
}
return x;
}
}
public BigQuerySelectQueryBlock clone() {
BigQuerySelectQueryBlock x = new BigQuerySelectQueryBlock();
cloneTo(x);
x.asStruct = this.asStruct;
if (differentialPrivacy != null) {
x.differentialPrivacy = this.differentialPrivacy.clone();
}
return x;
}
}
| DifferentialPrivacy |
java | spring-projects__spring-security | ldap/src/main/java/org/springframework/security/ldap/authentication/SpringSecurityAuthenticationSource.java | {
"start": 1558,
"end": 3636
} | class ____ implements AuthenticationSource {
private static final Log log = LogFactory.getLog(SpringSecurityAuthenticationSource.class);
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
/**
* Get the principals of the logged in user, in this case the distinguished name.
* @return the distinguished name of the logged in user.
*/
@Override
public String getPrincipal() {
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
if (authentication == null) {
log.debug("Returning empty String as Principal since authentication is null");
return "";
}
Object principal = authentication.getPrincipal();
if (principal instanceof LdapUserDetails details) {
return details.getDn();
}
if (authentication instanceof AnonymousAuthenticationToken) {
log.debug("Returning empty String as Principal since authentication is anonymous");
return "";
}
throw new IllegalArgumentException(
"The principal property of the authentication object" + "needs to be an LdapUserDetails.");
}
/**
* @see org.springframework.ldap.core.AuthenticationSource#getCredentials()
*/
@Override
public String getCredentials() {
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
if (authentication == null) {
log.debug("Returning empty String as Credentials since authentication is null");
return "";
}
return (String) authentication.getCredentials();
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
}
| SpringSecurityAuthenticationSource |
java | apache__camel | core/camel-base/src/main/java/org/apache/camel/impl/event/ExchangeAsyncProcessingStartedEvent.java | {
"start": 1416,
"end": 1836
} | class ____ extends AbstractExchangeEvent
implements CamelEvent.ExchangeAsyncProcessingStartedEvent {
private static final @Serial long serialVersionUID = -19248832613958122L;
public ExchangeAsyncProcessingStartedEvent(Exchange source) {
super(source);
}
@Override
public final String toString() {
return getExchange().getExchangeId();
}
}
| ExchangeAsyncProcessingStartedEvent |
java | quarkusio__quarkus | independent-projects/arc/runtime/src/test/java/io/quarkus/arc/impl/InMemoryLogHandler.java | {
"start": 213,
"end": 782
} | class ____ extends Handler {
final List<LogRecord> records = new CopyOnWriteArrayList<>();
@Override
public void publish(LogRecord record) {
records.add(record);
}
@Override
public void flush() {
}
@Override
public Level getLevel() {
return Level.FINE;
}
@Override
public void close() throws SecurityException {
this.records.clear();
}
public List<LogRecord> getRecords() {
return records;
}
void clearRecords() {
this.records.clear();
}
}
| InMemoryLogHandler |
java | dropwizard__dropwizard | dropwizard-configuration/src/main/java/io/dropwizard/configuration/ConfigurationFactory.java | {
"start": 233,
"end": 1733
} | interface ____<T> {
/**
* Loads, parses, binds, and validates a configuration object.
*
* @param provider the provider to use for reading configuration files
* @param path the path of the configuration file
* @return a validated configuration object
* @throws IOException if there is an error reading the file
* @throws ConfigurationException if there is an error parsing or validating the file
*/
T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException;
/**
* Loads, parses, binds, and validates a configuration object from a file.
*
* @param file the path of the configuration file
* @return a validated configuration object
* @throws IOException if there is an error reading the file
* @throws ConfigurationException if there is an error parsing or validating the file
*/
default T build(File file) throws IOException, ConfigurationException {
return build(new FileConfigurationSourceProvider(), file.toString());
}
/**
* Loads, parses, binds, and validates a configuration object from an empty document.
*
* @return a validated configuration object
* @throws IOException if there is an error reading the file
* @throws ConfigurationException if there is an error parsing or validating the file
*/
T build() throws IOException, ConfigurationException;
}
| ConfigurationFactory |
java | quarkusio__quarkus | extensions/jackson/deployment/src/test/java/io/quarkus/jackson/deployment/JacksonMixinsWithoutCustomizerTest.java | {
"start": 1314,
"end": 1398
} | class ____ {
@JsonProperty("nm")
public String name;
}
}
| FruitMixin |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/annotations/SelectKey.java | {
"start": 2941,
"end": 2990
} | interface ____ {
SelectKey[] value();
}
}
| List |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/nativeio/NativeIO.java | {
"start": 22466,
"end": 22932
} | class ____ {
final long timestamp;
final String name;
public CachedName(String name, long timestamp) {
this.name = name;
this.timestamp = timestamp;
}
}
private static final Map<Integer, CachedName> USER_ID_NAME_CACHE =
new ConcurrentHashMap<Integer, CachedName>();
private static final Map<Integer, CachedName> GROUP_ID_NAME_CACHE =
new ConcurrentHashMap<Integer, CachedName>();
private | CachedName |
java | quarkusio__quarkus | extensions/funqy/funqy-amazon-lambda/runtime/src/main/java/io/quarkus/funqy/lambda/config/AdvancedEventHandlingConfig.java | {
"start": 162,
"end": 467
} | interface ____ {
/**
* Sqs related config.
*/
Sqs sqs();
/**
* Sns related config.
*/
Sns sns();
/**
* Kinesis related config.
*/
Kinesis kinesis();
/**
* DynamoDb related config.
*/
DynamoDb dynamoDb();
}
| AdvancedEventHandlingConfig |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/alterTable/MySqlAlterTableTest25.java | {
"start": 911,
"end": 1446
} | class ____ extends TestCase {
public void test_alter_add_key() throws Exception {
String sql = "alter table xxxx add over bigint unsigned comment 'xxxx';";
MySqlStatementParser parser = new MySqlStatementParser(sql);
SQLStatement stmt = parser.parseStatementList().get(0);
parser.match(Token.EOF);
String output = SQLUtils.toMySqlString(stmt);
assertEquals("ALTER TABLE xxxx"
+ "\n\tADD COLUMN over bigint UNSIGNED COMMENT 'xxxx';", output);
}
}
| MySqlAlterTableTest25 |
java | playframework__playframework | core/play-guice/src/main/java/play/inject/guice/GuiceBuilder.java | {
"start": 1817,
"end": 6327
} | class ____
*/
public final Self in(ClassLoader classLoader) {
return newBuilder(delegate.in(classLoader));
}
/**
* Add additional configuration.
*
* @param conf the configuration to add
* @return a copy of this builder configured with the supplied configuration
*/
public final Self configure(Config conf) {
return newBuilder(delegate.configure(new play.api.Configuration(conf)));
}
/**
* Add additional configuration.
*
* @param conf the configuration to add
* @return a copy of this builder configured with the supplied configuration
*/
public final Self configure(Map<String, Object> conf) {
return configure(ConfigFactory.parseMap(conf));
}
/**
* Add additional configuration.
*
* @param key a configuration key to set
* @param value the associated value for <code>key</code>
* @return a copy of this builder configured with the key=value
*/
public final Self configure(String key, Object value) {
return configure(ImmutableMap.of(key, value));
}
/**
* Add bindings from guiceable modules.
*
* @param modules the set of modules to bind
* @return a copy of this builder configured with those modules
*/
public final Self bindings(GuiceableModule... modules) {
return newBuilder(delegate.bindings(Scala.varargs(modules)));
}
/**
* Add bindings from Guice modules.
*
* @param modules the set of Guice modules whose bindings to apply
* @return a copy of this builder configured with the provided bindings
*/
public final Self bindings(Module... modules) {
return bindings(Guiceable.modules(modules));
}
/**
* Add bindings from Play modules.
*
* @param modules the set of Guice modules whose bindings to apply
* @return a copy of this builder configured with the provided bindings
*/
public final Self bindings(play.api.inject.Module... modules) {
return bindings(Guiceable.modules(modules));
}
/**
* Add Play bindings.
*
* @param bindings the set of play bindings to apply
* @return a copy of this builder configured with the provided bindings
*/
public final Self bindings(play.api.inject.Binding<?>... bindings) {
return bindings(Guiceable.bindings(bindings));
}
/**
* Override bindings using guiceable modules.
*
* @param modules the set of Guice modules whose bindings override some previously configured ones
* @return a copy of this builder re-configured with the provided bindings
*/
public final Self overrides(GuiceableModule... modules) {
return newBuilder(delegate.overrides(Scala.varargs(modules)));
}
/**
* Override bindings using Guice modules.
*
* @param modules the set of Guice modules whose bindings override some previously configured ones
* @return a copy of this builder re-configured with the provided bindings
*/
public final Self overrides(Module... modules) {
return overrides(Guiceable.modules(modules));
}
/**
* Override bindings using Play modules.
*
* @param modules the set of Play modules whose bindings override some previously configured ones
* @return a copy of this builder re-configured with the provided bindings
*/
public final Self overrides(play.api.inject.Module... modules) {
return overrides(Guiceable.modules(modules));
}
/**
* Override bindings using Play bindings.
*
* @param bindings a set of Play bindings that override some previously configured ones
* @return a copy of this builder re-configured with the provided bindings
*/
public final Self overrides(play.api.inject.Binding<?>... bindings) {
return overrides(Guiceable.bindings(bindings));
}
/**
* Disable modules by class.
*
* @param moduleClasses the module classes whose bindings should be disabled
* @return a copy of this builder configured to ignore the provided module classes
*/
public final Self disable(Class<?>... moduleClasses) {
return newBuilder(delegate.disable(Scala.toSeq(moduleClasses)));
}
/**
* Create a Guice module that can be used to inject an Application.
*
* @return the module
*/
public Module applicationModule() {
return delegate.applicationModule();
}
/**
* Create a Play Injector backed by Guice using this configured builder.
*
* @return the injector
*/
public Injector injector() {
return delegate.injector().instanceOf(Injector.class);
}
protected abstract Self newBuilder(Delegate delegate);
}
| loader |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/streaming/runtime/tasks/TaskCheckpointingBehaviourTest.java | {
"start": 18889,
"end": 20310
} | class ____ extends CheckpointStateOutputStream {
private final Object lock = new Object();
private volatile boolean closed;
@Nullable
@Override
public StreamStateHandle closeAndGetHandle() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void write(int b) throws IOException {
// this needs to not react to interrupts until the handle is closed
synchronized (lock) {
while (!closed) {
try {
lock.wait();
} catch (InterruptedException ignored) {
}
}
}
}
@Override
public void close() throws IOException {
synchronized (lock) {
closed = true;
lock.notifyAll();
}
}
@Override
public long getPos() {
return 0;
}
@Override
public void flush() {}
@Override
public void sync() {}
}
// ------------------------------------------------------------------------
// test source operator that calls into the locking checkpoint output stream.
// ------------------------------------------------------------------------
@SuppressWarnings("serial")
private static final | LockingOutputStream |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/asm/ClassReader.java | {
"start": 47774,
"end": 56377
} | class ____ parsed.
* @param fieldInfoOffset the start offset of the field_info structure.
* @return the offset of the first byte following the field_info structure.
*/
private int readField(
final ClassVisitor classVisitor, final Context context, final int fieldInfoOffset) {
char[] charBuffer = context.charBuffer;
// Read the access_flags, name_index and descriptor_index fields.
int currentOffset = fieldInfoOffset;
int accessFlags = readUnsignedShort(currentOffset);
String name = readUTF8(currentOffset + 2, charBuffer);
String descriptor = readUTF8(currentOffset + 4, charBuffer);
currentOffset += 6;
// Read the field attributes (the variables are ordered as in Section 4.7 of the JVMS).
// Attribute offsets exclude the attribute_name_index and attribute_length fields.
// - The value corresponding to the ConstantValue attribute, or null.
Object constantValue = null;
// - The string corresponding to the Signature attribute, or null.
String signature = null;
// - The offset of the RuntimeVisibleAnnotations attribute, or 0.
int runtimeVisibleAnnotationsOffset = 0;
// - The offset of the RuntimeInvisibleAnnotations attribute, or 0.
int runtimeInvisibleAnnotationsOffset = 0;
// - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.
int runtimeVisibleTypeAnnotationsOffset = 0;
// - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.
int runtimeInvisibleTypeAnnotationsOffset = 0;
// - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).
// This list in the <i>reverse order</i> or their order in the ClassFile structure.
Attribute attributes = null;
int attributesCount = readUnsignedShort(currentOffset);
currentOffset += 2;
while (attributesCount-- > 0) {
// Read the attribute_info's attribute_name and attribute_length fields.
String attributeName = readUTF8(currentOffset, charBuffer);
int attributeLength = readInt(currentOffset + 2);
currentOffset += 6;
// The tests are sorted in decreasing frequency order (based on frequencies observed on
// typical classes).
if (Constants.CONSTANT_VALUE.equals(attributeName)) {
int constantvalueIndex = readUnsignedShort(currentOffset);
constantValue = constantvalueIndex == 0 ? null : readConst(constantvalueIndex, charBuffer);
} else if (Constants.SIGNATURE.equals(attributeName)) {
signature = readUTF8(currentOffset, charBuffer);
} else if (Constants.DEPRECATED.equals(attributeName)) {
accessFlags |= Opcodes.ACC_DEPRECATED;
} else if (Constants.SYNTHETIC.equals(attributeName)) {
accessFlags |= Opcodes.ACC_SYNTHETIC;
} else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {
runtimeVisibleAnnotationsOffset = currentOffset;
} else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {
runtimeVisibleTypeAnnotationsOffset = currentOffset;
} else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {
runtimeInvisibleAnnotationsOffset = currentOffset;
} else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {
runtimeInvisibleTypeAnnotationsOffset = currentOffset;
} else {
Attribute attribute =
readAttribute(
context.attributePrototypes,
attributeName,
currentOffset,
attributeLength,
charBuffer,
-1,
null);
attribute.nextAttribute = attributes;
attributes = attribute;
}
currentOffset += attributeLength;
}
// Visit the field declaration.
FieldVisitor fieldVisitor =
classVisitor.visitField(accessFlags, name, descriptor, signature, constantValue);
if (fieldVisitor == null) {
return currentOffset;
}
// Visit the RuntimeVisibleAnnotations attribute.
if (runtimeVisibleAnnotationsOffset != 0) {
int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);
int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;
while (numAnnotations-- > 0) {
// Parse the type_index field.
String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);
currentAnnotationOffset += 2;
// Parse num_element_value_pairs and element_value_pairs and visit these values.
currentAnnotationOffset =
readElementValues(
fieldVisitor.visitAnnotation(annotationDescriptor, /* visible= */ true),
currentAnnotationOffset,
/* named= */ true,
charBuffer);
}
}
// Visit the RuntimeInvisibleAnnotations attribute.
if (runtimeInvisibleAnnotationsOffset != 0) {
int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);
int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;
while (numAnnotations-- > 0) {
// Parse the type_index field.
String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);
currentAnnotationOffset += 2;
// Parse num_element_value_pairs and element_value_pairs and visit these values.
currentAnnotationOffset =
readElementValues(
fieldVisitor.visitAnnotation(annotationDescriptor, /* visible= */ false),
currentAnnotationOffset,
/* named= */ true,
charBuffer);
}
}
// Visit the RuntimeVisibleTypeAnnotations attribute.
if (runtimeVisibleTypeAnnotationsOffset != 0) {
int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);
int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;
while (numAnnotations-- > 0) {
// Parse the target_type, target_info and target_path fields.
currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);
// Parse the type_index field.
String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);
currentAnnotationOffset += 2;
// Parse num_element_value_pairs and element_value_pairs and visit these values.
currentAnnotationOffset =
readElementValues(
fieldVisitor.visitTypeAnnotation(
context.currentTypeAnnotationTarget,
context.currentTypeAnnotationTargetPath,
annotationDescriptor,
/* visible= */ true),
currentAnnotationOffset,
/* named= */ true,
charBuffer);
}
}
// Visit the RuntimeInvisibleTypeAnnotations attribute.
if (runtimeInvisibleTypeAnnotationsOffset != 0) {
int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);
int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;
while (numAnnotations-- > 0) {
// Parse the target_type, target_info and target_path fields.
currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);
// Parse the type_index field.
String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);
currentAnnotationOffset += 2;
// Parse num_element_value_pairs and element_value_pairs and visit these values.
currentAnnotationOffset =
readElementValues(
fieldVisitor.visitTypeAnnotation(
context.currentTypeAnnotationTarget,
context.currentTypeAnnotationTargetPath,
annotationDescriptor,
/* visible= */ false),
currentAnnotationOffset,
/* named= */ true,
charBuffer);
}
}
// Visit the non standard attributes.
while (attributes != null) {
// Copy and reset the nextAttribute field so that it can also be used in FieldWriter.
Attribute nextAttribute = attributes.nextAttribute;
attributes.nextAttribute = null;
fieldVisitor.visitAttribute(attributes);
attributes = nextAttribute;
}
// Visit the end of the field.
fieldVisitor.visitEnd();
return currentOffset;
}
/**
* Reads a JVMS method_info structure and makes the given visitor visit it.
*
* @param classVisitor the visitor that must visit the method.
* @param context information about the | being |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_3000/Issue3138.java | {
"start": 234,
"end": 416
} | class ____ extends TestCase {
public void test_0() throws Exception {
VO vo = JSON.parseObject("{\"value\":{\"@type\":\"aa\"}}", VO.class);
}
public static | Issue3138 |
java | apache__camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DeferServiceStartupListener.java | {
"start": 1386,
"end": 3091
} | class ____ implements StartupListener, Ordered {
private final Set<Service> earlyServices = new CopyOnWriteArraySet<>();
private final Set<Service> services = new CopyOnWriteArraySet<>();
public void addService(Service service, boolean startEarly) {
if (startEarly) {
earlyServices.add(service);
} else {
services.add(service);
}
}
@Override
public void onCamelContextStarting(CamelContext context, boolean alreadyStarted) throws Exception {
doStart(earlyServices, context, alreadyStarted);
}
@Override
public void onCamelContextStarted(CamelContext context, boolean alreadyStarted) throws Exception {
doStart(services, context, alreadyStarted);
}
protected void doStart(Set<Service> services, CamelContext context, boolean alreadyStarted) throws Exception {
// new services may be added while starting a service
// so use a while loop to get the newly added services as well
while (!services.isEmpty()) {
Service service = services.iterator().next();
try {
ServiceHelper.startService(service);
} catch (Exception e) {
if (service instanceof Endpoint endpoint) {
throw new ResolveEndpointFailedException(endpoint.getEndpointUri(), e);
} else {
throw e;
}
} finally {
services.remove(service);
}
}
}
@Override
public int getOrder() {
// we want to be last, so the other startup listeners run first
return Ordered.LOWEST;
}
}
| DeferServiceStartupListener |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/common/io/stream/InputStreamStreamInputTests.java | {
"start": 605,
"end": 885
} | class ____ extends AbstractStreamTests {
@Override
protected StreamInput getStreamInput(BytesReference bytesReference) throws IOException {
return new InputStreamStreamInput(StreamInput.wrap(BytesReference.toBytes(bytesReference)));
}
}
| InputStreamStreamInputTests |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/imports/innerclasses/TargetWithInnerClass.java | {
"start": 208,
"end": 526
} | class ____ {
private TargetInnerClass innerClassMember;
public TargetInnerClass getInnerClassMember() {
return innerClassMember;
}
public void setInnerClassMember(TargetInnerClass innerClassMember) {
this.innerClassMember = innerClassMember;
}
public static | TargetWithInnerClass |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/checkpointing/StreamCheckpointNotifierITCase.java | {
"start": 13258,
"end": 13365
} | interface ____ stores all the
* checkpoint ids it has seen in a static list.
*/
private static | it |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/admin/internals/AbortTransactionHandler.java | {
"start": 1876,
"end": 9175
} | class ____ extends AdminApiHandler.Batched<TopicPartition, Void> {
private final Logger log;
private final AbortTransactionSpec abortSpec;
private final PartitionLeaderStrategy lookupStrategy;
public AbortTransactionHandler(
AbortTransactionSpec abortSpec,
LogContext logContext
) {
this.abortSpec = abortSpec;
this.log = logContext.logger(AbortTransactionHandler.class);
this.lookupStrategy = new PartitionLeaderStrategy(logContext);
}
public static PartitionLeaderStrategy.PartitionLeaderFuture<Void> newFuture(
Set<TopicPartition> topicPartitions,
Map<TopicPartition, Integer> partitionLeaderCache
) {
return new PartitionLeaderStrategy.PartitionLeaderFuture<>(topicPartitions, partitionLeaderCache);
}
@Override
public String apiName() {
return "abortTransaction";
}
@Override
public AdminApiLookupStrategy<TopicPartition> lookupStrategy() {
return lookupStrategy;
}
@Override
public WriteTxnMarkersRequest.Builder buildBatchedRequest(
int brokerId,
Set<TopicPartition> topicPartitions
) {
validateTopicPartitions(topicPartitions);
WriteTxnMarkersRequestData.WritableTxnMarker marker = new WriteTxnMarkersRequestData.WritableTxnMarker()
.setCoordinatorEpoch(abortSpec.coordinatorEpoch())
.setProducerEpoch(abortSpec.producerEpoch())
.setProducerId(abortSpec.producerId())
.setTransactionResult(false);
marker.topics().add(new WriteTxnMarkersRequestData.WritableTxnMarkerTopic()
.setName(abortSpec.topicPartition().topic())
.setPartitionIndexes(singletonList(abortSpec.topicPartition().partition()))
);
WriteTxnMarkersRequestData request = new WriteTxnMarkersRequestData();
request.markers().add(marker);
return new WriteTxnMarkersRequest.Builder(request);
}
@Override
public ApiResult<TopicPartition, Void> handleResponse(
Node broker,
Set<TopicPartition> topicPartitions,
AbstractResponse abstractResponse
) {
validateTopicPartitions(topicPartitions);
WriteTxnMarkersResponse response = (WriteTxnMarkersResponse) abstractResponse;
List<WriteTxnMarkersResponseData.WritableTxnMarkerResult> markerResponses = response.data().markers();
if (markerResponses.size() != 1 || markerResponses.get(0).producerId() != abortSpec.producerId()) {
return ApiResult.failed(abortSpec.topicPartition(), new KafkaException("WriteTxnMarkers response " +
"included unexpected marker entries: " + markerResponses + "(expected to find exactly one " +
"entry with producerId " + abortSpec.producerId() + ")"));
}
WriteTxnMarkersResponseData.WritableTxnMarkerResult markerResponse = markerResponses.get(0);
List<WriteTxnMarkersResponseData.WritableTxnMarkerTopicResult> topicResponses = markerResponse.topics();
if (topicResponses.size() != 1 || !topicResponses.get(0).name().equals(abortSpec.topicPartition().topic())) {
return ApiResult.failed(abortSpec.topicPartition(), new KafkaException("WriteTxnMarkers response " +
"included unexpected topic entries: " + markerResponses + "(expected to find exactly one " +
"entry with topic partition " + abortSpec.topicPartition() + ")"));
}
WriteTxnMarkersResponseData.WritableTxnMarkerTopicResult topicResponse = topicResponses.get(0);
List<WriteTxnMarkersResponseData.WritableTxnMarkerPartitionResult> partitionResponses =
topicResponse.partitions();
if (partitionResponses.size() != 1 || partitionResponses.get(0).partitionIndex() != abortSpec.topicPartition().partition()) {
return ApiResult.failed(abortSpec.topicPartition(), new KafkaException("WriteTxnMarkers response " +
"included unexpected partition entries for topic " + abortSpec.topicPartition().topic() +
": " + markerResponses + "(expected to find exactly one entry with partition " +
abortSpec.topicPartition().partition() + ")"));
}
WriteTxnMarkersResponseData.WritableTxnMarkerPartitionResult partitionResponse = partitionResponses.get(0);
Errors error = Errors.forCode(partitionResponse.errorCode());
if (error != Errors.NONE) {
return handleError(error);
} else {
return ApiResult.completed(abortSpec.topicPartition(), null);
}
}
private ApiResult<TopicPartition, Void> handleError(Errors error) {
switch (error) {
case CLUSTER_AUTHORIZATION_FAILED:
log.error("WriteTxnMarkers request for abort spec {} failed cluster authorization", abortSpec);
return ApiResult.failed(abortSpec.topicPartition(), new ClusterAuthorizationException(
"WriteTxnMarkers request with " + abortSpec + " failed due to cluster " +
"authorization error"));
case INVALID_PRODUCER_EPOCH:
log.error("WriteTxnMarkers request for abort spec {} failed due to an invalid producer epoch",
abortSpec);
return ApiResult.failed(abortSpec.topicPartition(), new InvalidProducerEpochException(
"WriteTxnMarkers request with " + abortSpec + " failed due an invalid producer epoch"));
case TRANSACTION_COORDINATOR_FENCED:
log.error("WriteTxnMarkers request for abort spec {} failed because the coordinator epoch is fenced",
abortSpec);
return ApiResult.failed(abortSpec.topicPartition(), new TransactionCoordinatorFencedException(
"WriteTxnMarkers request with " + abortSpec + " failed since the provided " +
"coordinator epoch " + abortSpec.coordinatorEpoch() + " has been fenced " +
"by the active coordinator"));
case NOT_LEADER_OR_FOLLOWER:
case REPLICA_NOT_AVAILABLE:
case BROKER_NOT_AVAILABLE:
case UNKNOWN_TOPIC_OR_PARTITION:
log.debug("WriteTxnMarkers request for abort spec {} failed due to {}. Will retry after attempting to " +
"find the leader again", abortSpec, error);
return ApiResult.unmapped(singletonList(abortSpec.topicPartition()));
default:
log.error("WriteTxnMarkers request for abort spec {} failed due to an unexpected error {}",
abortSpec, error);
return ApiResult.failed(abortSpec.topicPartition(), error.exception(
"WriteTxnMarkers request with " + abortSpec + " failed due to unexpected error: " + error.message()));
}
}
private void validateTopicPartitions(Set<TopicPartition> topicPartitions) {
if (!topicPartitions.equals(singleton(abortSpec.topicPartition()))) {
throw new IllegalArgumentException("Received unexpected topic partitions " + topicPartitions +
" (expected only " + singleton(abortSpec.topicPartition()) + ")");
}
}
}
| AbortTransactionHandler |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/codegen/AsyncCodeGeneratorTest.java | {
"start": 13186,
"end": 13452
} | class ____ extends AsyncScalarFunction {
public void eval(CompletableFuture<String> f, Integer i, Long l, String s) {
f.completeExceptionally(new RuntimeException("Error!"));
}
}
/** Test function. */
public static | AsyncFuncError |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/pvt/pool/TestAbondon.java | {
"start": 877,
"end": 1997
} | class ____ extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
DruidDataSourceStatManager.clear();
dataSource = new DruidDataSource();
dataSource.setRemoveAbandoned(true);
dataSource.setRemoveAbandonedTimeoutMillis(10);
dataSource.setLogAbandoned(true);
dataSource.setTimeBetweenEvictionRunsMillis(10);
dataSource.setMinEvictableIdleTimeMillis(300 * 1000);
dataSource.setUrl("jdbc:mock:xxx");
}
protected void tearDown() throws Exception {
dataSource.close();
Assert.assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size());
}
public void test_0() throws Exception {
DruidPooledConnection conn = dataSource.getConnection();
Assert.assertEquals(false, conn.isClosed());
Thread.sleep(10);
for (int i = 0; i < 100; ++i) {
if (conn.isAbandonded()) {
break;
}
Thread.sleep(10);
}
Assert.assertEquals(true, conn.isAbandonded());
}
}
| TestAbondon |
java | quarkusio__quarkus | extensions/security/deployment/src/test/java/io/quarkus/security/test/cdi/inheritance/SubclassRolesAllowedBean.java | {
"start": 131,
"end": 191
} | class ____ extends RolesAllowedBean {
}
| SubclassRolesAllowedBean |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AsyncRequest.java | {
"start": 971,
"end": 1662
} | class ____<K> {
/** The record context of this request. */
protected final RecordContext<K> context;
protected final boolean sync;
/** The future to collect the result of the request. */
protected final InternalAsyncFuture asyncFuture;
public AsyncRequest(RecordContext<K> context, boolean sync, InternalAsyncFuture asyncFuture) {
this.context = context;
this.sync = sync;
this.asyncFuture = asyncFuture;
}
public RecordContext<K> getRecordContext() {
return context;
}
public boolean isSync() {
return sync;
}
public InternalAsyncFuture getFuture() {
return asyncFuture;
}
}
| AsyncRequest |
java | netty__netty | codec-base/src/main/java/io/netty/handler/codec/AsciiHeadersEncoder.java | {
"start": 1282,
"end": 3662
} | enum ____ {
/**
* {@code '\n'}
*/
LF,
/**
* {@code '\r\n'}
*/
CRLF
}
private final ByteBuf buf;
private final SeparatorType separatorType;
private final NewlineType newlineType;
public AsciiHeadersEncoder(ByteBuf buf) {
this(buf, SeparatorType.COLON_SPACE, NewlineType.CRLF);
}
public AsciiHeadersEncoder(ByteBuf buf, SeparatorType separatorType, NewlineType newlineType) {
this.buf = ObjectUtil.checkNotNull(buf, "buf");
this.separatorType = ObjectUtil.checkNotNull(separatorType, "separatorType");
this.newlineType = ObjectUtil.checkNotNull(newlineType, "newlineType");
}
public void encode(Entry<CharSequence, CharSequence> entry) {
final CharSequence name = entry.getKey();
final CharSequence value = entry.getValue();
final ByteBuf buf = this.buf;
final int nameLen = name.length();
final int valueLen = value.length();
final int entryLen = nameLen + valueLen + 4;
int offset = buf.writerIndex();
buf.ensureWritable(entryLen);
writeAscii(buf, offset, name);
offset += nameLen;
switch (separatorType) {
case COLON:
buf.setByte(offset ++, ':');
break;
case COLON_SPACE:
buf.setByte(offset ++, ':');
buf.setByte(offset ++, ' ');
break;
default:
throw new Error("Unexpected separator type: " + separatorType);
}
writeAscii(buf, offset, value);
offset += valueLen;
switch (newlineType) {
case LF:
buf.setByte(offset ++, '\n');
break;
case CRLF:
buf.setByte(offset ++, '\r');
buf.setByte(offset ++, '\n');
break;
default:
throw new Error("Unexpected newline type: " + newlineType);
}
buf.writerIndex(offset);
}
private static void writeAscii(ByteBuf buf, int offset, CharSequence value) {
if (value instanceof AsciiString) {
ByteBufUtil.copy((AsciiString) value, 0, buf, offset, value.length());
} else {
buf.setCharSequence(offset, value, CharsetUtil.US_ASCII);
}
}
}
| NewlineType |
java | grpc__grpc-java | alts/src/main/java/io/grpc/alts/internal/TsiPeer.java | {
"start": 1956,
"end": 2198
} | class ____ extends Property<Boolean> {
public BooleanProperty(@Nonnull String name, boolean value) {
super(name, value);
}
}
/** A peer property corresponding to a signed 64-bit integer. */
public static final | BooleanProperty |
java | quarkusio__quarkus | extensions/cache/deployment/src/test/java/io/quarkus/cache/test/runtime/CachedResultsInjectFailureTest.java | {
"start": 401,
"end": 834
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot(
jar -> jar.addClasses(MujBean.class))
.setExpectedException(IllegalStateException.class);
@Inject
@CachedResults
MujBean mujBean;
@Test
public void testFailure() {
fail();
}
@Dependent
public static | CachedResultsInjectFailureTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/node/shutdown/NodePrevalidateShardPathResponse.java | {
"start": 891,
"end": 2056
} | class ____ extends BaseNodeResponse {
private final Set<ShardId> shardIds;
protected NodePrevalidateShardPathResponse(DiscoveryNode node, Set<ShardId> shardIds) {
super(node);
this.shardIds = Set.copyOf(Objects.requireNonNull(shardIds));
}
protected NodePrevalidateShardPathResponse(StreamInput in) throws IOException {
super(in);
shardIds = in.readCollectionAsImmutableSet(ShardId::new);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeCollection(shardIds);
}
public Set<ShardId> getShardIds() {
return shardIds;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof NodePrevalidateShardPathResponse == false) return false;
NodePrevalidateShardPathResponse other = (NodePrevalidateShardPathResponse) o;
return Objects.equals(shardIds, other.shardIds) && Objects.equals(getNode(), other.getNode());
}
@Override
public int hashCode() {
return Objects.hash(shardIds, getNode());
}
}
| NodePrevalidateShardPathResponse |
java | junit-team__junit5 | junit-platform-console/src/main/java/org/junit/platform/console/options/SelectorConverter.java | {
"start": 3211,
"end": 3371
} | class ____ implements ITypeConverter<ClassSelector> {
@Override
public ClassSelector convert(String value) {
return selectClass(value);
}
}
static | Class |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/args/PathParamArgumentExplicitNameTest.java | {
"start": 579,
"end": 1176
} | class ____ {
@RegisterExtension
public static final QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot(root -> {
root.addClasses(MontyEcho.class, WSClient.class);
});
@Inject
Vertx vertx;
@TestHTTPResource("echo/monty")
URI testUri;
@Test
void testArgument() {
WSClient client = WSClient.create(vertx).connect(testUri);
assertEquals("python:monty", client.sendAndAwaitReply("python").toString());
}
@WebSocket(path = "/echo/{grail}")
public static | PathParamArgumentExplicitNameTest |
java | apache__camel | components/camel-jolt/src/main/java/org/apache/camel/component/jolt/JoltEndpoint.java | {
"start": 1953,
"end": 8303
} | class ____ extends ResourceEndpoint {
private JoltTransform transform;
@UriParam(defaultValue = "Hydrated")
private JoltInputOutputType outputType;
@UriParam(defaultValue = "Hydrated")
private JoltInputOutputType inputType;
@UriParam(defaultValue = "Chainr")
private JoltTransformType transformDsl = JoltTransformType.Chainr;
@UriParam(defaultValue = "false")
private boolean allowTemplateFromHeader;
public JoltEndpoint() {
}
public JoltEndpoint(String uri, JoltComponent component, String resourceUri) {
super(uri, component, resourceUri);
}
@Override
public boolean isRemote() {
return false;
}
@Override
public void clearContentCache() {
super.clearContentCache();
transform = null;
}
@Override
public ExchangePattern getExchangePattern() {
return ExchangePattern.InOut;
}
@Override
protected String createEndpointUri() {
return "jolt:" + getResourceUri();
}
private JoltTransform getTransform() throws Exception {
getInternalLock().lock();
try {
if (transform == null) {
if (log.isDebugEnabled()) {
String path = getResourceUri();
log.debug("Jolt content read from resource {} with resourceUri: {} for endpoint {}", getResourceUri(), path,
getEndpointUri());
}
// Sortr does not require a spec
if (this.transformDsl == JoltTransformType.Sortr) {
this.transform = new Sortr();
} else {
// getResourceAsInputStream also considers the content cache
Object spec = JsonUtils.jsonToObject(getResourceAsInputStream());
switch (this.transformDsl) {
case Shiftr:
this.transform = new Shiftr(spec);
break;
case Defaultr:
this.transform = new Defaultr(spec);
break;
case Removr:
this.transform = new Removr(spec);
break;
case Chainr:
default:
this.transform = Chainr.fromSpec(spec);
break;
}
}
}
return transform;
} finally {
getInternalLock().unlock();
}
}
/**
* Sets the Transform to use. If not set a Transform specified by the transformDsl will be created
*/
public void setTransform(JoltTransform transform) {
this.transform = transform;
}
public JoltInputOutputType getOutputType() {
return outputType;
}
/**
* Specifies if the output should be hydrated JSON or a JSON String.
*/
public void setOutputType(JoltInputOutputType outputType) {
this.outputType = outputType;
}
public JoltInputOutputType getInputType() {
return inputType;
}
/**
* Specifies if the input is hydrated JSON or a JSON String.
*/
public void setInputType(JoltInputOutputType inputType) {
this.inputType = inputType;
}
public JoltTransformType getTransformDsl() {
return transformDsl;
}
/**
* Specifies the Transform DSL of the endpoint resource. If none is specified <code>Chainr</code> will be used.
*/
public void setTransformDsl(JoltTransformType transformType) {
this.transformDsl = transformType;
}
public boolean isAllowTemplateFromHeader() {
return allowTemplateFromHeader;
}
/**
* Whether to allow to use resource template from header or not (default false).
*
* Enabling this allows to specify dynamic templates via message header. However this can be seen as a potential
* security vulnerability if the header is coming from a malicious user, so use this with care.
*/
public void setAllowTemplateFromHeader(boolean allowTemplateFromHeader) {
this.allowTemplateFromHeader = allowTemplateFromHeader;
}
public JoltEndpoint findOrCreateEndpoint(String uri, String newResourceUri) {
String newUri = uri.replace(getResourceUri(), newResourceUri);
log.debug("Getting endpoint with URI: {}", newUri);
return getCamelContext().getEndpoint(newUri, JoltEndpoint.class);
}
@Override
protected void onExchange(Exchange exchange) throws Exception {
String path = getResourceUri();
ObjectHelper.notNull(path, "resourceUri");
String newResourceUri = null;
if (allowTemplateFromHeader) {
newResourceUri = exchange.getIn().getHeader(JoltConstants.JOLT_RESOURCE_URI, String.class);
}
if (newResourceUri != null) {
exchange.getIn().removeHeader(JoltConstants.JOLT_RESOURCE_URI);
log.debug("{} set to {} creating new endpoint to handle exchange", JoltConstants.JOLT_RESOURCE_URI, newResourceUri);
JoltEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
newEndpoint.onExchange(exchange);
return;
}
Object input;
if (getInputType() == JoltInputOutputType.JsonString) {
input = JsonUtils.jsonToObject(exchange.getIn().getBody(InputStream.class));
} else {
input = exchange.getIn().getBody();
}
Map<String, Object> inputContextMap = null;
if (allowTemplateFromHeader) {
inputContextMap = exchange.getIn().getHeader(JoltConstants.JOLT_CONTEXT, Map.class);
}
Object output;
if (inputContextMap != null) {
output = ((ContextualTransform) getTransform()).transform(input, inputContextMap);
} else {
output = ((Transform) getTransform()).transform(input);
}
// now lets output the results to the exchange
Object body = output;
if (getOutputType() == JoltInputOutputType.JsonString) {
body = JsonUtils.toJsonString(output);
}
ExchangeHelper.setInOutBodyPatternAware(exchange, body);
}
}
| JoltEndpoint |
java | spring-projects__spring-boot | module/spring-boot-security/src/main/java/org/springframework/boot/security/autoconfigure/ReactiveUserDetailsServiceAutoConfiguration.java | {
"start": 5115,
"end": 5343
} | class ____ extends AnyNestedCondition {
RSocketEnabledOrReactiveWebApplication() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnBean(RSocketMessageHandler.class)
static | RSocketEnabledOrReactiveWebApplication |
java | alibaba__fastjson | src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonAutoDiscoverable.java | {
"start": 440,
"end": 1197
} | class ____ implements AutoDiscoverable {
public static final String FASTJSON_AUTO_DISCOVERABLE = "fastjson.auto.discoverable";
public volatile static boolean autoDiscover = true;
static {
try {
autoDiscover = Boolean.parseBoolean(
System.getProperty(FASTJSON_AUTO_DISCOVERABLE, String.valueOf(autoDiscover)));
} catch (Throwable ex) {
//skip
}
}
public void configure(final FeatureContext context) {
final Configuration config = context.getConfiguration();
// Register FastJson.
if (!config.isRegistered(FastJsonFeature.class) && autoDiscover) {
context.register(FastJsonFeature.class);
}
}
}
| FastJsonAutoDiscoverable |
java | apache__camel | components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/Constants.java | {
"start": 1002,
"end": 1075
} | class ____ {
public static String FOO = "123";
}
}
| MyInnerStuff |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/aot/samples/basic/ImportsContextCustomizerFactory.java | {
"start": 1450,
"end": 2055
} | class ____ implements ContextCustomizerFactory {
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass,
List<ContextConfigurationAttributes> configAttributes) {
if (AotDetector.useGeneratedArtifacts()) {
return null;
}
if (testClass.getName().startsWith("org.springframework.test.context.aot.samples") &&
testClass.isAnnotationPresent(Import.class)) {
return new ImportsContextCustomizer(testClass);
}
return null;
}
/**
* Emulates {@code ImportsContextCustomizer} from Spring Boot's testing support.
*/
private static | ImportsContextCustomizerFactory |
java | quarkusio__quarkus | extensions/spring-security/runtime/src/main/java/io/quarkus/spring/security/runtime/interceptor/check/PrincipalNameFromParameterObjectSecurityCheck.java | {
"start": 766,
"end": 4227
} | class ____ implements SecurityCheck {
private final int index;
private final Class<?> expectedParameterClass;
private final Class<? extends StringPropertyAccessor> stringPropertyAccessorClass;
private final String propertyName;
private final CheckType checkType;
private PrincipalNameFromParameterObjectSecurityCheck(int index, String expectedParameterClass,
String stringPropertyAccessorClass, String propertyName, CheckType checkType) throws ClassNotFoundException {
this.index = index;
this.expectedParameterClass = Class.forName(expectedParameterClass, false,
Thread.currentThread().getContextClassLoader());
this.stringPropertyAccessorClass = (Class<? extends StringPropertyAccessor>) Class.forName(stringPropertyAccessorClass,
false, Thread.currentThread().getContextClassLoader());
this.propertyName = propertyName;
this.checkType = checkType;
}
public static PrincipalNameFromParameterObjectSecurityCheck of(int index, String expectedParameterClass,
String stringPropertyAccessorClass, String propertyName, CheckType checkType) {
try {
return new PrincipalNameFromParameterObjectSecurityCheck(index, expectedParameterClass, stringPropertyAccessorClass,
propertyName, checkType);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
@Override
public void apply(SecurityIdentity identity, Method method, Object[] parameters) {
doApply(identity, parameters, method.getDeclaringClass().getName(), method.getName());
}
@Override
public void apply(SecurityIdentity identity, MethodDescription methodDescription, Object[] parameters) {
doApply(identity, parameters, methodDescription.getClassName(), methodDescription.getMethodName());
}
private void doApply(SecurityIdentity identity, Object[] parameters, String className, String methodName) {
if (index > parameters.length - 1) {
throw genericNotApplicableException(className, methodName);
}
Object parameterValue = parameters[index];
if (!expectedParameterClass.equals(parameterValue.getClass())) {
throw genericNotApplicableException(className, methodName);
}
String parameterValueStr = getStringValue(parameterValue);
if (identity.isAnonymous()) {
throw new UnauthorizedException();
}
String name = identity.getPrincipal().getName();
if (checkType == CheckType.EQ) {
if (!name.equals(parameterValueStr)) {
throw new ForbiddenException();
}
} else if (checkType == CheckType.NEQ) {
if (name.equals(parameterValueStr)) {
throw new ForbiddenException();
}
}
}
private String getStringValue(Object parameterValue) {
return Arc.container().instance(stringPropertyAccessorClass).get().access(parameterValue, propertyName);
}
private IllegalStateException genericNotApplicableException(String className, String methodName) {
return new IllegalStateException(
"PrincipalNameFromParameterObjectSecurityCheck with index " + index + " cannot be applied to '" + className
+ "#" + methodName + "'");
}
public | PrincipalNameFromParameterObjectSecurityCheck |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/result/SimpleHandlerAdapter.java | {
"start": 1210,
"end": 1617
} | class ____ implements HandlerAdapter {
@Override
public boolean supports(Object handler) {
return WebHandler.class.isAssignableFrom(handler.getClass());
}
@Override
public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {
WebHandler webHandler = (WebHandler) handler;
Mono<Void> mono = webHandler.handle(exchange);
return mono.then(Mono.empty());
}
}
| SimpleHandlerAdapter |
java | google__error-prone | test_helpers/src/test/java/com/google/errorprone/CompilationTestHelperTest.java | {
"start": 5023,
"end": 5728
} | class ____ {
// BUG: Diagnostic contains:
public boolean doIt() {
return true;
}
}
""")
.doTest());
assertThat(expected).hasMessageThat().contains("Did not see an error on line 3");
}
@Test
public void fileWithBugMatcherAndErrorOnWrongLineFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.addSourceLines(
"Test.java",
"""
public | Test |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/TestContext.java | {
"start": 4710,
"end": 4865
} | class ____ the current {@linkplain #getTestMethod() test method},
* which may be a {@link org.junit.jupiter.api.Nested @Nested} test class
* within the | for |
java | spring-projects__spring-framework | spring-core-test/src/main/java/org/springframework/core/test/tools/DynamicResourceFileObject.java | {
"start": 1133,
"end": 2033
} | class ____ extends SimpleJavaFileObject {
private volatile byte @Nullable [] bytes;
DynamicResourceFileObject(String fileName) {
super(createUri(fileName), Kind.OTHER);
}
DynamicResourceFileObject(String fileName, String content) {
super(createUri(fileName), Kind.OTHER);
this.bytes = content.getBytes();
}
private static URI createUri(String fileName) {
return URI.create("resource:///" + fileName);
}
@Override
public InputStream openInputStream() throws IOException {
byte[] content = this.bytes;
if (content == null) {
throw new IOException("No data written");
}
return new ByteArrayInputStream(content);
}
@Override
public OutputStream openOutputStream() {
return new JavaResourceOutputStream();
}
private void closeOutputStream(byte[] bytes) {
this.bytes = bytes;
}
byte @Nullable [] getBytes() {
return this.bytes;
}
| DynamicResourceFileObject |
java | apache__dubbo | dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/enums/DubboGenerateTypeEnum.java | {
"start": 862,
"end": 1861
} | enum ____ {
Tri("tri", "org.apache.dubbo.gen.tri.Dubbo3TripleGenerator"),
Tri_reactor("tri_reactor", "org.apache.dubbo.gen.tri.reactive.ReactorDubbo3TripleGenerator"),
;
private String id;
private String mainClass;
DubboGenerateTypeEnum(String id, String mainClass) {
this.id = id;
this.mainClass = mainClass;
}
public static DubboGenerateTypeEnum getByType(String dubboGenerateType) {
DubboGenerateTypeEnum[] values = DubboGenerateTypeEnum.values();
for (DubboGenerateTypeEnum value : values) {
if (value.getId().equals(dubboGenerateType)) {
return value;
}
}
return null;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMainClass() {
return mainClass;
}
public void setMainClass(String mainClass) {
this.mainClass = mainClass;
}
}
| DubboGenerateTypeEnum |
java | google__gson | gson/src/test/java/com/google/gson/GsonTest.java | {
"start": 4217,
"end": 5213
} | class ____ extends TypeAdapter<Integer> {
@Override
public Integer read(JsonReader in) throws IOException {
in.skipValue();
return 3;
}
@Override
public void write(JsonWriter out, Integer value) {
throw new AssertionError("not needed for test");
}
@Override
public String toString() {
return "custom-adapter";
}
}
Gson gson = new GsonBuilder().registerTypeAdapter(Boolean.class, new IntegerAdapter()).create();
// Use `Class<?>` here to avoid that the JVM itself creates the ClassCastException (though the
// check below for the custom message would detect that as well)
Class<?> deserializedClass = Boolean.class;
var exception =
assertThrows(ClassCastException.class, () -> gson.fromJson("true", deserializedClass));
assertThat(exception)
.hasMessageThat()
.isEqualTo(
"Type adapter 'custom-adapter' returned wrong type; requested | IntegerAdapter |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/BooleanLiteralTest.java | {
"start": 5701,
"end": 5958
} | class ____ {
Boolean f() {
Boolean foo = null;
Boolean b = true ? foo : Boolean.TRUE;
return b;
}
}
""")
.expectUnchanged()
.doTest();
}
}
| Test |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/service/invoker/AbstractReactorHttpExchangeAdapter.java | {
"start": 1218,
"end": 3967
} | class ____ implements ReactorHttpExchangeAdapter {
private ReactiveAdapterRegistry reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
private @Nullable Duration blockTimeout;
/**
* Protected constructor, for subclasses.
*/
protected AbstractReactorHttpExchangeAdapter() {
}
/**
* Configure the {@link ReactiveAdapterRegistry} to use.
* <p>By default, this is {@link ReactiveAdapterRegistry#getSharedInstance()}.
*/
public void setReactiveAdapterRegistry(ReactiveAdapterRegistry reactiveAdapterRegistry) {
this.reactiveAdapterRegistry = reactiveAdapterRegistry;
}
@Override
public ReactiveAdapterRegistry getReactiveAdapterRegistry() {
return this.reactiveAdapterRegistry;
}
/**
* Configure how long to block for the response of an HTTP service method
* as described in {@link #getBlockTimeout()}.
*/
public void setBlockTimeout(@Nullable Duration blockTimeout) {
this.blockTimeout = blockTimeout;
}
@Override
public @Nullable Duration getBlockTimeout() {
return this.blockTimeout;
}
@Override
public void exchange(HttpRequestValues requestValues) {
if (this.blockTimeout != null) {
exchangeForMono(requestValues).block(this.blockTimeout);
}
else {
exchangeForMono(requestValues).block();
}
}
@Override
public HttpHeaders exchangeForHeaders(HttpRequestValues requestValues) {
HttpHeaders headers = (this.blockTimeout != null ?
exchangeForHeadersMono(requestValues).block(this.blockTimeout) :
exchangeForHeadersMono(requestValues).block());
Assert.state(headers != null, "Expected HttpHeaders");
return headers;
}
@Override
@Nullable
public <T> T exchangeForBody(HttpRequestValues requestValues, ParameterizedTypeReference<T> bodyType) {
return (this.blockTimeout != null ?
exchangeForBodyMono(requestValues, bodyType).block(this.blockTimeout) :
exchangeForBodyMono(requestValues, bodyType).block());
}
@Override
public ResponseEntity<Void> exchangeForBodilessEntity(HttpRequestValues requestValues) {
ResponseEntity<Void> entity = (this.blockTimeout != null ?
exchangeForBodilessEntityMono(requestValues).block(this.blockTimeout) :
exchangeForBodilessEntityMono(requestValues).block());
Assert.state(entity != null, "Expected ResponseEntity");
return entity;
}
@Override
public <T> ResponseEntity<T> exchangeForEntity(
HttpRequestValues requestValues, ParameterizedTypeReference<T> bodyType) {
ResponseEntity<T> entity = (this.blockTimeout != null ?
exchangeForEntityMono(requestValues, bodyType).block(this.blockTimeout) :
exchangeForEntityMono(requestValues, bodyType).block());
Assert.state(entity != null, "Expected ResponseEntity");
return entity;
}
}
| AbstractReactorHttpExchangeAdapter |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/sps/TestStoragePolicySatisfierWithStripedFile.java | {
"start": 2708,
"end": 23313
} | class ____ {
private static final Logger LOG = LoggerFactory
.getLogger(TestStoragePolicySatisfierWithStripedFile.class);
private final int stripesPerBlock = 2;
private ErasureCodingPolicy ecPolicy;
private int dataBlocks;
private int parityBlocks;
private int cellSize;
private int defaultStripeBlockSize;
private Configuration conf;
private StoragePolicySatisfier sps;
private ExternalSPSContext ctxt;
private NameNodeConnector nnc;
private ErasureCodingPolicy getEcPolicy() {
return StripedFileTestUtil.getDefaultECPolicy();
}
/**
* Initialize erasure coding policy.
*/
@BeforeEach
public void init(){
ecPolicy = getEcPolicy();
dataBlocks = ecPolicy.getNumDataUnits();
parityBlocks = ecPolicy.getNumParityUnits();
cellSize = ecPolicy.getCellSize();
defaultStripeBlockSize = cellSize * stripesPerBlock;
conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_STORAGE_POLICY_SATISFIER_MODE_KEY,
StoragePolicySatisfierMode.EXTERNAL.toString());
// Reduced refresh cycle to update latest datanodes.
conf.setLong(DFSConfigKeys.DFS_SPS_DATANODE_CACHE_REFRESH_INTERVAL_MS,
1000);
conf.setInt(
DFSConfigKeys.DFS_STORAGE_POLICY_SATISFIER_MAX_RETRY_ATTEMPTS_KEY, 30);
initConfWithStripe(conf, defaultStripeBlockSize);
}
/**
* Tests to verify that all the striped blocks(data + parity blocks) are
* moving to satisfy the storage policy.
*/
@Test
@Timeout(value = 300)
public void testMoverWithFullStripe() throws Exception {
// start 11 datanodes
int numOfDatanodes = 11;
int storagesPerDatanode = 2;
long capacity = 20 * defaultStripeBlockSize;
long[][] capacities = new long[numOfDatanodes][storagesPerDatanode];
for (int i = 0; i < numOfDatanodes; i++) {
for (int j = 0; j < storagesPerDatanode; j++) {
capacities[i][j] = capacity;
}
}
final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(numOfDatanodes)
.storagesPerDatanode(storagesPerDatanode)
.storageTypes(new StorageType[][]{
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE}})
.storageCapacities(capacities)
.build();
HdfsAdmin hdfsAdmin = new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
try {
cluster.waitActive();
startSPS();
DistributedFileSystem dfs = cluster.getFileSystem();
dfs.enableErasureCodingPolicy(
StripedFileTestUtil.getDefaultECPolicy().getName());
// set "/bar" directory with HOT storage policy.
ClientProtocol client = NameNodeProxies.createProxy(conf,
cluster.getFileSystem(0).getUri(), ClientProtocol.class).getProxy();
String barDir = "/bar";
client.mkdirs(barDir, new FsPermission((short) 777), true);
client.setStoragePolicy(barDir, HdfsConstants.HOT_STORAGE_POLICY_NAME);
// set an EC policy on "/bar" directory
client.setErasureCodingPolicy(barDir,
StripedFileTestUtil.getDefaultECPolicy().getName());
// write file to barDir
final String fooFile = "/bar/foo";
long fileLen = cellSize * dataBlocks;
DFSTestUtil.createFile(cluster.getFileSystem(), new Path(fooFile),
fileLen, (short) 3, 0);
// verify storage types and locations
LocatedBlocks locatedBlocks = client.getBlockLocations(fooFile, 0,
fileLen);
for (LocatedBlock lb : locatedBlocks.getLocatedBlocks()) {
for (StorageType type : lb.getStorageTypes()) {
assertEquals(StorageType.DISK, type);
}
}
StripedFileTestUtil.verifyLocatedStripedBlocks(locatedBlocks,
dataBlocks + parityBlocks);
// start 5 more datanodes
int numOfNewDatanodes = 5;
capacities = new long[numOfNewDatanodes][storagesPerDatanode];
for (int i = 0; i < numOfNewDatanodes; i++) {
for (int j = 0; j < storagesPerDatanode; j++) {
capacities[i][j] = capacity;
}
}
cluster.startDataNodes(conf, 5,
new StorageType[][]{
{StorageType.ARCHIVE, StorageType.ARCHIVE},
{StorageType.ARCHIVE, StorageType.ARCHIVE},
{StorageType.ARCHIVE, StorageType.ARCHIVE},
{StorageType.ARCHIVE, StorageType.ARCHIVE},
{StorageType.ARCHIVE, StorageType.ARCHIVE}},
true, null, null, null, capacities, null, false, false, false, null, null, null);
cluster.triggerHeartbeats();
// move file to ARCHIVE
client.setStoragePolicy(barDir, "COLD");
hdfsAdmin.satisfyStoragePolicy(new Path(fooFile));
LOG.info("Sets storage policy to COLD and invoked satisfyStoragePolicy");
cluster.triggerHeartbeats();
// verify storage types and locations
waitExpectedStorageType(cluster, fooFile, fileLen, StorageType.ARCHIVE, 9,
9, 60000);
} finally {
cluster.shutdown();
sps.stopGracefully();
}
}
/**
* Tests to verify that only few datanodes are available and few striped
* blocks are able to move. Others are still trying to find available nodes.
*
* For example, we have 3 nodes A(disk, disk), B(disk, disk), C(disk, archive)
*
* Assume a block with storage locations A(disk), B(disk), C(disk). Now, set
* policy as COLD and invoked {@link HdfsAdmin#satisfyStoragePolicy(Path)},
* while choosing the target node for A, it shouldn't choose C. For C, it
* should do local block movement as it has ARCHIVE storage type.
*/
@Test
@Timeout(value = 300)
public void testWhenOnlyFewTargetNodesAreAvailableToSatisfyStoragePolicy()
throws Exception {
// start 10 datanodes
int numOfDatanodes = 11;
int storagesPerDatanode = 2;
long capacity = 20 * defaultStripeBlockSize;
long[][] capacities = new long[numOfDatanodes][storagesPerDatanode];
for (int i = 0; i < numOfDatanodes; i++) {
for (int j = 0; j < storagesPerDatanode; j++) {
capacities[i][j] = capacity;
}
}
final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(numOfDatanodes)
.storagesPerDatanode(storagesPerDatanode)
.storageTypes(new StorageType[][]{
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE}})
.storageCapacities(capacities)
.build();
HdfsAdmin hdfsAdmin = new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
try {
cluster.waitActive();
startSPS();
DistributedFileSystem dfs = cluster.getFileSystem();
dfs.enableErasureCodingPolicy(
StripedFileTestUtil.getDefaultECPolicy().getName());
// set "/bar" directory with HOT storage policy.
ClientProtocol client = NameNodeProxies.createProxy(conf,
cluster.getFileSystem(0).getUri(), ClientProtocol.class).getProxy();
String barDir = "/bar";
client.mkdirs(barDir, new FsPermission((short) 777), true);
client.setStoragePolicy(barDir, HdfsConstants.HOT_STORAGE_POLICY_NAME);
// set an EC policy on "/bar" directory
client.setErasureCodingPolicy(barDir,
StripedFileTestUtil.getDefaultECPolicy().getName());
// write file to barDir
final String fooFile = "/bar/foo";
long fileLen = cellSize * dataBlocks;
DFSTestUtil.createFile(cluster.getFileSystem(), new Path(fooFile),
fileLen, (short) 3, 0);
// verify storage types and locations
LocatedBlocks locatedBlocks = client.getBlockLocations(fooFile, 0,
fileLen);
for (LocatedBlock lb : locatedBlocks.getLocatedBlocks()) {
for (StorageType type : lb.getStorageTypes()) {
assertEquals(StorageType.DISK, type);
}
}
Thread.sleep(5000);
StripedFileTestUtil.verifyLocatedStripedBlocks(locatedBlocks,
dataBlocks + parityBlocks);
// start 2 more datanodes
int numOfNewDatanodes = 2;
capacities = new long[numOfNewDatanodes][storagesPerDatanode];
for (int i = 0; i < numOfNewDatanodes; i++) {
for (int j = 0; j < storagesPerDatanode; j++) {
capacities[i][j] = capacity;
}
}
cluster.startDataNodes(conf, 2,
new StorageType[][]{
{StorageType.ARCHIVE, StorageType.ARCHIVE},
{StorageType.ARCHIVE, StorageType.ARCHIVE}},
true, null, null, null, capacities, null, false, false, false, null, null, null);
cluster.triggerHeartbeats();
// Move file to ARCHIVE. Only 5 datanodes are available with ARCHIVE
// storage type.
client.setStoragePolicy(barDir, "COLD");
hdfsAdmin.satisfyStoragePolicy(new Path(fooFile));
LOG.info("Sets storage policy to COLD and invoked satisfyStoragePolicy");
cluster.triggerHeartbeats();
waitForAttemptedItems(1, 30000);
// verify storage types and locations.
waitExpectedStorageType(cluster, fooFile, fileLen, StorageType.ARCHIVE, 5,
9, 60000);
} finally {
cluster.shutdown();
sps.stopGracefully();
}
}
/**
* Test SPS for low redundant file blocks.
* 1. Create cluster with 10 datanode.
* 1. Create one striped file with default EC Policy.
* 2. Set policy and call satisfyStoragePolicy for file.
* 3. Stop NameNode and Datanodes.
* 4. Start NameNode with 5 datanode and wait for block movement.
* 5. Start remaining 5 datanode.
* 6. All replica should be moved in proper storage based on policy.
*/
@Test
@Timeout(value = 300)
public void testSPSWhenFileHasLowRedundancyBlocks() throws Exception {
// start 9 datanodes
int numOfDatanodes = 9;
int storagesPerDatanode = 2;
long capacity = 20 * defaultStripeBlockSize;
long[][] capacities = new long[numOfDatanodes][storagesPerDatanode];
for (int i = 0; i < numOfDatanodes; i++) {
for (int j = 0; j < storagesPerDatanode; j++) {
capacities[i][j] = capacity;
}
}
conf.set(DFSConfigKeys
.DFS_STORAGE_POLICY_SATISFIER_RECHECK_TIMEOUT_MILLIS_KEY,
"3000");
conf.set(DFSConfigKeys
.DFS_STORAGE_POLICY_SATISFIER_SELF_RETRY_TIMEOUT_MILLIS_KEY,
"5000");
final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(numOfDatanodes)
.storagesPerDatanode(storagesPerDatanode)
.storageTypes(new StorageType[][]{
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE},
{StorageType.DISK, StorageType.ARCHIVE}})
.storageCapacities(capacities)
.build();
try {
cluster.waitActive();
startSPS();
DistributedFileSystem fs = cluster.getFileSystem();
fs.enableErasureCodingPolicy(
StripedFileTestUtil.getDefaultECPolicy().getName());
Path barDir = new Path("/bar");
fs.mkdirs(barDir);
// set an EC policy on "/bar" directory
fs.setErasureCodingPolicy(barDir,
StripedFileTestUtil.getDefaultECPolicy().getName());
// write file to barDir
final Path fooFile = new Path("/bar/foo");
long fileLen = cellSize * dataBlocks;
DFSTestUtil.createFile(cluster.getFileSystem(), fooFile,
fileLen, (short) 3, 0);
// Move file to ARCHIVE.
fs.setStoragePolicy(barDir, "COLD");
//Stop DataNodes and restart namenode
List<DataNodeProperties> list = new ArrayList<>(numOfDatanodes);
for (int i = 0; i < numOfDatanodes; i++) {
list.add(cluster.stopDataNode(0));
}
cluster.restartNameNodes();
// Restart half datanodes
for (int i = 0; i < 5; i++) {
cluster.restartDataNode(list.get(i), false);
}
cluster.waitActive();
fs.satisfyStoragePolicy(fooFile);
DFSTestUtil.waitExpectedStorageType(fooFile.toString(),
StorageType.ARCHIVE, 5, 30000, cluster.getFileSystem());
//Start remaining datanodes
for (int i = numOfDatanodes - 1; i >= 5; i--) {
cluster.restartDataNode(list.get(i), false);
}
cluster.waitActive();
// verify storage types and locations.
waitExpectedStorageType(cluster, fooFile.toString(), fileLen,
StorageType.ARCHIVE, 9, 9, 60000);
} finally {
cluster.shutdown();
sps.stopGracefully();
}
}
/**
* Tests to verify that for the given path, no blocks under the given path
* will be scheduled for block movement as there are no available datanode
* with required storage type.
*
* For example, there are two block for a file:
*
* File1 => blk_1[locations=A(DISK),B(DISK),C(DISK)],
* blk_2[locations=A(DISK),B(DISK),C(DISK)]. Now, set storage policy to COLD.
* No datanode is available with storage type ARCHIVE.
*
* SPS won't schedule any block movement for this path.
*/
@Test
@Timeout(value = 300)
public void testWhenNoTargetDatanodeToSatisfyStoragePolicy()
throws Exception {
// start 10 datanodes
int numOfDatanodes = 10;
int storagesPerDatanode = 2;
long capacity = 20 * defaultStripeBlockSize;
long[][] capacities = new long[numOfDatanodes][storagesPerDatanode];
for (int i = 0; i < numOfDatanodes; i++) {
for (int j = 0; j < storagesPerDatanode; j++) {
capacities[i][j] = capacity;
}
}
final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(numOfDatanodes)
.storagesPerDatanode(storagesPerDatanode)
.storageTypes(new StorageType[][]{
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK},
{StorageType.DISK, StorageType.DISK}})
.storageCapacities(capacities)
.build();
HdfsAdmin hdfsAdmin = new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
try {
cluster.waitActive();
startSPS();
DistributedFileSystem dfs = cluster.getFileSystem();
dfs.enableErasureCodingPolicy(
StripedFileTestUtil.getDefaultECPolicy().getName());
// set "/bar" directory with HOT storage policy.
ClientProtocol client = NameNodeProxies.createProxy(conf,
cluster.getFileSystem(0).getUri(), ClientProtocol.class).getProxy();
String barDir = "/bar";
client.mkdirs(barDir, new FsPermission((short) 777), true);
client.setStoragePolicy(barDir, HdfsConstants.HOT_STORAGE_POLICY_NAME);
// set an EC policy on "/bar" directory
client.setErasureCodingPolicy(barDir,
StripedFileTestUtil.getDefaultECPolicy().getName());
// write file to barDir
final String fooFile = "/bar/foo";
long fileLen = cellSize * dataBlocks;
DFSTestUtil.createFile(cluster.getFileSystem(), new Path(fooFile),
fileLen, (short) 3, 0);
// verify storage types and locations
LocatedBlocks locatedBlocks = client.getBlockLocations(fooFile, 0,
fileLen);
for (LocatedBlock lb : locatedBlocks.getLocatedBlocks()) {
for (StorageType type : lb.getStorageTypes()) {
assertEquals(StorageType.DISK, type);
}
}
StripedFileTestUtil.verifyLocatedStripedBlocks(locatedBlocks,
dataBlocks + parityBlocks);
// Move file to ARCHIVE. Only 5 datanodes are available with ARCHIVE
// storage type.
client.setStoragePolicy(barDir, "COLD");
hdfsAdmin.satisfyStoragePolicy(new Path(fooFile));
LOG.info("Sets storage policy to COLD and invoked satisfyStoragePolicy");
cluster.triggerHeartbeats();
waitForAttemptedItems(1, 30000);
// verify storage types and locations.
waitExpectedStorageType(cluster, fooFile, fileLen, StorageType.DISK, 9, 9,
60000);
waitForAttemptedItems(1, 30000);
} finally {
cluster.shutdown();
sps.stopGracefully();
}
}
private void startSPS() throws IOException {
nnc = DFSTestUtil.getNameNodeConnector(conf,
HdfsServerConstants.MOVER_ID_PATH, 1, false);
sps = new StoragePolicySatisfier(conf);
ctxt = new ExternalSPSContext(sps, nnc);
sps.init(ctxt);
sps.start(StoragePolicySatisfierMode.EXTERNAL);
}
private static void initConfWithStripe(Configuration conf,
int stripeBlockSize) {
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, stripeBlockSize);
conf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1L);
conf.setLong(DFSConfigKeys.DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_KEY,
1L);
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_REDUNDANCY_CONSIDERLOAD_KEY,
false);
}
// Check whether the Block movement has been successfully completed to satisfy
// the storage policy for the given file.
private void waitExpectedStorageType(MiniDFSCluster cluster,
final String fileName, long fileLen,
final StorageType expectedStorageType, int expectedStorageCount,
int expectedBlkLocationCount, int timeout) throws Exception {
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
int actualStorageCount = 0;
try {
LocatedBlocks locatedBlocks = cluster.getFileSystem().getClient()
.getLocatedBlocks(fileName, 0, fileLen);
for (LocatedBlock lb : locatedBlocks.getLocatedBlocks()) {
LOG.info("LocatedBlocks => Size {}, locs {}",
lb.getLocations().length, lb);
if (lb.getLocations().length > expectedBlkLocationCount) {
return false;
}
for (StorageType storageType : lb.getStorageTypes()) {
if (expectedStorageType == storageType) {
actualStorageCount++;
} else {
LOG.info("Expected storage type {} and actual {}",
expectedStorageType, storageType);
}
}
}
LOG.info(
expectedStorageType + " replica count, expected={} and actual={}",
expectedStorageCount, actualStorageCount);
} catch (IOException e) {
LOG.error("Exception while getting located blocks", e);
return false;
}
return expectedStorageCount == actualStorageCount;
}
}, 100, timeout);
}
private void waitForAttemptedItems(long expectedBlkMovAttemptedCount,
int timeout) throws TimeoutException, InterruptedException {
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
LOG.info("expectedAttemptedItemsCount={} actualAttemptedItemsCount={}",
expectedBlkMovAttemptedCount,
((BlockStorageMovementAttemptedItems) (sps
.getAttemptedItemsMonitor())).getAttemptedItemsCount());
return ((BlockStorageMovementAttemptedItems) (sps
.getAttemptedItemsMonitor()))
.getAttemptedItemsCount() == expectedBlkMovAttemptedCount;
}
}, 100, timeout);
}
}
| TestStoragePolicySatisfierWithStripedFile |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/FileInputWithDeleteTest.java | {
"start": 661,
"end": 2372
} | class ____ extends AbstractMultipartTest {
private static final java.nio.file.Path uploadDir = Paths.get("file-uploads");
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(Resource.class)
.addAsResource(new StringAsset(
"quarkus.http.body.uploads-directory="
+ uploadDir.toString() + "\n"),
"application.properties");
}
});
private final File HTML_FILE = new File("./src/test/resources/test.html");
private final File HTML_FILE2 = new File("./src/test/resources/test2.html");
@Test
public void test() throws IOException {
RestAssured.given()
.contentType("application/octet-stream")
.body(HTML_FILE)
.when()
.post("/test")
.then()
.statusCode(200)
.body(equalTo(fileSizeAsStr(HTML_FILE)));
awaitUploadDirectoryToEmpty(uploadDir);
RestAssured.given()
.contentType("application/octet-stream")
.body(HTML_FILE2)
.when()
.post("/test")
.then()
.statusCode(200)
.body(equalTo(fileSizeAsStr(HTML_FILE2)));
awaitUploadDirectoryToEmpty(uploadDir);
}
@Path("test")
public static | FileInputWithDeleteTest |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/api/AbstractIterableAssert.java | {
"start": 126234,
"end": 129742
} | class ____ 'first' and 'last' String properties
*
* // name is null for noname => it does not match the filter on "name.first"
* assertThat(employees).filteredOn("name.first", "Luke")
* .containsOnly(luke);
*
* assertThat(employees).filteredOn("name.last", "Vader")
* .isEmpty();</code></pre>
* <p>
* If you want to filter on null value, use {@link #filteredOnNull(String)} as Java will resolve the call to
* {@link #filteredOn(String, FilterOperator)} instead of this method.
* <p>
* An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the iterable
* elements.
* <p>
* You can chain filters:
* <pre><code class='java'> // fellowshipOfTheRing is a list of TolkienCharacter having race and name fields
* // 'not' filter is statically imported from Assertions.not
*
* assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")
* .filteredOn("name", not("Boromir"))
* .containsOnly(aragorn);</code></pre>
*
* If you need more complex filter, use {@link #filteredOn(Predicate)} or {@link #filteredOn(Condition)}.
*
* @param propertyOrFieldName the name of the property or field to read
* @param expectedValue the value to compare element's property or field with
* @return a new assertion object with the filtered iterable under test
* @throws IllegalArgumentException if the given propertyOrFieldName is {@code null} or empty.
* @throws IntrospectionError if the given propertyOrFieldName can't be found in one of the iterable elements.
*/
@CheckReturnValue
public SELF filteredOn(String propertyOrFieldName, Object expectedValue) {
Filters<? extends ELEMENT> filter = filter((Iterable<? extends ELEMENT>) actual);
Iterable<? extends ELEMENT> filteredIterable = filter.with(propertyOrFieldName, expectedValue).get();
return newAbstractIterableAssert(filteredIterable).withAssertionState(myself);
}
/**
* Filters the iterable under test keeping only elements whose property or field specified by
* {@code propertyOrFieldName} is null.
* <p>
* The filter first tries to get the value from a property (named {@code propertyOrFieldName}), if no such property
* exists it tries to read the value from a field. Reading private fields is supported by default, this can be
* globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)
* Assertions.setAllowExtractingPrivateFields(false)}.
* <p>
* When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is
* considered to be null, thus reading "address.street.name" value will return null if "street" value is null.
* <p>
* As an example, let's check all employees 800 years old (yes, special employees):
* <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);
* Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
* Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
* Employee noname = new Employee(4L, null, 50);
*
* List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
*
* assertThat(employees).filteredOnNull("name")
* .containsOnly(noname);</code></pre>
*
* Nested properties/fields are supported:
* <pre><code class='java'> // Name is bean | with |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlBaseParser.java | {
"start": 87322,
"end": 92797
} | class ____ extends ParserRuleContext {
public BooleanExpressionContext where;
public BooleanExpressionContext having;
public TerminalNode SELECT() {
return getToken(SqlBaseParser.SELECT, 0);
}
public SelectItemsContext selectItems() {
return getRuleContext(SelectItemsContext.class, 0);
}
public TopClauseContext topClause() {
return getRuleContext(TopClauseContext.class, 0);
}
public SetQuantifierContext setQuantifier() {
return getRuleContext(SetQuantifierContext.class, 0);
}
public FromClauseContext fromClause() {
return getRuleContext(FromClauseContext.class, 0);
}
public TerminalNode WHERE() {
return getToken(SqlBaseParser.WHERE, 0);
}
public TerminalNode GROUP() {
return getToken(SqlBaseParser.GROUP, 0);
}
public TerminalNode BY() {
return getToken(SqlBaseParser.BY, 0);
}
public GroupByContext groupBy() {
return getRuleContext(GroupByContext.class, 0);
}
public TerminalNode HAVING() {
return getToken(SqlBaseParser.HAVING, 0);
}
public List<BooleanExpressionContext> booleanExpression() {
return getRuleContexts(BooleanExpressionContext.class);
}
public BooleanExpressionContext booleanExpression(int i) {
return getRuleContext(BooleanExpressionContext.class, i);
}
public QuerySpecificationContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override
public int getRuleIndex() {
return RULE_querySpecification;
}
@Override
public void enterRule(ParseTreeListener listener) {
if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).enterQuerySpecification(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).exitQuerySpecification(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if (visitor instanceof SqlBaseVisitor) return ((SqlBaseVisitor<? extends T>) visitor).visitQuerySpecification(this);
else return visitor.visitChildren(this);
}
}
public final QuerySpecificationContext querySpecification() throws RecognitionException {
QuerySpecificationContext _localctx = new QuerySpecificationContext(_ctx, getState());
enterRule(_localctx, 16, RULE_querySpecification);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(309);
match(SELECT);
setState(311);
_errHandler.sync(this);
switch (getInterpreter().adaptivePredict(_input, 36, _ctx)) {
case 1: {
setState(310);
topClause();
}
break;
}
setState(314);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la == ALL || _la == DISTINCT) {
{
setState(313);
setQuantifier();
}
}
setState(316);
selectItems();
setState(318);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la == FROM) {
{
setState(317);
fromClause();
}
}
setState(322);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la == WHERE) {
{
setState(320);
match(WHERE);
setState(321);
((QuerySpecificationContext) _localctx).where = booleanExpression(0);
}
}
setState(327);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la == GROUP) {
{
setState(324);
match(GROUP);
setState(325);
match(BY);
setState(326);
groupBy();
}
}
setState(331);
_errHandler.sync(this);
_la = _input.LA(1);
if (_la == HAVING) {
{
setState(329);
match(HAVING);
setState(330);
((QuerySpecificationContext) _localctx).having = booleanExpression(0);
}
}
}
} catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
} finally {
exitRule();
}
return _localctx;
}
@SuppressWarnings("CheckReturnValue")
public static | QuerySpecificationContext |
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/container/ContainerResourceFailedEvent.java | {
"start": 1048,
"end": 1471
} | class ____ extends ContainerResourceEvent {
private final String diagnosticMesage;
public ContainerResourceFailedEvent(ContainerId container,
LocalResourceRequest rsrc, String diagnosticMesage) {
super(container, ContainerEventType.RESOURCE_FAILED, rsrc);
this.diagnosticMesage = diagnosticMesage;
}
public String getDiagnosticMessage() {
return diagnosticMesage;
}
}
| ContainerResourceFailedEvent |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/internal/tls/SslContextManager.java | {
"start": 11821,
"end": 12616
} | class ____ {
private final KeyManagerFactory keyManagerFactory;
private final TrustManagerFactory trustManagerFactory;
private final Function<String, KeyManagerFactory> keyManagerFactoryMapper;
private final Function<String, TrustManager[]> trustManagerMapper;
private final List<CRL> crls;
public Config(KeyManagerFactory keyManagerFactory, TrustManagerFactory trustManagerFactory, Function<String, KeyManagerFactory> keyManagerFactoryMapper, Function<String, TrustManager[]> trustManagerMapper, List<CRL> crls) {
this.keyManagerFactory = keyManagerFactory;
this.trustManagerFactory = trustManagerFactory;
this.keyManagerFactoryMapper = keyManagerFactoryMapper;
this.trustManagerMapper = trustManagerMapper;
this.crls = crls;
}
}
}
| Config |
java | elastic__elasticsearch | libs/logstash-bridge/src/main/java/org/elasticsearch/logstashbridge/geoip/IpDatabaseProviderBridge.java | {
"start": 709,
"end": 876
} | interface ____ extends StableBridgeAPI<IpDatabaseProvider> {
Boolean isValid(String name);
IpDatabaseBridge getDatabase(String name);
}
| IpDatabaseProviderBridge |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneUniqueJoinColumnsTest.java | {
"start": 3902,
"end": 4880
} | class ____ extends BaseEntity {
@Column( name = "columnAEntityB" )
public Long columnAEntityB;
@Column( name = "columnBEntityB" )
public Long columnBEntityB;
@OneToOne( fetch = FetchType.LAZY )
@JoinColumns( {
@JoinColumn( name = "columnAEntityB", referencedColumnName = "columnAEntityA", insertable = false, updatable = false ),
@JoinColumn( name = "columnBEntityB", referencedColumnName = "columnBEntityA", insertable = false, updatable = false )
} )
public EntityA entityA;
public Long getColumnAEntityB() {
return columnAEntityB;
}
public void setColumnAEntityB(Long columnAEntityB) {
this.columnAEntityB = columnAEntityB;
}
public Long getColumnBEntityB() {
return columnBEntityB;
}
public void setColumnBEntityB(Long columnBEntityB) {
this.columnBEntityB = columnBEntityB;
}
public EntityA getEntityA() {
return entityA;
}
public void setEntityA(EntityA entityA) {
this.entityA = entityA;
}
}
}
| EntityB |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/project/ProjectResolver.java | {
"start": 1054,
"end": 4040
} | interface ____ extends ProjectIdResolver {
default ProjectMetadata getProjectMetadata(Metadata metadata) {
return metadata.getProject(getProjectId());
}
default ProjectMetadata getProjectMetadata(ClusterState clusterState) {
return getProjectMetadata(clusterState.metadata());
}
default boolean hasProject(ClusterState clusterState) {
return hasProject(clusterState.metadata());
}
default boolean hasProject(Metadata metadata) {
return metadata.hasProject(getProjectId());
}
// TODO: What happens if the context does not have a project? throw or return null?
default ProjectState getProjectState(ClusterState clusterState) {
final ProjectId id = getProjectId();
final ProjectState projectState = clusterState.projectState(id);
assert projectState != null : "Received null project state for [" + id + "] from " + clusterState;
return projectState;
}
/**
* Returns the identifiers of all projects on which this request should operate.
* In practice, this will either be:
* <ul>
* <li>If the request is tied to a single project, then a collection with a single item that is the same as
* {@link #getProjectId()} if the project exists in the cluster state</li>
* <li>If the request is not tied to a single project and it is allowed to access all projects,
* then a collection of all the project ids in the cluster</li>
* <li>Otherwise an exception is thrown</li>
* </ul>
* @return A readonly collection of all the project ids on which this request should operate
* @throws SecurityException if this request is required to provide a project id, but none was provided
*/
default Collection<ProjectId> getProjectIds(ClusterState clusterState) {
final ProjectId projectId = Objects.requireNonNull(getProjectId());
if (clusterState.metadata().hasProject(projectId) == false) {
throw new IllegalArgumentException("Project [" + projectId + "] does not exist");
}
return Set.of(getProjectId());
}
/**
* Execute a block in the context of a specific project.
*
* This method: <ol>
* <li> Configures the execution (thread) context so that any calls to resolve a project (e.g. {@link #getProjectId()}
* or {@link #getProjectMetadata(Metadata)}) will return the project specified by {@code projectId}.</li>
* <li>Executes the {@link CheckedRunnable#run()} method on the supplied {@code body}</li>
* <li>Restores the context to its original state</li>
* </ol>
*
* @throws IllegalStateException If there is already a project-id set in the execution context.
* It is an error to attempt to override the active project-id
*/
<E extends Exception> void executeOnProject(ProjectId projectId, CheckedRunnable<E> body) throws E;
}
| ProjectResolver |
java | apache__camel | components/camel-ai/camel-torchserve/src/main/java/org/apache/camel/component/torchserve/client/Inference.java | {
"start": 1094,
"end": 1768
} | interface ____ {
/**
* Get openapi description.
*/
Api apiDescription() throws ApiException;
/**
* Get TorchServe status.
*/
Response ping() throws ApiException;
/**
* Predictions entry point to get inference using default model version.
*/
Object predictions(String modelName, Object body) throws ApiException;
/**
* Predictions entry point to get inference using specific model version.
*/
Object predictions(String modelName, String modelVersion, Object body) throws ApiException;
/**
* Not supported yet.
*/
Object explanations(String modelName) throws ApiException;
}
| Inference |
java | google__guice | extensions/testlib/test/com/google/inject/testing/fieldbinder/BoundFieldModuleTest.java | {
"start": 28654,
"end": 29447
} | class ____ {
@Bind(lazy = true)
Provider<Integer> foo = Providers.of(null);
}
public void testFieldBoundAsProvider_lazy() {
LazyProviderClass asProvider = new LazyProviderClass();
Provider<Integer> provider =
Guice.createInjector(BoundFieldModule.of(asProvider)).getProvider(Integer.class);
assertNull(provider.get());
asProvider.foo = Providers.of(1);
assertEquals(1, provider.get().intValue());
asProvider.foo =
new Provider<Integer>() {
@Override
public Integer get() {
throw new RuntimeException("boom");
}
};
try {
provider.get();
fail();
} catch (ProvisionException e) {
assertContains(e.getMessage(), "boom");
}
}
private static final | LazyProviderClass |
java | spring-projects__spring-boot | module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/management/ThreadDumpEndpointAutoConfiguration.java | {
"start": 1372,
"end": 1529
} | class ____ {
@Bean
@ConditionalOnMissingBean
ThreadDumpEndpoint dumpEndpoint() {
return new ThreadDumpEndpoint();
}
}
| ThreadDumpEndpointAutoConfiguration |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/component/ApiMethodPropertiesHelper.java | {
"start": 1396,
"end": 8393
} | class ____<C> {
protected static final Logger LOG = LoggerFactory.getLogger(ApiMethodPropertiesHelper.class);
// set of field names which are specific to the api, to be excluded from method argument considerations
protected final Set<String> componentConfigFields = new HashSet<>();
protected final Class<?> componentConfigClass;
protected final String propertyPrefix;
private final int prefixLength;
private final String camelCasePrefix;
protected ApiMethodPropertiesHelper(CamelContext context, Class<C> componentConfiguration, String propertyPrefix) {
this.componentConfigClass = componentConfiguration;
this.propertyPrefix = propertyPrefix;
this.prefixLength = propertyPrefix.length();
if (!Character.isLetterOrDigit(propertyPrefix.charAt(prefixLength - 1))) {
this.camelCasePrefix = propertyPrefix.substring(0, prefixLength - 1);
} else {
this.camelCasePrefix = null;
}
// use reflection free configurer (if possible)
PropertyConfigurer configurer = PluginHelper.getConfigurerResolver(context)
.resolvePropertyConfigurer(componentConfiguration.getName(), context);
if (configurer instanceof ExtendedPropertyConfigurerGetter getter) {
Set<String> names = getter.getAllOptions(null).keySet();
for (String name : names) {
// lower case the first letter which is what the properties map expects
String key = Character.toLowerCase(name.charAt(0)) + name.substring(1);
componentConfigFields.add(key);
}
} else {
// fallback to be reflection based
for (Field field : componentConfiguration.getDeclaredFields()) {
componentConfigFields.add(field.getName());
}
}
}
/**
* Gets exchange header properties that start with propertyPrefix.
*
* @param exchange Camel exchange
* @param properties map to collect properties with required prefix
*/
public Map<String, Object> getExchangeProperties(Exchange exchange, Map<String, Object> properties) {
int nProperties = 0;
for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
final String key = entry.getKey();
if (key.startsWith(propertyPrefix)) {
properties.put(key.substring(prefixLength),
entry.getValue());
nProperties++;
} else if (camelCasePrefix != null && key.startsWith(camelCasePrefix)) {
// assuming all property names start with a lowercase character
final String propertyName = Character.toLowerCase(key.charAt(prefixLength - 1))
+ key.substring(prefixLength);
properties.put(propertyName, entry.getValue());
nProperties++;
}
}
LOG.debug("Found {} properties in exchange", nProperties);
return properties;
}
public void getEndpointProperties(CamelContext context, Object endpointConfiguration, Map<String, Object> properties) {
PropertyConfigurer configurer = PluginHelper.getConfigurerResolver(context)
.resolvePropertyConfigurer(endpointConfiguration.getClass().getName(), context);
// use reflection free configurer (if possible)
if (configurer instanceof ExtendedPropertyConfigurerGetter getter) {
useGetters(endpointConfiguration, properties, getter);
} else {
PluginHelper.getBeanIntrospection(context).getProperties(endpointConfiguration, properties,
null, false);
}
// remove component config properties so we only have endpoint properties
for (String key : componentConfigFields) {
properties.remove(key);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Found endpoint properties {}", properties.keySet());
}
}
public Set<String> getEndpointPropertyNames(CamelContext context, Object endpointConfiguration) {
Map<String, Object> properties = new HashMap<>();
getEndpointProperties(context, endpointConfiguration, properties);
return Collections.unmodifiableSet(properties.keySet());
}
public Set<String> getValidEndpointProperties(CamelContext context, Object endpointConfiguration) {
Set<String> fields = new HashSet<>();
PropertyConfigurer configurer = PluginHelper.getConfigurerResolver(context)
.resolvePropertyConfigurer(endpointConfiguration.getClass().getName(), context);
// use reflection free configurer (if possible)
if (configurer instanceof ExtendedPropertyConfigurerGetter getter) {
Set<String> names = getter.getAllOptions(endpointConfiguration).keySet();
for (String name : names) {
// lower case the first letter which is what the properties map expects
String key = Character.toLowerCase(name.charAt(0)) + name.substring(1);
fields.add(key);
}
} else {
// fallback to use reflection
for (Field field : endpointConfiguration.getClass().getDeclaredFields()) {
fields.add(field.getName());
}
}
return Collections.unmodifiableSet(fields);
}
public void getConfigurationProperties(CamelContext context, Object endpointConfiguration, Map<String, Object> properties) {
PropertyConfigurer configurer = PluginHelper.getConfigurerResolver(context)
.resolvePropertyConfigurer(endpointConfiguration.getClass().getName(), context);
// use reflection free configurer (if possible)
if (configurer instanceof ExtendedPropertyConfigurerGetter getter) {
useGetters(endpointConfiguration, properties, getter);
} else {
PluginHelper.getBeanIntrospection(context).getProperties(endpointConfiguration, properties,
null, false);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Found configuration properties {}", properties.keySet());
}
}
private static void useGetters(
Object endpointConfiguration, Map<String, Object> properties, ExtendedPropertyConfigurerGetter configurer) {
ExtendedPropertyConfigurerGetter getter = configurer;
Set<String> all = getter.getAllOptions(endpointConfiguration).keySet();
for (String name : all) {
Object value = getter.getOptionValue(endpointConfiguration, name, true);
if (value != null) {
// lower case the first letter which is what the properties map expects
String key = Character.toLowerCase(name.charAt(0)) + name.substring(1);
properties.put(key, value);
}
}
}
}
| ApiMethodPropertiesHelper |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/cluster/metadata/SelectorResolverTests.java | {
"start": 1504,
"end": 14543
} | class ____ extends ESTestCase {
public void testResolveExpression() {
// === Parsing and defaults
// Allow selectors TRUE
Context selectorsAllowed = getContext(getOptionsForSelectors());
assertThat(resolve(selectorsAllowed, "testXXX"), equalTo(new ResolvedExpression("testXXX", DATA)));
assertThat(resolve(selectorsAllowed, "testXXX::data"), equalTo(new ResolvedExpression("testXXX", DATA)));
assertThat(resolve(selectorsAllowed, "testXXX::failures"), equalTo(new ResolvedExpression("testXXX", FAILURES)));
// Disallow selectors (example: creating, modifying, or deleting indices/data streams/aliases).
// Accepts standard expressions but throws when selectors are specified.
Context noSelectors = getContext(getDisabledSelectorOptions());
assertThat(resolve(noSelectors, "testXXX"), equalTo(new ResolvedExpression("testXXX")));
expectThrows(IllegalArgumentException.class, () -> resolve(noSelectors, "testXXX::data"));
expectThrows(IllegalArgumentException.class, () -> resolve(noSelectors, "testXXX::failures"));
// === Errors
// Only recognized components can be selected
expectThrows(InvalidIndexNameException.class, () -> resolve(selectorsAllowed, "testXXX::custom"));
// Spelling is important
expectThrows(InvalidIndexNameException.class, () -> resolve(selectorsAllowed, "testXXX::failres"));
// Only the match all wildcard is supported
expectThrows(InvalidIndexNameException.class, () -> resolve(selectorsAllowed, "testXXX::d*ta"));
// Only one selector separator is allowed per expression
expectThrows(InvalidIndexNameException.class, () -> resolve(selectorsAllowed, "test::XXX::data"));
// === Wildcards, Date Math, and edge cases
// Wildcards are left as-is (handled in wildcard resolver)
assertThat(resolve(selectorsAllowed, "*"), equalTo(new ResolvedExpression("*", DATA)));
// Exclusions are left as-is (if no wildcards are present they are not treated as exclusions)
assertThat(resolve(selectorsAllowed, "-testXXX"), equalTo(new ResolvedExpression("-testXXX", DATA)));
// Exclusion syntax with selectors will have the selectors parsed
assertThat(resolve(selectorsAllowed, "-testXXX::failures"), equalTo(new ResolvedExpression("-testXXX", FAILURES)));
// Date math is left unprocessed (handled later in date math resolver)
assertThat(resolve(selectorsAllowed, "<test-{now/d}>"), equalTo(new ResolvedExpression("<test-{now/d}>", DATA)));
// Providing a selector requires adding after the date math brackets
assertThat(resolve(selectorsAllowed, "<test-{now/d}>::failures"), equalTo(new ResolvedExpression("<test-{now/d}>", FAILURES)));
// Selectors inside of date math expressions will trip an exception because they do not match an existing component name exactly
expectThrows(InvalidIndexNameException.class, () -> resolve(selectorsAllowed, "<test-{now/d}::failures>"));
// === Corner Cases
// Empty index name is not necessarily disallowed, but will be filtered out in the next steps of resolution
assertThat(resolve(selectorsAllowed, "::data"), equalTo(new ResolvedExpression("", DATA)));
assertThat(resolve(selectorsAllowed, "::failures"), equalTo(new ResolvedExpression("", FAILURES)));
// CCS with an empty index and cluster name is not necessarily disallowed, though other code in the resolution logic will likely
// throw
assertThat(resolve(selectorsAllowed, ":::data"), equalTo(new ResolvedExpression(":", DATA)));
assertThat(resolve(selectorsAllowed, ":::failures"), equalTo(new ResolvedExpression(":", FAILURES)));
// Any more prefix colon characters will trigger the multiple separators error logic
expectThrows(InvalidIndexNameException.class, () -> resolve(selectorsAllowed, "::::data"));
expectThrows(InvalidIndexNameException.class, () -> resolve(selectorsAllowed, "::::failures"));
expectThrows(InvalidIndexNameException.class, () -> resolve(selectorsAllowed, ":::::failures"));
// Suffix case is not supported because there is no component named with the empty string
expectThrows(InvalidIndexNameException.class, () -> resolve(selectorsAllowed, "index::"));
// remote cluster syntax is not allowed with :: selectors
final Set<String> remoteClusterExpressionsWithSelectors = Set.of(
"cluster:index::failures",
"cluster-*:index::failures",
"cluster-*:index-*::failures",
"cluster-*:*::failures",
"*:index-*::failures",
"*:*::failures",
"*:-test*,*::failures",
"cluster:::failures",
"failures:index::failures",
"data:index::failures",
"failures:failures::failures",
"data:data::failures",
"cluster:index::data",
"cluster-*:index::data",
"cluster-*:index-*::data",
"cluster-*:*::data",
"*:index-*::data",
"*:*::data",
"cluster:::data",
"failures:index::data",
"data:index::data",
"failures:failures::data",
"data:data::data",
"*:-test*,*::data"
);
for (String expression : remoteClusterExpressionsWithSelectors) {
var e = expectThrows(InvalidIndexNameException.class, () -> resolve(selectorsAllowed, expression));
assertThat(e.getMessage(), containsString("Selectors are not yet supported on remote cluster patterns"));
}
}
public void testResolveMatchAllToSelectors() {
Context selectorsAllowed = getContext(getOptionsForSelectors());
assertThat(resolveMatchAllToSelector(selectorsAllowed, "*"), is(DATA));
assertThat(resolveMatchAllToSelector(selectorsAllowed, "*::data"), is(DATA));
assertThat(resolveMatchAllToSelector(selectorsAllowed, "*::failures"), is(FAILURES));
assertThat(resolveMatchAllToSelector(selectorsAllowed, "_all"), is(DATA));
assertThat(resolveMatchAllToSelector(selectorsAllowed, "_all::data"), is(DATA));
assertThat(resolveMatchAllToSelector(selectorsAllowed, "_all::failures"), is(FAILURES));
Context selectorsDisallowed = getContext(getDisabledSelectorOptions());
assertThat(resolveMatchAllToSelector(selectorsDisallowed, "*"), is(nullValue()));
expectThrows(IllegalArgumentException.class, () -> resolveMatchAllToSelector(selectorsDisallowed, "*::data"));
expectThrows(IllegalArgumentException.class, () -> resolveMatchAllToSelector(selectorsDisallowed, "*::failures"));
assertThat(resolveMatchAllToSelector(selectorsDisallowed, "_all"), is(nullValue()));
expectThrows(IllegalArgumentException.class, () -> resolveMatchAllToSelector(selectorsDisallowed, "_all::data"));
expectThrows(IllegalArgumentException.class, () -> resolveMatchAllToSelector(selectorsDisallowed, "_all::failures"));
}
public void testCombineExpressionWithSelector() {
expectThrows(NullPointerException.class, () -> IndexNameExpressionResolver.combineSelectorExpression(null, null));
expectThrows(NullPointerException.class, () -> IndexNameExpressionResolver.combineSelectorExpression(null, ""));
expectThrows(NullPointerException.class, () -> IndexNameExpressionResolver.combineSelectorExpression(null, "a"));
expectThrows(NullPointerException.class, () -> IndexNameExpressionResolver.combineSelectorExpression(null, "*"));
assertThat(IndexNameExpressionResolver.combineSelectorExpression("", null), is(equalTo("")));
assertThat(IndexNameExpressionResolver.combineSelectorExpression("", ""), is(equalTo("::")));
assertThat(IndexNameExpressionResolver.combineSelectorExpression("a", null), is(equalTo("a")));
assertThat(IndexNameExpressionResolver.combineSelectorExpression("a", ""), is(equalTo("a::")));
assertThat(IndexNameExpressionResolver.combineSelectorExpression("a", "b"), is(equalTo("a::b")));
assertThat(IndexNameExpressionResolver.combineSelectorExpression("*", "b"), is(equalTo("*::b")));
}
public void testHasSelectorSuffix() {
assertThat(IndexNameExpressionResolver.hasSelectorSuffix(null), is(false));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix(""), is(false));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("abcdefg"), is(false));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("*"), is(false));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("cluster:index"), is(false));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("index::data"), is(true));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("index::failures"), is(true));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("index::any"), is(true));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("index::*"), is(true));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("index::::::::::toomany"), is(true));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("cluster:index::data"), is(true));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("*:*::*"), is(true));
assertThat(IndexNameExpressionResolver.hasSelectorSuffix("index::value::value"), is(true));
}
public void testSplitSelectorExpression() {
expectThrows(NullPointerException.class, () -> IndexNameExpressionResolver.splitSelectorExpression(null));
assertThat(IndexNameExpressionResolver.splitSelectorExpression(""), is(equalTo(new Tuple<>("", null))));
assertThat(IndexNameExpressionResolver.splitSelectorExpression("a"), is(equalTo(new Tuple<>("a", null))));
assertThat(IndexNameExpressionResolver.splitSelectorExpression("*"), is(equalTo(new Tuple<>("*", null))));
assertThat(IndexNameExpressionResolver.splitSelectorExpression("index"), is(equalTo(new Tuple<>("index", null))));
assertThat(IndexNameExpressionResolver.splitSelectorExpression("cluster:index"), is(equalTo(new Tuple<>("cluster:index", null))));
assertThat(IndexNameExpressionResolver.splitSelectorExpression("*:index"), is(equalTo(new Tuple<>("*:index", null))));
assertThat(IndexNameExpressionResolver.splitSelectorExpression("cluster:*"), is(equalTo(new Tuple<>("cluster:*", null))));
assertThat(IndexNameExpressionResolver.splitSelectorExpression("*:*"), is(equalTo(new Tuple<>("*:*", null))));
assertThat(IndexNameExpressionResolver.splitSelectorExpression("*:*:*"), is(equalTo(new Tuple<>("*:*:*", null))));
assertThat(IndexNameExpressionResolver.splitSelectorExpression("a::data"), is(equalTo(new Tuple<>("a", "data"))));
assertThat(IndexNameExpressionResolver.splitSelectorExpression("a::failures"), is(equalTo(new Tuple<>("a", "failures"))));
expectThrows(InvalidIndexNameException.class, () -> IndexNameExpressionResolver.splitSelectorExpression("a::*"));
expectThrows(InvalidIndexNameException.class, () -> IndexNameExpressionResolver.splitSelectorExpression("a::random"));
expectThrows(InvalidIndexNameException.class, () -> IndexNameExpressionResolver.splitSelectorExpression("a::d*ta"));
expectThrows(InvalidIndexNameException.class, () -> IndexNameExpressionResolver.splitSelectorExpression("a::*ailures"));
expectThrows(InvalidIndexNameException.class, () -> IndexNameExpressionResolver.splitSelectorExpression("a::"));
expectThrows(InvalidIndexNameException.class, () -> IndexNameExpressionResolver.splitSelectorExpression("a::**"));
expectThrows(InvalidIndexNameException.class, () -> IndexNameExpressionResolver.splitSelectorExpression("index::data::*"));
expectThrows(InvalidIndexNameException.class, () -> IndexNameExpressionResolver.splitSelectorExpression("::*"));
}
private static IndicesOptions getOptionsForSelectors() {
return IndicesOptions.builder().gatekeeperOptions(IndicesOptions.GatekeeperOptions.builder().allowSelectors(true)).build();
}
private static IndicesOptions getDisabledSelectorOptions() {
return IndicesOptions.builder().gatekeeperOptions(IndicesOptions.GatekeeperOptions.builder().allowSelectors(false)).build();
}
private static Context getContext(IndicesOptions indicesOptions) {
return new Context(mock(ProjectMetadata.class), indicesOptions, SystemIndices.SystemIndexAccessLevel.NONE);
}
private static ResolvedExpression resolve(Context context, String expression) {
return SelectorResolver.parseExpression(expression, context.getOptions());
}
private static IndexComponentSelector resolveMatchAllToSelector(Context context, String matchAll) {
return SelectorResolver.parseMatchAllToSelector(context, matchAll);
}
}
| SelectorResolverTests |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java | {
"start": 44414,
"end": 45250
} | class ____ implements Serializable {
private Map<String, Child> children = new HashMap<String, Child>();
private List<Child> list = new ArrayList<Child>();
public List<Child> getList() {
return list;
}
public void setList(List<Child> list) {
if (CollectionUtils.isNotEmpty(list)) {
this.list.addAll(list);
}
}
public Map<String, Child> getChildren() {
return children;
}
public void setChildren(Map<String, Child> children) {
if (CollectionUtils.isNotEmptyMap(children)) {
this.children.putAll(children);
}
}
public void addChild(Child child) {
this.children.put(child.getName(), child);
}
}
public static | TestData |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/ResolvableType.java | {
"start": 37679,
"end": 37866
} | class ____ (analogous to
* {@link Class#isAssignableFrom}, which this serves as a wrapper for).
* <p>For example: {@code ResolvableType.forRawClass(List.class)}.
* @param clazz the | only |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/BidirectionalProxyTest.java | {
"start": 7474,
"end": 7961
} | class ____ extends AMappedSuperclass {
public AEntity(String id) {
super(id);
}
protected AEntity() {
}
@OneToMany(targetEntity=CEntity.class, mappedBy="aChildEntity", fetch=FetchType.LAZY)
protected Set<CEntity> cEntries = new LinkedHashSet();
public Set<CEntity> getcEntries() {
return cEntries;
}
public void setcEntries(Set<CEntity> cEntries) {
this.cEntries = cEntries;
}
}
@Entity(name="AChildEntity")
@Table(name="ACChild")
public static | AEntity |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/support/ProxyImageNameSubstitutor.java | {
"start": 1016,
"end": 2369
} | class ____ extends ImageNameSubstitutor {
private static final List<String> NAMES_TO_PROXY_PREFIX = List.of("ryuk");
private static final List<String> NAMES_TO_LIBRARY_PROXY_PREFIX = List.of("mysql", "postgres");
private static final String PROXY_PREFIX = "docker-hub.usw1.packages.broadcom.com/";
private static final String LIBRARY_PROXY_PREFIX = PROXY_PREFIX + "library/";
@Override
public DockerImageName apply(DockerImageName dockerImageName) {
if (NAMES_TO_PROXY_PREFIX.stream().anyMatch(s -> dockerImageName.asCanonicalNameString().contains(s))) {
return DockerImageName.parse(applyProxyPrefix(dockerImageName.asCanonicalNameString()));
}
if (NAMES_TO_LIBRARY_PROXY_PREFIX.stream().anyMatch(s -> dockerImageName.asCanonicalNameString().contains(s))) {
return DockerImageName.parse(applyProxyAndLibraryPrefix(dockerImageName.asCanonicalNameString()));
}
return dockerImageName;
}
@Override
protected String getDescription() {
return "Spring Data Proxy Image Name Substitutor";
}
/**
* Apply a non-library-based prefix.
*/
private static String applyProxyPrefix(String imageName) {
return PROXY_PREFIX + imageName;
}
/**
* Apply a library based prefix.
*/
private static String applyProxyAndLibraryPrefix(String imageName) {
return LIBRARY_PROXY_PREFIX + imageName;
}
}
| ProxyImageNameSubstitutor |
java | spring-projects__spring-security | cas/src/test/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetailsTests.java | {
"start": 1333,
"end": 5282
} | class ____ {
private DefaultServiceAuthenticationDetails details;
private MockHttpServletRequest request;
private Pattern artifactPattern;
private String casServiceUrl;
private ConfigurableApplicationContext context;
@BeforeEach
public void setUp() {
this.casServiceUrl = "https://localhost:8443/j_spring_security_cas";
this.request = new MockHttpServletRequest();
this.request.setScheme("https");
this.request.setServerName("localhost");
this.request.setServerPort(8443);
this.request.setRequestURI("/cas-sample/secure/");
this.artifactPattern = DefaultServiceAuthenticationDetails
.createArtifactPattern(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER);
}
@AfterEach
public void cleanup() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void getServiceUrlNullQuery() throws Exception {
this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern);
assertThat(this.details.getServiceUrl()).isEqualTo(UrlUtils.buildFullRequestUrl(this.request));
}
@Test
public void getServiceUrlTicketOnlyParam() throws Exception {
this.request.setQueryString("ticket=123");
this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern);
String serviceUrl = this.details.getServiceUrl();
this.request.setQueryString(null);
assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request));
}
@Test
public void getServiceUrlTicketFirstMultiParam() throws Exception {
this.request.setQueryString("ticket=123&other=value");
this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern);
String serviceUrl = this.details.getServiceUrl();
this.request.setQueryString("other=value");
assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request));
}
@Test
public void getServiceUrlTicketLastMultiParam() throws Exception {
this.request.setQueryString("other=value&ticket=123");
this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern);
String serviceUrl = this.details.getServiceUrl();
this.request.setQueryString("other=value");
assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request));
}
@Test
public void getServiceUrlTicketMiddleMultiParam() throws Exception {
this.request.setQueryString("other=value&ticket=123&last=this");
this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern);
String serviceUrl = this.details.getServiceUrl();
this.request.setQueryString("other=value&last=this");
assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request));
}
@Test
public void getServiceUrlDoesNotUseHostHeader() throws Exception {
this.casServiceUrl = "https://example.com/j_spring_security_cas";
this.request.setServerName("evil.com");
this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern);
assertThat(this.details.getServiceUrl()).isEqualTo("https://example.com/cas-sample/secure/");
}
@Test
public void getServiceUrlDoesNotUseHostHeaderExplicit() {
this.casServiceUrl = "https://example.com/j_spring_security_cas";
this.request.setServerName("evil.com");
ServiceAuthenticationDetails details = loadServiceAuthenticationDetails(
"defaultserviceauthenticationdetails-explicit.xml");
assertThat(details.getServiceUrl()).isEqualTo("https://example.com/cas-sample/secure/");
}
private ServiceAuthenticationDetails loadServiceAuthenticationDetails(String resourceName) {
this.context = new GenericXmlApplicationContext(getClass(), resourceName);
ServiceAuthenticationDetailsSource source = this.context.getBean(ServiceAuthenticationDetailsSource.class);
return source.buildDetails(this.request);
}
}
| DefaultServiceAuthenticationDetailsTests |
java | elastic__elasticsearch | x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/checkpoint/RemoteClusterResolver.java | {
"start": 752,
"end": 878
} | class ____ extends RemoteClusterAware {
private final CopyOnWriteArraySet<String> clusters;
static | RemoteClusterResolver |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java | {
"start": 8779,
"end": 9012
} | interface ____ by the proxy will be specified.
* <p><b>WARNING:</b> Review your proxy definitions when exposing a JDK dynamic
* proxy through JMX, in particular with this property turned to {@code true}:
* the specified | implemented |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/CbrtLongEvaluator.java | {
"start": 4177,
"end": 4746
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory val;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory val) {
this.source = source;
this.val = val;
}
@Override
public CbrtLongEvaluator get(DriverContext context) {
return new CbrtLongEvaluator(source, val.get(context), context);
}
@Override
public String toString() {
return "CbrtLongEvaluator[" + "val=" + val + "]";
}
}
}
| Factory |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/ZPopArgs.java | {
"start": 514,
"end": 684
} | class ____ implements CompositeArgument {
private ProtocolKeyword modifier;
/**
* Builder entry points for {@link ScanArgs}.
*/
public static | ZPopArgs |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/Join.java | {
"start": 2555,
"end": 7041
} | class ____ extends Configured implements Tool {
public static final String REDUCES_PER_HOST = "mapreduce.join.reduces_per_host";
static int printUsage() {
System.out.println("join [-r <reduces>] " +
"[-inFormat <input format class>] " +
"[-outFormat <output format class>] " +
"[-outKey <output key class>] " +
"[-outValue <output value class>] " +
"[-joinOp <inner|outer|override>] " +
"[input]* <input> <output>");
ToolRunner.printGenericCommandUsage(System.out);
return 2;
}
/**
* The main driver for sort program.
* Invoke this method to submit the map/reduce job.
* @throws IOException When there is communication problems with the
* job tracker.
*/
@SuppressWarnings("unchecked")
public int run(String[] args) throws Exception {
Configuration conf = getConf();
JobClient client = new JobClient(conf);
ClusterStatus cluster = client.getClusterStatus();
int num_reduces = (int) (cluster.getMaxReduceTasks() * 0.9);
String join_reduces = conf.get(REDUCES_PER_HOST);
if (join_reduces != null) {
num_reduces = cluster.getTaskTrackers() *
Integer.parseInt(join_reduces);
}
Job job = Job.getInstance(conf);
job.setJobName("join");
job.setJarByClass(Sort.class);
job.setMapperClass(Mapper.class);
job.setReducerClass(Reducer.class);
Class<? extends InputFormat> inputFormatClass =
SequenceFileInputFormat.class;
Class<? extends OutputFormat> outputFormatClass =
SequenceFileOutputFormat.class;
Class<? extends WritableComparable> outputKeyClass = BytesWritable.class;
Class<? extends Writable> outputValueClass = TupleWritable.class;
String op = "inner";
List<String> otherArgs = new ArrayList<String>();
for(int i=0; i < args.length; ++i) {
try {
if ("-r".equals(args[i])) {
num_reduces = Integer.parseInt(args[++i]);
} else if ("-inFormat".equals(args[i])) {
inputFormatClass =
Class.forName(args[++i]).asSubclass(InputFormat.class);
} else if ("-outFormat".equals(args[i])) {
outputFormatClass =
Class.forName(args[++i]).asSubclass(OutputFormat.class);
} else if ("-outKey".equals(args[i])) {
outputKeyClass =
Class.forName(args[++i]).asSubclass(WritableComparable.class);
} else if ("-outValue".equals(args[i])) {
outputValueClass =
Class.forName(args[++i]).asSubclass(Writable.class);
} else if ("-joinOp".equals(args[i])) {
op = args[++i];
} else {
otherArgs.add(args[i]);
}
} catch (NumberFormatException except) {
System.out.println("ERROR: Integer expected instead of " + args[i]);
return printUsage();
} catch (ArrayIndexOutOfBoundsException except) {
System.out.println("ERROR: Required parameter missing from " +
args[i-1]);
return printUsage(); // exits
}
}
// Set user-supplied (possibly default) job configs
job.setNumReduceTasks(num_reduces);
if (otherArgs.size() < 2) {
System.out.println("ERROR: Wrong number of parameters: ");
return printUsage();
}
FileOutputFormat.setOutputPath(job,
new Path(otherArgs.remove(otherArgs.size() - 1)));
List<Path> plist = new ArrayList<Path>(otherArgs.size());
for (String s : otherArgs) {
plist.add(new Path(s));
}
job.setInputFormatClass(CompositeInputFormat.class);
job.getConfiguration().set(CompositeInputFormat.JOIN_EXPR,
CompositeInputFormat.compose(op, inputFormatClass,
plist.toArray(new Path[0])));
job.setOutputFormatClass(outputFormatClass);
job.setOutputKeyClass(outputKeyClass);
job.setOutputValueClass(outputValueClass);
Date startTime = new Date();
System.out.println("Job started: " + startTime);
int ret = job.waitForCompletion(true) ? 0 : 1 ;
Date end_time = new Date();
System.out.println("Job ended: " + end_time);
System.out.println("The job took " +
(end_time.getTime() - startTime.getTime()) /1000 + " seconds.");
return ret;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new Join(), args);
System.exit(res);
}
}
| Join |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/loadbalancer/StickyLoadBalancerDefinition.java | {
"start": 1599,
"end": 3034
} | class ____ extends LoadBalancerDefinition {
@XmlElement(name = "correlationExpression", required = true)
private ExpressionSubElementDefinition correlationExpression;
public StickyLoadBalancerDefinition() {
}
protected StickyLoadBalancerDefinition(StickyLoadBalancerDefinition source) {
super(source);
this.correlationExpression
= source.correlationExpression != null ? source.correlationExpression.copyDefinition() : null;
}
@Override
public StickyLoadBalancerDefinition copyDefinition() {
return new StickyLoadBalancerDefinition(this);
}
public ExpressionSubElementDefinition getCorrelationExpression() {
return correlationExpression;
}
/**
* The correlation expression to use to calculate the correlation key
*/
public void setCorrelationExpression(ExpressionSubElementDefinition correlationExpression) {
this.correlationExpression = correlationExpression;
}
public void setCorrelationExpression(Expression expression) {
ExpressionDefinition def = ExpressionNodeHelper.toExpressionDefinition(expression);
this.correlationExpression = new ExpressionSubElementDefinition();
this.correlationExpression.setExpressionType(def);
}
@Override
public String toString() {
return "StickyLoadBalancer[" + correlationExpression + "]";
}
}
| StickyLoadBalancerDefinition |
java | quarkusio__quarkus | independent-projects/qute/core/src/main/java/io/quarkus/qute/ParserHook.java | {
"start": 181,
"end": 376
} | interface ____ {
/**
* This method is invoked before a template contents is parsed
*
* @param parserHelper
*/
void beforeParsing(ParserHelper parserHelper);
}
| ParserHook |
java | apache__avro | lang/java/trevni/avro/src/main/java/org/apache/trevni/avro/mapreduce/AvroTrevniKeyRecordReader.java | {
"start": 1134,
"end": 1887
} | class ____<T> extends AvroTrevniRecordReaderBase<AvroKey<T>, NullWritable, T> {
/** A reusable object to hold records of the Avro container file. */
private final AvroKey<T> mCurrentKey = new AvroKey<>();
/** {@inheritDoc} */
@Override
public AvroKey<T> getCurrentKey() throws IOException, InterruptedException {
return mCurrentKey;
}
/** {@inheritDoc} */
@Override
public NullWritable getCurrentValue() throws IOException, InterruptedException {
return NullWritable.get();
}
/** {@inheritDoc} */
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
boolean hasNext = super.nextKeyValue();
mCurrentKey.datum(getCurrentRecord());
return hasNext;
}
}
| AvroTrevniKeyRecordReader |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/jmx/export/naming/KeyNamingStrategy.java | {
"start": 1967,
"end": 4691
} | class ____ implements ObjectNamingStrategy, InitializingBean {
/**
* {@code Log} instance for this class.
*/
protected final Log logger = LogFactory.getLog(getClass());
/**
* Stores the mappings of bean key to {@code ObjectName}.
*/
private @Nullable Properties mappings;
/**
* Stores the {@code Resource}s containing properties that should be loaded
* into the final merged set of {@code Properties} used for {@code ObjectName}
* resolution.
*/
private Resource @Nullable [] mappingLocations;
/**
* Stores the result of merging the {@code mappings} {@code Properties}
* with the properties stored in the resources defined by {@code mappingLocations}.
*/
private @Nullable Properties mergedMappings;
/**
* Set local properties, containing object name mappings, for example, via
* the "props" tag in XML bean definitions. These can be considered
* defaults, to be overridden by properties loaded from files.
*/
public void setMappings(Properties mappings) {
this.mappings = mappings;
}
/**
* Set a location of a properties file to be loaded,
* containing object name mappings.
*/
public void setMappingLocation(Resource location) {
this.mappingLocations = new Resource[] {location};
}
/**
* Set location of properties files to be loaded,
* containing object name mappings.
*/
public void setMappingLocations(Resource... mappingLocations) {
this.mappingLocations = mappingLocations;
}
/**
* Merges the {@code Properties} configured in the {@code mappings} and
* {@code mappingLocations} into the final {@code Properties} instance
* used for {@code ObjectName} resolution.
*/
@Override
public void afterPropertiesSet() throws IOException {
this.mergedMappings = new Properties();
CollectionUtils.mergePropertiesIntoMap(this.mappings, this.mergedMappings);
if (this.mappingLocations != null) {
for (Resource location : this.mappingLocations) {
if (logger.isDebugEnabled()) {
logger.debug("Loading JMX object name mappings file from " + location);
}
PropertiesLoaderUtils.fillProperties(this.mergedMappings, location);
}
}
}
/**
* Attempts to retrieve the {@code ObjectName} via the given key, trying to
* find a mapped value in the mappings first.
*/
@Override
public ObjectName getObjectName(Object managedBean, @Nullable String beanKey) throws MalformedObjectNameException {
Assert.notNull(beanKey, "KeyNamingStrategy requires bean key");
String objectName = null;
if (this.mergedMappings != null) {
objectName = this.mergedMappings.getProperty(beanKey);
}
if (objectName == null) {
objectName = beanKey;
}
return ObjectNameManager.getInstance(objectName);
}
}
| KeyNamingStrategy |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/converter/FSQueueConverterBuilder.java | {
"start": 1138,
"end": 3312
} | class ____ {
FSConfigToCSConfigRuleHandler ruleHandler;
CapacitySchedulerConfiguration capacitySchedulerConfig;
boolean preemptionEnabled;
boolean sizeBasedWeight;
Resource clusterResource;
float queueMaxAMShareDefault;
int queueMaxAppsDefault;
ConversionOptions conversionOptions;
boolean drfUsed;
boolean usePercentages;
private FSQueueConverterBuilder() {
}
public static FSQueueConverterBuilder create() {
return new FSQueueConverterBuilder();
}
public FSQueueConverterBuilder withRuleHandler(
FSConfigToCSConfigRuleHandler ruleHandler) {
this.ruleHandler = ruleHandler;
return this;
}
public FSQueueConverterBuilder withCapacitySchedulerConfig(
CapacitySchedulerConfiguration capacitySchedulerConfig) {
this.capacitySchedulerConfig = capacitySchedulerConfig;
return this;
}
public FSQueueConverterBuilder withPreemptionEnabled(
boolean preemptionEnabled) {
this.preemptionEnabled = preemptionEnabled;
return this;
}
public FSQueueConverterBuilder withSizeBasedWeight(
boolean sizeBasedWeight) {
this.sizeBasedWeight = sizeBasedWeight;
return this;
}
public FSQueueConverterBuilder withClusterResource(
Resource resource) {
this.clusterResource = resource;
return this;
}
public FSQueueConverterBuilder withQueueMaxAMShareDefault(
float queueMaxAMShareDefault) {
this.queueMaxAMShareDefault = queueMaxAMShareDefault;
return this;
}
public FSQueueConverterBuilder withQueueMaxAppsDefault(
int queueMaxAppsDefault) {
this.queueMaxAppsDefault = queueMaxAppsDefault;
return this;
}
public FSQueueConverterBuilder withConversionOptions(
ConversionOptions conversionOptions) {
this.conversionOptions = conversionOptions;
return this;
}
public FSQueueConverterBuilder withDrfUsed(boolean drfUsed) {
this.drfUsed = drfUsed;
return this;
}
public FSQueueConverterBuilder withPercentages(boolean usePercentages) {
this.usePercentages = usePercentages;
return this;
}
public FSQueueConverter build() {
return new FSQueueConverter(this);
}
}
| FSQueueConverterBuilder |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/CharValueComparator.java | {
"start": 1333,
"end": 4696
} | class ____ extends TypeComparator<CharValue> {
private static final long serialVersionUID = 1L;
private final boolean ascendingComparison;
private final CharValue reference = new CharValue();
private final CharValue tempReference = new CharValue();
private final TypeComparator<?>[] comparators = new TypeComparator[] {this};
public CharValueComparator(boolean ascending) {
this.ascendingComparison = ascending;
}
@Override
public int hash(CharValue record) {
return record.hashCode();
}
@Override
public void setReference(CharValue toCompare) {
toCompare.copyTo(reference);
}
@Override
public boolean equalToReference(CharValue candidate) {
return candidate.equals(this.reference);
}
@Override
public int compareToReference(TypeComparator<CharValue> referencedComparator) {
CharValue otherRef = ((CharValueComparator) referencedComparator).reference;
int comp = otherRef.compareTo(reference);
return ascendingComparison ? comp : -comp;
}
@Override
public int compare(CharValue first, CharValue second) {
int comp = first.compareTo(second);
return ascendingComparison ? comp : -comp;
}
@Override
public int compareSerialized(DataInputView firstSource, DataInputView secondSource)
throws IOException {
reference.read(firstSource);
tempReference.read(secondSource);
int comp = reference.compareTo(tempReference);
return ascendingComparison ? comp : -comp;
}
@Override
public boolean supportsNormalizedKey() {
return NormalizableKey.class.isAssignableFrom(CharValue.class);
}
@Override
public int getNormalizeKeyLen() {
return reference.getMaxNormalizedKeyLen();
}
@Override
public boolean isNormalizedKeyPrefixOnly(int keyBytes) {
return keyBytes < getNormalizeKeyLen();
}
@Override
public void putNormalizedKey(CharValue record, MemorySegment target, int offset, int numBytes) {
record.copyNormalizedKey(target, offset, numBytes);
}
@Override
public boolean invertNormalizedKey() {
return !ascendingComparison;
}
@Override
public TypeComparator<CharValue> duplicate() {
return new CharValueComparator(ascendingComparison);
}
@Override
public int extractKeys(Object record, Object[] target, int index) {
target[index] = record;
return 1;
}
@Override
public TypeComparator<?>[] getFlatComparators() {
return comparators;
}
// --------------------------------------------------------------------------------------------
// unsupported normalization
// --------------------------------------------------------------------------------------------
@Override
public boolean supportsSerializationWithKeyNormalization() {
return false;
}
@Override
public void writeWithKeyNormalization(CharValue record, DataOutputView target)
throws IOException {
throw new UnsupportedOperationException();
}
@Override
public CharValue readWithKeyDenormalization(CharValue reuse, DataInputView source)
throws IOException {
throw new UnsupportedOperationException();
}
}
| CharValueComparator |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/lifecycle/beancreationeventlistener/E.java | {
"start": 118,
"end": 151
} | class ____ {
E(A a) {
}
}
| E |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.