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 | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/BoxedPrimitiveConstructorTest.java | {
"start": 3527,
"end": 4849
} | class ____ {
static final Boolean CONST = true;
static final String CONST2 = null;
{
// BUG: Diagnostic contains: boolean a = true;
boolean a = new Boolean(true);
// BUG: Diagnostic contains: boolean b = false;
boolean b = new Boolean(false);
// BUG: Diagnostic contains: boolean c = Boolean.valueOf(CONST);
boolean c = new Boolean(CONST);
// BUG: Diagnostic contains: boolean e = true;
boolean e = new Boolean("true");
// BUG: Diagnostic contains: boolean f = false;
boolean f = new Boolean("nope");
// BUG: Diagnostic contains: boolean g = Boolean.valueOf(CONST2);
boolean g = new Boolean(CONST2);
// BUG: Diagnostic contains: System.err.println(Boolean.TRUE);
System.err.println(new Boolean("true"));
// BUG: Diagnostic contains: System.err.println(Boolean.FALSE);
System.err.println(new Boolean("false"));
}
}
""")
.doTest();
}
@Test
public void negative() {
compilationHelper
.addSourceLines(
"Test.java",
"""
public | Test |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/MapKeyJpaAnnotation.java | {
"start": 459,
"end": 1301
} | class ____ implements MapKey {
private String name;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public MapKeyJpaAnnotation(ModelsContext modelContext) {
this.name = "";
}
/**
* Used in creating annotation instances from JDK variant
*/
public MapKeyJpaAnnotation(MapKey annotation, ModelsContext modelContext) {
this.name = annotation.name();
}
/**
* Used in creating annotation instances from Jandex variant
*/
public MapKeyJpaAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) {
this.name = (String) attributeValues.get( "name" );
}
@Override
public Class<? extends Annotation> annotationType() {
return MapKey.class;
}
@Override
public String name() {
return name;
}
public void name(String value) {
this.name = value;
}
}
| MapKeyJpaAnnotation |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/reduce/MergeManager.java | {
"start": 1120,
"end": 1276
} | interface ____ a reduce side merge that works with the default Shuffle
* implementation.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public | for |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/proxy/filter/StatFilterTest.java | {
"start": 1053,
"end": 2412
} | class ____ extends TestCase {
public void setUp() throws Exception {
JdbcStatManager.getInstance().reset();
}
public void tearDown() throws Exception {
JdbcStatManager.getInstance().reset();
DruidDriver.getProxyDataSources().clear();
assertEquals(0, JdbcStatManager.getInstance().getSqlList().size());
}
public void test_stat() throws Exception {
String url = "jdbc:wrap-jdbc:filters=default:jdbc:mock:xx";
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 1");
while (rs.next()) {
rs.getInt(1);
}
rs.close();
stmt.close();
conn.close();
TabularData sqlList = JdbcStatManager.getInstance().getSqlList();
assertEquals(true, sqlList.size() > 0);
int count = 0;
for (Object item : sqlList.values()) {
CompositeData row = (CompositeData) item;
if (url.equals((String) row.get("URL"))) {
count++;
}
long[] histogram = (long[]) row.get("Histogram");
assertEquals(0L, histogram[histogram.length - 1]);
}
assertEquals(true, count > 0);
System.out.println(JSONUtils.toJSONString(sqlList));
}
}
| StatFilterTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CassandraEndpointBuilderFactory.java | {
"start": 33244,
"end": 35102
} | class ____ implements logic for converting ResultSet
* into message body ALL, ONE, LIMIT_10, LIMIT_100...
*
* The option will be converted to a
* <code>org.apache.camel.component.cassandra.ResultSetConversionStrategy</code> type.
*
* Group: advanced
*
* @param resultSetConversionStrategy the value to set
* @return the dsl builder
*/
default AdvancedCassandraEndpointConsumerBuilder resultSetConversionStrategy(String resultSetConversionStrategy) {
doSetProperty("resultSetConversionStrategy", resultSetConversionStrategy);
return this;
}
/**
* To use the Session instance (you would normally not use this option).
*
* The option is a:
* <code>com.datastax.oss.driver.api.core.CqlSession</code> type.
*
* Group: advanced
*
* @param session the value to set
* @return the dsl builder
*/
default AdvancedCassandraEndpointConsumerBuilder session(com.datastax.oss.driver.api.core.CqlSession session) {
doSetProperty("session", session);
return this;
}
/**
* To use the Session instance (you would normally not use this option).
*
* The option will be converted to a
* <code>com.datastax.oss.driver.api.core.CqlSession</code> type.
*
* Group: advanced
*
* @param session the value to set
* @return the dsl builder
*/
default AdvancedCassandraEndpointConsumerBuilder session(String session) {
doSetProperty("session", session);
return this;
}
}
/**
* Builder for endpoint producers for the Cassandra CQL component.
*/
public | that |
java | elastic__elasticsearch | x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/cache/common/TestUtils.java | {
"start": 12825,
"end": 14376
} | class ____ extends BlobStoreCacheService {
private final ConcurrentHashMap<String, BytesArray> blobs = new ConcurrentHashMap<>();
public SimpleBlobStoreCacheService() {
super(mock(Client.class), SNAPSHOT_BLOB_CACHE_INDEX);
}
@Override
protected void innerGet(GetRequest request, ActionListener<GetResponse> listener) {
final BytesArray bytes = blobs.get(request.id());
listener.onResponse(
new GetResponse(
new GetResult(
request.index(),
request.id(),
UNASSIGNED_SEQ_NO,
UNASSIGNED_PRIMARY_TERM,
0L,
bytes != null,
bytes,
null,
null
)
)
);
}
@Override
protected void innerPut(IndexRequest request, ActionListener<DocWriteResponse> listener) {
final BytesArray bytesArray = blobs.put(request.id(), new BytesArray(request.source().toBytesRef(), true));
listener.onResponse(
new IndexResponse(
new ShardId(request.index(), "_na", 0),
request.id(),
UNASSIGNED_SEQ_NO,
UNASSIGNED_PRIMARY_TERM,
0L,
bytesArray == null
)
);
}
}
}
| SimpleBlobStoreCacheService |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/client/DefaultApiVersionInserter.java | {
"start": 1182,
"end": 3734
} | class ____ implements ApiVersionInserter {
private final @Nullable String header;
private final @Nullable String queryParam;
private final @Nullable String mediaTypeParam;
private final @Nullable Integer pathSegmentIndex;
private final ApiVersionFormatter versionFormatter;
DefaultApiVersionInserter(
@Nullable String header, @Nullable String queryParam, @Nullable String mediaTypeParam,
@Nullable Integer pathSegmentIndex, @Nullable ApiVersionFormatter formatter) {
Assert.isTrue(header != null || queryParam != null || mediaTypeParam != null || pathSegmentIndex != null,
"Expected 'header', 'queryParam', 'mediaTypeParam', or 'pathSegmentIndex' to be configured");
this.header = header;
this.queryParam = queryParam;
this.mediaTypeParam = mediaTypeParam;
this.pathSegmentIndex = pathSegmentIndex;
this.versionFormatter = (formatter != null ? formatter : Object::toString);
}
@Override
public URI insertVersion(Object version, URI uri) {
if (this.queryParam == null && this.pathSegmentIndex == null) {
return uri;
}
String formattedVersion = this.versionFormatter.formatVersion(version);
UriComponentsBuilder builder = UriComponentsBuilder.fromUri(uri);
if (this.queryParam != null) {
builder.queryParam(this.queryParam, formattedVersion);
}
if (this.pathSegmentIndex != null) {
List<String> pathSegments = new ArrayList<>(builder.build().getPathSegments());
assertPathSegmentIndex(this.pathSegmentIndex, pathSegments.size(), uri);
pathSegments.add(this.pathSegmentIndex, formattedVersion);
builder.replacePath(null);
pathSegments.forEach(builder::pathSegment);
}
return builder.build().toUri();
}
private void assertPathSegmentIndex(Integer index, int pathSegmentsSize, URI uri) {
Assert.state(index <= pathSegmentsSize,
"Cannot insert version into '" + uri.getPath() + "' at path segment index " + index);
}
@Override
public void insertVersion(Object version, HttpHeaders headers) {
if (this.header != null) {
String formattedVersion = this.versionFormatter.formatVersion(version);
headers.set(this.header, formattedVersion);
}
if (this.mediaTypeParam != null) {
MediaType contentType = headers.getContentType();
if (contentType != null) {
Map<String, String> params = new LinkedHashMap<>(contentType.getParameters());
params.put(this.mediaTypeParam, this.versionFormatter.formatVersion(version));
contentType = new MediaType(contentType, params);
headers.setContentType(contentType);
}
}
}
}
| DefaultApiVersionInserter |
java | google__guice | core/test/com/google/inject/MembersInjectorTest.java | {
"start": 13614,
"end": 13784
} | class ____ {
int failures = 0;
@Inject
void fail() {
throw new ClassCastException("whoops, failure #" + (++failures));
}
}
static | InjectionFailure |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/cdi/bcextensions/CustomPseudoScopeTest.java | {
"start": 3350,
"end": 3552
} | class ____ {
@Inject
PrototypeBean prototype;
public String getPrototypeId() {
return prototype.getId();
}
}
@ApplicationScoped
static | SingletonBean |
java | apache__kafka | share-coordinator/src/test/java/org/apache/kafka/coordinator/share/ShareCoordinatorOffsetsManagerTest.java | {
"start": 1433,
"end": 2930
} | class ____ {
private ShareCoordinatorOffsetsManager manager;
private static final SharePartitionKey KEY1 = SharePartitionKey.getInstance("gs1", Uuid.randomUuid(), 0);
private static final SharePartitionKey KEY2 = SharePartitionKey.getInstance("gs2", Uuid.randomUuid(), 0);
private static final SharePartitionKey KEY3 = SharePartitionKey.getInstance("gs1", Uuid.randomUuid(), 1);
private static final SharePartitionKey KEY4 = SharePartitionKey.getInstance("gs1", Uuid.randomUuid(), 7);
@BeforeEach
public void setUp() {
manager = new ShareCoordinatorOffsetsManager(new SnapshotRegistry(new LogContext()));
}
@Test
public void testUpdateStateAddsToInternalState() {
manager.updateState(KEY1, 0L, false);
assertEquals(Optional.empty(), manager.lastRedundantOffset());
manager.updateState(KEY1, 10L, false);
assertEquals(Optional.of(10L), manager.lastRedundantOffset()); // [0-9] offsets are redundant.
manager.updateState(KEY2, 15L, false);
assertEquals(Optional.of(10L), manager.lastRedundantOffset()); // No update to last redundant after adding 15L so, still 10L.
manager.updateState(KEY1, 25L, true);
assertEquals(Optional.of(15L), manager.lastRedundantOffset()); // KEY1 deleted, no longer part of calculation.
assertNull(manager.curState().get(KEY1));
assertEquals(15L, manager.curState().get(KEY2));
}
private static | ShareCoordinatorOffsetsManagerTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/GenericTypeSerializationTest.java | {
"start": 9761,
"end": 10145
} | class ____<T>
{
final T value;
SimpleWrapper(T value) {
this.value = value;
}
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static <T> SimpleWrapper<T> fromJson(JsonSimpleWrapper<T> value) {
return new SimpleWrapper<>(value.object);
}
}
@JsonDeserialize
public static final | SimpleWrapper |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/event/connection/JfrReauthFailedEvent.java | {
"start": 504,
"end": 988
} | class ____ extends Event {
private final String epId;
/**
* Create a new {@link JfrReauthFailedEvent} given a {@link ReauthenticationFailedEvent}.
*
* @param event the {@link ReauthenticationFailedEvent}
*/
public JfrReauthFailedEvent(ReauthenticationFailedEvent event) {
this.epId = event.getEpId();
}
/**
* @return the connection endpoint ID
*/
public String getEpId() {
return epId;
}
}
| JfrReauthFailedEvent |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/float2darrays/Float2DArrays_assertNumberOfRows_Test.java | {
"start": 802,
"end": 1080
} | class ____ extends Float2DArraysBaseTest {
@Test
void should_delegate_to_Arrays2D() {
// WHEN
float2dArrays.assertNumberOfRows(info, actual, 2);
// THEN
verify(arrays2d).assertNumberOfRows(info, failures, actual, 2);
}
}
| Float2DArrays_assertNumberOfRows_Test |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/publisher/FluxMapTest.java | {
"start": 17139,
"end": 17253
} | class ____<T> implements Supplier<T> {
@Override
public @Nullable T get() {
return null;
}
}
}
| NullSupplier |
java | junit-team__junit5 | documentation/src/test/java/example/ParameterizedMigrationDemo.java | {
"start": 1673,
"end": 2232
} | class ____ {
static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] { { 1, "foo" }, { 2, "bar" } });
}
@org.junit.jupiter.params.Parameter(0)
int number;
@org.junit.jupiter.params.Parameter(1)
String text;
@BeforeParameterizedClassInvocation
static void before(int number, String text) {
}
@AfterParameterizedClassInvocation
static void after() {
}
@org.junit.jupiter.api.Test
void someTest() {
}
@org.junit.jupiter.api.Test
void anotherTest() {
}
}
// end::after[]
}
| JupiterParameterizedClassTests |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/rest/action/document/RestIndexAction.java | {
"start": 1971,
"end": 2972
} | class ____ extends BaseRestHandler {
static final String TYPES_DEPRECATION_MESSAGE = "[types removal] Specifying types in document "
+ "index requests is deprecated, use the typeless endpoints instead (/{index}/_doc/{id}, /{index}/_doc, "
+ "or /{index}/_create/{id}).";
private final Set<String> capabilities = Set.of(FAILURE_STORE_STATUS_CAPABILITY);
private final ClusterService clusterService;
private final ProjectIdResolver projectIdResolver;
public RestIndexAction(ClusterService clusterService, ProjectIdResolver projectIdResolver) {
this.clusterService = clusterService;
this.projectIdResolver = projectIdResolver;
}
@Override
public List<Route> routes() {
return List.of(new Route(POST, "/{index}/_doc/{id}"), new Route(PUT, "/{index}/_doc/{id}"));
}
@Override
public String getName() {
return "document_index_action";
}
@ServerlessScope(Scope.PUBLIC)
public static final | RestIndexAction |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/lib/output/TestMRCJCFileOutputCommitter.java | {
"start": 1872,
"end": 7139
} | class ____ {
private static Path outDir = new Path(System.getProperty("test.build.data",
"/tmp"), "output");
// A random task attempt id for testing.
private static String attempt = "attempt_200707121733_0001_m_000000_0";
private static String partFile = "part-m-00000";
private static TaskAttemptID taskID = TaskAttemptID.forName(attempt);
private Text key1 = new Text("key1");
private Text key2 = new Text("key2");
private Text val1 = new Text("val1");
private Text val2 = new Text("val2");
@SuppressWarnings("unchecked")
private void writeOutput(RecordWriter theRecordWriter,
TaskAttemptContext context) throws IOException, InterruptedException {
NullWritable nullWritable = NullWritable.get();
try {
theRecordWriter.write(key1, val1);
theRecordWriter.write(null, nullWritable);
theRecordWriter.write(null, val1);
theRecordWriter.write(nullWritable, val2);
theRecordWriter.write(key2, nullWritable);
theRecordWriter.write(key1, null);
theRecordWriter.write(null, null);
theRecordWriter.write(key2, val2);
} finally {
theRecordWriter.close(context);
}
}
private static void cleanup() throws IOException {
Configuration conf = new Configuration();
FileSystem fs = outDir.getFileSystem(conf);
fs.delete(outDir, true);
}
@BeforeEach
public void setUp() throws IOException {
cleanup();
}
@AfterEach
public void tearDown() throws IOException {
cleanup();
}
@SuppressWarnings("unchecked")
@Test
public void testCommitter() throws Exception {
Job job = Job.getInstance();
FileOutputFormat.setOutputPath(job, outDir);
Configuration conf = job.getConfiguration();
conf.set(MRJobConfig.TASK_ATTEMPT_ID, attempt);
JobContext jContext = new JobContextImpl(conf, taskID.getJobID());
TaskAttemptContext tContext = new TaskAttemptContextImpl(conf, taskID);
FileOutputCommitter committer = new FileOutputCommitter(outDir, tContext);
// setup
committer.setupJob(jContext);
committer.setupTask(tContext);
// write output
TextOutputFormat theOutputFormat = new TextOutputFormat();
RecordWriter theRecordWriter = theOutputFormat.getRecordWriter(tContext);
writeOutput(theRecordWriter, tContext);
// do commit
committer.commitTask(tContext);
committer.commitJob(jContext);
// validate output
File expectedFile = new File(new Path(outDir, partFile).toString());
StringBuilder expectedOutput = new StringBuilder();
expectedOutput.append(key1).append('\t').append(val1).append("\n");
expectedOutput.append(val1).append("\n");
expectedOutput.append(val2).append("\n");
expectedOutput.append(key2).append("\n");
expectedOutput.append(key1).append("\n");
expectedOutput.append(key2).append('\t').append(val2).append("\n");
String output = UtilsForTests.slurp(expectedFile);
assertThat(output).isEqualTo(expectedOutput.toString());
FileUtil.fullyDelete(new File(outDir.toString()));
}
@Test
public void testEmptyOutput() throws Exception {
Job job = Job.getInstance();
FileOutputFormat.setOutputPath(job, outDir);
Configuration conf = job.getConfiguration();
conf.set(MRJobConfig.TASK_ATTEMPT_ID, attempt);
JobContext jContext = new JobContextImpl(conf, taskID.getJobID());
TaskAttemptContext tContext = new TaskAttemptContextImpl(conf, taskID);
FileOutputCommitter committer = new FileOutputCommitter(outDir, tContext);
// setup
committer.setupJob(jContext);
committer.setupTask(tContext);
// Do not write any output
// do commit
committer.commitTask(tContext);
committer.commitJob(jContext);
FileUtil.fullyDelete(new File(outDir.toString()));
}
@SuppressWarnings("unchecked")
@Test
public void testAbort() throws IOException, InterruptedException {
Job job = Job.getInstance();
FileOutputFormat.setOutputPath(job, outDir);
Configuration conf = job.getConfiguration();
conf.set(MRJobConfig.TASK_ATTEMPT_ID, attempt);
JobContext jContext = new JobContextImpl(conf, taskID.getJobID());
TaskAttemptContext tContext = new TaskAttemptContextImpl(conf, taskID);
FileOutputCommitter committer = new FileOutputCommitter(outDir, tContext);
// do setup
committer.setupJob(jContext);
committer.setupTask(tContext);
// write output
TextOutputFormat theOutputFormat = new TextOutputFormat();
RecordWriter theRecordWriter = theOutputFormat.getRecordWriter(tContext);
writeOutput(theRecordWriter, tContext);
// do abort
committer.abortTask(tContext);
File expectedFile = new File(new Path(committer.getWorkPath(), partFile)
.toString());
assertFalse(expectedFile.exists(), "task temp dir still exists");
committer.abortJob(jContext, JobStatus.State.FAILED);
expectedFile = new File(new Path(outDir, FileOutputCommitter.PENDING_DIR_NAME)
.toString());
assertFalse(expectedFile.exists(), "job temp dir still exists");
assertThat(new File(outDir.toString())
.listFiles()).withFailMessage("Output directory not empty").isEmpty();
FileUtil.fullyDelete(new File(outDir.toString()));
}
public static | TestMRCJCFileOutputCommitter |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/ClassUtils.java | {
"start": 21300,
"end": 21477
} | class ____ by {@code className} using the {@code classLoader}.
* @throws NullPointerException if the className is null.
* @throws ClassNotFoundException if the | represented |
java | apache__camel | components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/HttpServerConsumerChannelFactory.java | {
"start": 1448,
"end": 2078
} | interface ____ {
/**
* Initializes this consumer channel factory with the given port.
*/
void init(int port);
/**
* The port number this consumer channel factory is using.
*/
int getPort();
/**
* Adds the given consumer.
*/
void addConsumer(NettyHttpConsumer consumer);
/**
* Removes the given consumer
*/
void removeConsumer(NettyHttpConsumer consumer);
/**
* Number of active consumers
*/
int consumers();
/**
* Gets the {@link ChannelHandler}
*/
ChannelHandler getChannelHandler();
}
| HttpServerConsumerChannelFactory |
java | apache__flink | flink-python/src/main/java/org/apache/flink/table/executor/python/ChainingOptimizingExecutor.java | {
"start": 1676,
"end": 3573
} | class ____ implements Executor {
private final Executor executor;
public ChainingOptimizingExecutor(Executor executor) {
this.executor = Preconditions.checkNotNull(executor);
}
@Override
public ReadableConfig getConfiguration() {
return executor.getConfiguration();
}
@Override
public Pipeline createPipeline(
List<Transformation<?>> transformations,
ReadableConfig configuration,
String defaultJobName) {
return createPipeline(
transformations, configuration, defaultJobName, Collections.emptyList());
}
@Override
public Pipeline createPipeline(
List<Transformation<?>> transformations,
ReadableConfig configuration,
@Nullable String defaultJobName,
List<JobStatusHook> jobStatusHookList) {
List<Transformation<?>> chainedTransformations = transformations;
if (configuration
.getOptional(PythonOptions.PYTHON_OPERATOR_CHAINING_ENABLED)
.orElse(getConfiguration().get(PythonOptions.PYTHON_OPERATOR_CHAINING_ENABLED))) {
chainedTransformations = PythonOperatorChainingOptimizer.optimize(transformations);
}
PythonConfigUtil.setPartitionCustomOperatorNumPartitions(chainedTransformations);
return executor.createPipeline(
chainedTransformations, configuration, defaultJobName, jobStatusHookList);
}
@Override
public JobExecutionResult execute(Pipeline pipeline) throws Exception {
return executor.execute(pipeline);
}
@Override
public JobClient executeAsync(Pipeline pipeline) throws Exception {
return executor.executeAsync(pipeline);
}
@Override
public boolean isCheckpointingEnabled() {
return executor.isCheckpointingEnabled();
}
}
| ChainingOptimizingExecutor |
java | spring-projects__spring-framework | integration-tests/src/test/java/org/springframework/context/annotation/jsr330/ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java | {
"start": 13729,
"end": 13863
} | class ____ extends ScopedTestBean implements AnotherScopeTestInterface {
}
@Named
@SessionScoped
public static | RequestScopedTestBean |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/typelevel/MockitoSpyBeansByNameIntegrationTests.java | {
"start": 3034,
"end": 3565
} | class ____ {
@Bean
ExampleService s1() {
return new ExampleService() {
@Override
public String greeting() {
return "prod 1";
}
};
}
@Bean
ExampleService s2() {
return new ExampleService() {
@Override
public String greeting() {
return "prod 2";
}
};
}
@Bean
ExampleService s3() {
return new ExampleService() {
@Override
public String greeting() {
return "prod 3";
}
};
}
@Bean
ExampleService s4() {
return () -> "prod 4";
}
}
}
| Config |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/publisher/FluxPeekTest.java | {
"start": 1788,
"end": 23492
} | class ____ extends FluxOperatorTest<String, String> {
@Override
protected Scenario<String, String> defaultScenarioOptions(Scenario<String, String> defaultOptions) {
return defaultOptions.fusionMode(Fuseable.ANY);
}
@Override
protected List<Scenario<String, String>> scenarios_operatorSuccess() {
return Arrays.asList(scenario(f -> f.doOnSubscribe(s -> {
})),
scenario(f -> f.doOnError(s -> {
})),
scenario(f -> f.doOnTerminate(() -> {
})),
scenario(f -> f.doAfterTerminate(() -> {
})),
scenario(f -> f.doOnCancel(() -> {
})),
scenario(f -> f.doOnComplete(() -> {
})),
scenario(f -> f.doOnRequest(d -> {
})),
scenario(f -> f.doOnRequest(s -> {
throw new RuntimeException(); //ignored
})),
scenario(f -> f.doOnNext(s -> {
})),
scenario(f -> f.doOnError(s -> {
})));
}
@Override
protected List<Scenario<String, String>> scenarios_touchAndAssertState() {
return Arrays.asList(scenario(f -> f.doOnNext(d -> {
})));
}
@Override
protected List<Scenario<String, String>> scenarios_operatorError() {
return Arrays.asList(
scenario(f -> f.doOnSubscribe(s -> {
throw exception();
})).producerNever(),
scenario(f -> f.doOnComplete(() -> {
throw exception();
})).receiveValues(item(0), item(1), item(2)),
scenario(f -> f.doOnNext(s -> {
throw exception();
})),
scenario(f -> f.doOnComplete(() -> {
throw exception();
})).producerEmpty(),
scenario(f -> f.doOnCancel(() -> {
throw exception();
})).producerNever()
.verifier(step -> {
//fixme Support bubbled error verification in reactor-test
Hooks.onErrorDropped(d -> assertThat(d).hasMessage(exception().getMessage()));
step.consumeSubscriptionWith(Subscription::cancel)
.verifyErrorMessage(exception().getMessage());
}));
}
@Override
protected List<Scenario<String, String>> scenarios_errorFromUpstreamFailure() {
List<Scenario<String, String>> combinedScenarios = new ArrayList<>();
combinedScenarios.addAll(scenarios_operatorSuccess());
combinedScenarios.addAll(Arrays.asList(scenario(f -> f.doAfterTerminate(() -> {
throw droppedException();
})).fusionMode(Fuseable.NONE)
.verifier(step -> {
try {
step.verifyErrorMessage(exception().getMessage());
}
catch (Exception e) {
assertThat(Exceptions.unwrap(e)).hasMessage(droppedException().getMessage());
}
}),
scenario(f -> f.doOnNext(s -> {
throw exception();
})
.doOnError(s -> {
throw Exceptions.errorCallbackNotImplemented(new Exception("unsupported"));
})).fusionMode(Fuseable.NONE)
.verifier(step -> {
try {
step.verifyErrorMessage("unsupported");
fail("Exception expected");
}
catch (Exception e) {
assertThat(Exceptions.unwrap(e).getCause()).hasMessage("unsupported");
}
}),
//extra scenarios for coverage using specific combination of fluxpkeek
// not necessarily open
scenario(f -> Flux.doOnSignal(f, null, null, s -> {
if (s.getMessage()
.equals(exception().getMessage())) {
throw Exceptions.propagate(s);
}
}, null, () -> {
throw droppedException();
}, null, null)
.doOnError(s -> {
throw Exceptions.errorCallbackNotImplemented(new Exception("unsupported"));
})).verifier(step -> {
try {
step.thenCancel()
.verify();
}
catch (Exception e) {
assertThat(Exceptions.unwrap(e)).hasMessage(droppedException().getMessage());
}
}),
scenario(f -> Flux.doOnSignal(f, null, null, s -> {
if (s.getMessage()
.equals(exception().getMessage())) {
throw Exceptions.propagate(s);
}
}, null, () -> {
throw droppedException();
}, null, null)
.doOnError(s -> {
throw Exceptions.errorCallbackNotImplemented(s);
})).verifier(step -> {
try {
step.thenCancel()
.verify();
}
catch (Exception e) {
assertThat(Exceptions.unwrap(e)).hasMessage(droppedException().getMessage());
}
}),
scenario(f -> Flux.doOnSignal(f, null, null, s -> {
if (s.getMessage()
.equals(exception().getMessage())) {
throw Exceptions.propagate(s);
}
}, null, () -> {
throw droppedException();
}, null, null)
.doOnError(s -> {
throw exception();
})).fusionMode(Fuseable.NONE)
.verifier(step -> {
try {
step.verifyErrorMessage("test");
}
catch (Exception e) {
assertThat(Exceptions.unwrap(e)).hasMessage(droppedException().getMessage());
}
})
));
return combinedScenarios;
}
@Test
public void nullSource() {
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> {
new FluxPeek<>(null, null, null, null, null, null, null, null);
});
}
@Test
public void normal() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
AtomicReference<Subscription> onSubscribe = new AtomicReference<>();
AtomicReference<Integer> onNext = new AtomicReference<>();
AtomicReference<Throwable> onError = new AtomicReference<>();
AtomicBoolean onComplete = new AtomicBoolean();
AtomicLong onRequest = new AtomicLong();
AtomicBoolean onAfterComplete = new AtomicBoolean();
AtomicBoolean onCancel = new AtomicBoolean();
new FluxPeek<>(Flux.just(1)
.hide(), onSubscribe::set, onNext::set, onError::set, () -> onComplete.set(true), () -> onAfterComplete.set(true), onRequest::set, () -> onCancel.set(true)).subscribe(ts);
assertThat(onSubscribe.get()).isNotNull();
assertThat(onNext).hasValue((Integer) 1);
assertThat(onError.get()).isNull();
assertThat(onComplete.get()).isTrue();
assertThat(onAfterComplete.get()).isTrue();
assertThat(onRequest).hasValue(Long.MAX_VALUE);
assertThat(onCancel.get()).isFalse();
}
@Test
public void error() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
AtomicReference<Subscription> onSubscribe = new AtomicReference<>();
AtomicReference<Integer> onNext = new AtomicReference<>();
AtomicReference<Throwable> onError = new AtomicReference<>();
AtomicBoolean onComplete = new AtomicBoolean();
AtomicLong onRequest = new AtomicLong();
AtomicBoolean onAfterComplete = new AtomicBoolean();
AtomicBoolean onCancel = new AtomicBoolean();
new FluxPeek<>(new FluxError<>(new RuntimeException("forced failure")), onSubscribe::set, onNext::set, onError::set, () -> onComplete.set(true), () -> onAfterComplete.set(true), onRequest::set, () -> onCancel.set(true)).subscribe(ts);
assertThat(onSubscribe.get()).isNotNull();
assertThat(onNext.get()).isNull();
assertThat(onError.get()).isInstanceOf(RuntimeException.class);
assertThat(onComplete.get()).isFalse();
assertThat(onAfterComplete.get()).isTrue();
assertThat(onRequest).hasValue(Long.MAX_VALUE);
assertThat(onCancel.get()).isFalse();
}
@Test
public void empty() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
AtomicReference<Subscription> onSubscribe = new AtomicReference<>();
AtomicReference<Integer> onNext = new AtomicReference<>();
AtomicReference<Throwable> onError = new AtomicReference<>();
AtomicBoolean onComplete = new AtomicBoolean();
AtomicLong onRequest = new AtomicLong();
AtomicBoolean onAfterComplete = new AtomicBoolean();
AtomicBoolean onCancel = new AtomicBoolean();
new FluxPeek<>(Flux.empty(), onSubscribe::set, onNext::set, onError::set, () -> onComplete.set(true), () -> onAfterComplete.set(true), onRequest::set, () -> onCancel.set(true)).subscribe(ts);
assertThat(onSubscribe.get()).isNotNull();
assertThat(onNext.get()).isNull();
assertThat(onError.get()).isNull();
assertThat(onComplete.get()).isTrue();
assertThat(onAfterComplete.get()).isTrue();
assertThat(onRequest).hasValue(Long.MAX_VALUE);
assertThat(onCancel.get()).isFalse();
}
@Test
public void never() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
AtomicReference<Subscription> onSubscribe = new AtomicReference<>();
AtomicReference<Integer> onNext = new AtomicReference<>();
AtomicReference<Throwable> onError = new AtomicReference<>();
AtomicBoolean onComplete = new AtomicBoolean();
AtomicLong onRequest = new AtomicLong();
AtomicBoolean onAfterComplete = new AtomicBoolean();
AtomicBoolean onCancel = new AtomicBoolean();
new FluxPeek<>(Flux.never(), onSubscribe::set, onNext::set, onError::set, () -> onComplete.set(true), () -> onAfterComplete.set(true), onRequest::set, () -> onCancel.set(true)).subscribe(ts);
assertThat(onSubscribe.get()).isNotNull();
assertThat(onNext.get()).isNull();
assertThat(onError.get()).isNull();
assertThat(onComplete.get()).isFalse();
assertThat(onAfterComplete.get()).isFalse();
assertThat(onRequest).hasValue(Long.MAX_VALUE);
assertThat(onCancel.get()).isFalse();
}
@Test
public void neverCancel() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
AtomicReference<Subscription> onSubscribe = new AtomicReference<>();
AtomicReference<Integer> onNext = new AtomicReference<>();
AtomicReference<Throwable> onError = new AtomicReference<>();
AtomicBoolean onComplete = new AtomicBoolean();
AtomicLong onRequest = new AtomicLong();
AtomicBoolean onAfterComplete = new AtomicBoolean();
AtomicBoolean onCancel = new AtomicBoolean();
new FluxPeek<>(Flux.never(), onSubscribe::set, onNext::set, onError::set, () -> onComplete.set(true), () -> onAfterComplete.set(true), onRequest::set, () -> onCancel.set(true)).subscribe(ts);
assertThat(onSubscribe.get()).isNotNull();
assertThat(onNext.get()).isNull();
assertThat(onError.get()).isNull();
assertThat(onComplete.get()).isFalse();
assertThat(onAfterComplete.get()).isFalse();
assertThat(onRequest).hasValue(Long.MAX_VALUE);
assertThat(onCancel.get()).isFalse();
ts.cancel();
assertThat(onCancel.get()).isTrue();
}
@Test
public void callbackError() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Throwable err = new Exception("test");
Flux.just(1)
.hide()
.doOnNext(d -> {
throw Exceptions.propagate(err);
})
.subscribe(ts);
//nominal error path (DownstreamException)
ts.assertErrorMessage("test");
ts = AssertSubscriber.create();
try {
Flux.just(1)
.hide()
.doOnNext(d -> {
throw Exceptions.bubble(err);
})
.subscribe(ts);
fail("Exception expected");
}
catch (Exception e) {
assertThat(Exceptions.unwrap(e)).isSameAs(err);
}
}
@Test
public void completeCallbackError() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Throwable err = new Exception("test");
Flux.just(1)
.hide()
.doOnComplete(() -> {
throw Exceptions.propagate(err);
})
.subscribe(ts);
//nominal error path (DownstreamException)
ts.assertErrorMessage("test");
ts = AssertSubscriber.create();
try {
Flux.just(1)
.hide()
.doOnComplete(() -> {
throw Exceptions.bubble(err);
})
.subscribe(ts);
fail("Exception expected");
}
catch (Exception e) {
assertThat(Exceptions.unwrap(e)).isSameAs(err);
}
}
@Test
public void errorCallbackError() {
IllegalStateException err = new IllegalStateException("test");
FluxPeek<String> flux = new FluxPeek<>(Flux.error(new IllegalArgumentException("bar")), null, null, e -> {
throw err;
}, null, null, null, null);
AssertSubscriber<String> ts = AssertSubscriber.create();
flux.subscribe(ts);
ts.assertNoValues();
ts.assertError(IllegalStateException.class);
ts.assertErrorWith(e -> e.getSuppressed()[0].getMessage()
.equals("bar"));
}
//See https://github.com/reactor/reactor-core/issues/272
@Test
public void errorCallbackError2() {
//test with alternate / wrapped error types
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Throwable err = new Exception("test");
Flux.just(1)
.hide()
.doOnNext(d -> {
throw new RuntimeException();
})
.doOnError(e -> {
throw Exceptions.propagate(err);
})
.subscribe(ts);
//nominal error path (DownstreamException)
ts.assertErrorMessage("test");
ts = AssertSubscriber.create();
try {
Flux.just(1)
.hide()
.doOnNext(d -> {
throw new RuntimeException();
})
.doOnError(d -> {
throw Exceptions.bubble(err);
})
.subscribe(ts);
fail("Exception expected");
}
catch (Exception e) {
assertThat(Exceptions.unwrap(e)).isSameAs(err);
}
}
//See https://github.com/reactor/reactor-core/issues/253
@Test
public void errorCallbackErrorWithParallel() {
AssertSubscriber<Integer> assertSubscriber = new AssertSubscriber<>();
Mono.just(1)
.hide()
.publishOn(parallel())
.doOnNext(i -> {
throw new IllegalArgumentException();
})
.doOnError(e -> {
throw new IllegalStateException(e);
})
.subscribe(assertSubscriber);
assertSubscriber.await()
.assertError(IllegalStateException.class)
.assertNotComplete();
}
@Test
@TestLoggerExtension.Redirect
void afterTerminateCallbackErrorDoesNotInvokeOnError(TestLogger testLogger) {
IllegalStateException e = new IllegalStateException("test");
AtomicReference<Throwable> errorCallbackCapture = new AtomicReference<>();
FluxPeek<String> flux = new FluxPeek<>(Flux.empty(),
null,
null,
errorCallbackCapture::set,
null,
() -> {
throw e;
},
null,
null);
AssertSubscriber<String> ts = AssertSubscriber.create();
flux.subscribe(ts);
ts.assertNoValues();
ts.assertComplete();
assertThat(errorCallbackCapture.get()).isNull();
assertThat(testLogger.getErrContent())
.contains("Operator called default onErrorDropped")
.contains(e.toString());
}
@Test
public void afterTerminateCallbackFatalIsThrownDirectly() {
AtomicReference<Throwable> errorCallbackCapture = new AtomicReference<>();
Error fatal = new LinkageError();
FluxPeek<String> flux = new FluxPeek<>(Flux.empty(), null, null, errorCallbackCapture::set, null, () -> {
throw fatal;
}, null, null);
AssertSubscriber<String> ts = AssertSubscriber.create();
try {
flux.subscribe(ts);
fail("expected thrown exception");
}
catch (Throwable e) {
assertThat(e).isSameAs(fatal);
}
ts.assertNoValues();
ts.assertComplete();
assertThat(errorCallbackCapture).hasValue(null);
//same with after error
errorCallbackCapture.set(null);
flux = new FluxPeek<>(Flux.error(new NullPointerException()), null, null, errorCallbackCapture::set, null, () -> {
throw fatal;
}, null, null);
ts = AssertSubscriber.create();
try {
flux.subscribe(ts);
fail("expected thrown exception");
}
catch (Throwable e) {
assertThat(e).isSameAs(fatal);
}
ts.assertNoValues();
ts.assertError(NullPointerException.class);
assertThat(errorCallbackCapture.get()).isInstanceOf(NullPointerException.class);
}
@Test
@TestLoggerExtension.Redirect
void afterTerminateCallbackErrorAndErrorCallbackError(TestLogger testLogger) {
IllegalStateException error1 = new IllegalStateException("afterTerminate");
IllegalArgumentException error2 = new IllegalArgumentException("error");
FluxPeek<String> flux = new FluxPeek<>(Flux.empty(), null, null, e -> {
throw error2;
}, null, () -> {
throw error1;
}, null, null);
AssertSubscriber<String> ts = AssertSubscriber.create();
flux.subscribe(ts);
assertThat(testLogger.getErrContent())
.contains("Operator called default onErrorDropped")
.contains(error1.getMessage());
assertThat(error2.getSuppressed()).hasSize(0);
//error2 is never thrown
ts.assertNoValues();
ts.assertComplete();
}
@Test
@TestLoggerExtension.Redirect
void afterTerminateCallbackErrorAndErrorCallbackError2(TestLogger testLogger) {
IllegalStateException afterTerminate = new IllegalStateException("afterTerminate");
IllegalArgumentException error = new IllegalArgumentException("error");
NullPointerException ex = new NullPointerException();
FluxPeek<String> flux = new FluxPeek<>(Flux.error(ex), null, null, e -> {
throw error;
}, null, () -> {
throw afterTerminate;
}, null, null);
AssertSubscriber<String> ts = AssertSubscriber.create();
flux.subscribe(ts);
assertThat(testLogger.getErrContent())
.contains("Operator called default onErrorDropped")
.contains(afterTerminate.getMessage());
//afterTerminate suppressed error which itself suppressed original err
assertThat(afterTerminate.getSuppressed()).hasSize(1);
assertThat(afterTerminate).hasSuppressedException(error);
assertThat(error.getSuppressed()).hasSize(1);
assertThat(error).hasSuppressedException(ex);
ts.assertNoValues();
//the subscriber still sees the 'error' message since actual.onError is called before the afterTerminate callback
ts.assertErrorMessage("error");
}
@Test
public void syncFusionAvailable() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.range(1, 2)
.doOnNext(v -> {
})
.subscribe(ts);
Subscription s = ts.upstream();
assertThat(s).as("check QueueSubscription").isInstanceOf(QueueSubscription.class);
}
@Test
public void asyncFusionAvailable() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Sinks.unsafe().many()
.unicast()
.onBackpressureBuffer(Queues.<Integer>get(2).get())
.asFlux()
.doOnNext(v -> {
})
.subscribe(ts);
Subscription s = ts.upstream();
assertThat(s).as("check QueueSubscription").isInstanceOf(QueueSubscription.class);
}
@Test
public void conditionalFusionAvailable() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Flux.wrap(u -> {
if (!(u instanceof Fuseable.ConditionalSubscriber)) {
Operators.error(u, new IllegalArgumentException("The subscriber is not conditional: " + u));
}
else {
Operators.complete(u);
}
})
.doOnNext(v -> {
})
.filter(v -> true)
.subscribe(ts);
ts.assertNoError()
.assertNoValues()
.assertComplete();
}
@Test
public void conditionalFusionAvailableWithFuseable() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Flux.wrap(u -> {
if (!(u instanceof Fuseable.ConditionalSubscriber)) {
Operators.error(u, new IllegalArgumentException("The subscriber is not conditional: " + u));
}
else {
Operators.complete(u);
}
})
.doOnNext(v -> {
})
.filter(v -> true)
.subscribe(ts);
ts.assertNoError()
.assertNoValues()
.assertComplete();
}
@Test
public void syncCompleteCalled() {
AtomicBoolean onComplete = new AtomicBoolean();
AssertSubscriber<Object> ts = AssertSubscriber.create();
Flux.range(1, 2)
.hide()
.doOnComplete(() -> onComplete.set(true))
.subscribe(ts);
ts.assertNoError()
.assertValues(1, 2)
.assertComplete();
assertThat(onComplete.get()).as("onComplete not called back").isTrue();
}
@Test
public void syncdoAfterTerminateCalled() {
AtomicBoolean onTerminate = new AtomicBoolean();
AssertSubscriber<Object> ts = AssertSubscriber.create();
Flux.range(1, 2)
.hide()
.doAfterTerminate(() -> onTerminate.set(true))
.subscribe(ts);
ts.assertNoError()
.assertValues(1, 2)
.assertComplete();
assertThat(onTerminate.get()).as("onComplete not called back").isTrue();
}
@Test
public void syncdoOnTerminateCalled() {
AtomicBoolean onTerminate = new AtomicBoolean();
AssertSubscriber<Object> ts = AssertSubscriber.create();
Flux.range(1, 2)
.hide()
.doOnTerminate(() -> onTerminate.set(true))
.subscribe(ts);
ts.assertNoError()
.assertValues(1, 2)
.assertComplete();
assertThat(onTerminate.get()).as("onComplete not called back").isTrue();
}
@Test
public void syncdoOnTerminateCalled2() {
AtomicBoolean onTerminate = new AtomicBoolean();
AssertSubscriber<Object> ts = AssertSubscriber.create();
Flux.empty()
.hide()
.doOnTerminate(() -> onTerminate.set(true))
.subscribe(ts);
ts.assertNoError()
.assertComplete();
assertThat(onTerminate.get()).as("onComplete not called back").isTrue();
}
@Test
public void syncdoOnTerminateCalled3() {
AtomicBoolean onTerminate = new AtomicBoolean();
AssertSubscriber<Object> ts = AssertSubscriber.create();
Flux.error(new Exception("test"))
.hide()
.doOnTerminate(() -> onTerminate.set(true))
.subscribe(ts);
ts.assertErrorMessage("test")
.assertNotComplete();
assertThat(onTerminate.get()).as("onComplete not called back").isTrue();
}
@Test
public void should_reduce_to_10_events() {
for (int i = 0; i < 20; i++) {
AtomicInteger count = new AtomicInteger();
Flux.range(0, 10)
.flatMap(x -> Flux.range(0, 2)
.map(y -> blockingOp(x, y))
.subscribeOn(parallel())
.reduce((l, r) -> l + "_" + r)
.hide()
.doOnSuccess(s -> {
count.incrementAndGet();
}))
.blockLast();
assertThat(count).hasValue(10);
}
}
@Test
public void should_reduce_to_10_events_conditional() {
for (int i = 0; i < 20; i++) {
AtomicInteger count = new AtomicInteger();
Flux.range(0, 10)
.flatMap(x -> Flux.range(0, 2)
.map(y -> blockingOp(x, y))
.subscribeOn(parallel())
.reduce((l, r) -> l + "_" + r)
.hide()
.doOnSuccess(s -> {
count.incrementAndGet();
})
.filter(v -> true))
.blockLast();
assertThat(count).hasValue(10);
}
}
static String blockingOp(Integer x, Integer y) {
try {
sleep(10);
}
catch (InterruptedException e) {
e.printStackTrace();
}
return "x" + x + "y" + y;
}
static final | FluxPeekTest |
java | spring-projects__spring-framework | spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java | {
"start": 2347,
"end": 14124
} | class ____ {
private SimpleBrokerMessageHandler messageHandler;
@Mock
private SubscribableChannel clientInChannel;
@Mock
private MessageChannel clientOutChannel;
@Mock
private SubscribableChannel brokerChannel;
@Mock
private TaskScheduler taskScheduler;
@Captor
ArgumentCaptor<Message<?>> messageCaptor;
@BeforeEach
void setup() {
this.messageHandler = new SimpleBrokerMessageHandler(
this.clientInChannel, this.clientOutChannel, this.brokerChannel, Collections.emptyList());
}
@Test
void subscribePublish() {
startSession("sess1");
startSession("sess2");
this.messageHandler.handleMessage(createSubscriptionMessage("sess1", "sub1", "/foo"));
this.messageHandler.handleMessage(createSubscriptionMessage("sess1", "sub2", "/foo"));
this.messageHandler.handleMessage(createSubscriptionMessage("sess1", "sub3", "/bar"));
this.messageHandler.handleMessage(createSubscriptionMessage("sess2", "sub1", "/foo"));
this.messageHandler.handleMessage(createSubscriptionMessage("sess2", "sub2", "/foo"));
this.messageHandler.handleMessage(createSubscriptionMessage("sess2", "sub3", "/bar"));
this.messageHandler.handleMessage(createMessage("/foo", "message1"));
this.messageHandler.handleMessage(createMessage("/bar", "message2"));
verify(this.clientOutChannel, times(6)).send(this.messageCaptor.capture());
assertThat(messageCaptured("sess1", "sub1", "/foo")).isTrue();
assertThat(messageCaptured("sess1", "sub2", "/foo")).isTrue();
assertThat(messageCaptured("sess2", "sub1", "/foo")).isTrue();
assertThat(messageCaptured("sess2", "sub2", "/foo")).isTrue();
assertThat(messageCaptured("sess1", "sub3", "/bar")).isTrue();
assertThat(messageCaptured("sess2", "sub3", "/bar")).isTrue();
}
@Test
void subscribeDisconnectPublish() {
String sess1 = "sess1";
String sess2 = "sess2";
startSession(sess1);
startSession(sess2);
this.messageHandler.handleMessage(createSubscriptionMessage(sess1, "sub1", "/foo"));
this.messageHandler.handleMessage(createSubscriptionMessage(sess1, "sub2", "/foo"));
this.messageHandler.handleMessage(createSubscriptionMessage(sess1, "sub3", "/bar"));
this.messageHandler.handleMessage(createSubscriptionMessage(sess2, "sub1", "/foo"));
this.messageHandler.handleMessage(createSubscriptionMessage(sess2, "sub2", "/foo"));
this.messageHandler.handleMessage(createSubscriptionMessage(sess2, "sub3", "/bar"));
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.DISCONNECT);
headers.setSessionId(sess1);
headers.setUser(new TestPrincipal("joe"));
Message<byte[]> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
this.messageHandler.handleMessage(message);
this.messageHandler.handleMessage(createMessage("/foo", "message1"));
this.messageHandler.handleMessage(createMessage("/bar", "message2"));
verify(this.clientOutChannel, times(4)).send(this.messageCaptor.capture());
Message<?> captured = this.messageCaptor.getAllValues().get(2);
assertThat(SimpMessageHeaderAccessor.getMessageType(captured.getHeaders())).isEqualTo(SimpMessageType.DISCONNECT_ACK);
assertThat(captured.getHeaders().get(SimpMessageHeaderAccessor.DISCONNECT_MESSAGE_HEADER)).isSameAs(message);
assertThat(SimpMessageHeaderAccessor.getSessionId(captured.getHeaders())).isEqualTo(sess1);
assertThat(SimpMessageHeaderAccessor.getUser(captured.getHeaders()).getName()).isEqualTo("joe");
assertThat(messageCaptured(sess2, "sub1", "/foo")).isTrue();
assertThat(messageCaptured(sess2, "sub2", "/foo")).isTrue();
assertThat(messageCaptured(sess2, "sub3", "/bar")).isTrue();
}
@Test
void connect() {
String id = "sess1";
Message<String> connectMessage = startSession(id);
Message<?> connectAckMessage = this.messageCaptor.getValue();
SimpMessageHeaderAccessor connectAckHeaders = SimpMessageHeaderAccessor.wrap(connectAckMessage);
assertThat(connectAckHeaders.getHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER)).isEqualTo(connectMessage);
assertThat(connectAckHeaders.getSessionId()).isEqualTo(id);
assertThat(connectAckHeaders.getUser().getName()).isEqualTo("joe");
assertThat(SimpMessageHeaderAccessor.getHeartbeat(connectAckHeaders.getMessageHeaders())).isEqualTo(new long[] {10000, 10000});
}
@Test
void heartbeatValueWithAndWithoutTaskScheduler() {
assertThat(this.messageHandler.getHeartbeatValue()).isNull();
this.messageHandler.setTaskScheduler(this.taskScheduler);
assertThat(this.messageHandler.getHeartbeatValue()).isNotNull();
assertThat(this.messageHandler.getHeartbeatValue()).isEqualTo(new long[] {10000, 10000});
}
@Test
void startWithHeartbeatValueWithoutTaskScheduler() {
this.messageHandler.setHeartbeatValue(new long[] {10000, 10000});
assertThatIllegalArgumentException().isThrownBy(
this.messageHandler::start);
}
@Test
@SuppressWarnings("rawtypes")
public void startAndStopWithHeartbeatValue() {
ScheduledFuture future = mock();
given(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), eq(Duration.ofMillis(15000)))).willReturn(future);
this.messageHandler.setTaskScheduler(this.taskScheduler);
this.messageHandler.setHeartbeatValue(new long[] {15000, 16000});
this.messageHandler.start();
verify(this.taskScheduler).scheduleWithFixedDelay(any(Runnable.class), eq(Duration.ofMillis(15000)));
verifyNoMoreInteractions(this.taskScheduler, future);
this.messageHandler.stop();
verify(future).cancel(true);
verifyNoMoreInteractions(future);
}
@Test
void startWithOneZeroHeartbeatValue() {
this.messageHandler.setTaskScheduler(this.taskScheduler);
this.messageHandler.setHeartbeatValue(new long[] {0, 10000});
this.messageHandler.start();
verify(this.taskScheduler).scheduleWithFixedDelay(any(Runnable.class), eq(Duration.ofMillis(10000)));
}
@Test
void readInactivity() throws Exception {
this.messageHandler.setHeartbeatValue(new long[] {0, 1});
this.messageHandler.setTaskScheduler(this.taskScheduler);
this.messageHandler.start();
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(this.taskScheduler).scheduleWithFixedDelay(taskCaptor.capture(), eq(Duration.ofMillis(1)));
Runnable heartbeatTask = taskCaptor.getValue();
assertThat(heartbeatTask).isNotNull();
String id = "sess1";
TestPrincipal user = new TestPrincipal("joe");
Message<String> connectMessage = createConnectMessage(id, user, new long[] {1, 0});
this.messageHandler.handleMessage(connectMessage);
Thread.sleep(10);
heartbeatTask.run();
verify(this.clientOutChannel, atLeast(2)).send(this.messageCaptor.capture());
List<Message<?>> messages = this.messageCaptor.getAllValues();
assertThat(messages).hasSize(2);
MessageHeaders headers = messages.get(0).getHeaders();
assertThat(headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)).isEqualTo(SimpMessageType.CONNECT_ACK);
headers = messages.get(1).getHeaders();
assertThat(headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)).isEqualTo(SimpMessageType.DISCONNECT_ACK);
assertThat(headers.get(SimpMessageHeaderAccessor.SESSION_ID_HEADER)).isEqualTo(id);
assertThat(headers.get(SimpMessageHeaderAccessor.USER_HEADER)).isEqualTo(user);
}
@Test
void writeInactivity() throws Exception {
this.messageHandler.setHeartbeatValue(new long[] {1, 0});
this.messageHandler.setTaskScheduler(this.taskScheduler);
this.messageHandler.start();
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(this.taskScheduler).scheduleWithFixedDelay(taskCaptor.capture(), eq(Duration.ofMillis(1)));
Runnable heartbeatTask = taskCaptor.getValue();
assertThat(heartbeatTask).isNotNull();
String id = "sess1";
TestPrincipal user = new TestPrincipal("joe");
Message<String> connectMessage = createConnectMessage(id, user, new long[] {0, 1});
this.messageHandler.handleMessage(connectMessage);
Thread.sleep(10);
heartbeatTask.run();
verify(this.clientOutChannel, times(2)).send(this.messageCaptor.capture());
List<Message<?>> messages = this.messageCaptor.getAllValues();
assertThat(messages).hasSize(2);
MessageHeaders headers = messages.get(0).getHeaders();
assertThat(headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)).isEqualTo(SimpMessageType.CONNECT_ACK);
headers = messages.get(1).getHeaders();
assertThat(headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)).isEqualTo(SimpMessageType.HEARTBEAT);
assertThat(headers.get(SimpMessageHeaderAccessor.SESSION_ID_HEADER)).isEqualTo(id);
assertThat(headers.get(SimpMessageHeaderAccessor.USER_HEADER)).isEqualTo(user);
}
@Test
void readWriteIntervalCalculation() throws Exception {
this.messageHandler.setHeartbeatValue(new long[] {1, 1});
this.messageHandler.setTaskScheduler(this.taskScheduler);
this.messageHandler.start();
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(this.taskScheduler).scheduleWithFixedDelay(taskCaptor.capture(), eq(Duration.ofMillis(1)));
Runnable heartbeatTask = taskCaptor.getValue();
assertThat(heartbeatTask).isNotNull();
String id = "sess1";
TestPrincipal user = new TestPrincipal("joe");
Message<String> connectMessage = createConnectMessage(id, user, new long[] {10000, 10000});
this.messageHandler.handleMessage(connectMessage);
Thread.sleep(10);
heartbeatTask.run();
verify(this.clientOutChannel, times(1)).send(this.messageCaptor.capture());
List<Message<?>> messages = this.messageCaptor.getAllValues();
assertThat(messages).hasSize(1);
assertThat(messages.get(0).getHeaders().get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER)).isEqualTo(SimpMessageType.CONNECT_ACK);
}
private Message<String> startSession(String id) {
this.messageHandler.start();
Message<String> connectMessage = createConnectMessage(id, new TestPrincipal("joe"), null);
this.messageHandler.setTaskScheduler(this.taskScheduler);
this.messageHandler.handleMessage(connectMessage);
verify(this.clientOutChannel, times(1)).send(this.messageCaptor.capture());
reset(this.clientOutChannel);
return connectMessage;
}
private Message<String> createSubscriptionMessage(String sessionId, String subscriptionId, String destination) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.SUBSCRIBE);
headers.setSubscriptionId(subscriptionId);
headers.setDestination(destination);
headers.setSessionId(sessionId);
return MessageBuilder.createMessage("", headers.getMessageHeaders());
}
private Message<String> createConnectMessage(String sessionId, Principal user, long[] heartbeat) {
SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
accessor.setSessionId(sessionId);
accessor.setUser(user);
accessor.setHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER, heartbeat);
return MessageBuilder.createMessage("", accessor.getMessageHeaders());
}
private Message<String> createMessage(String destination, String payload) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headers.setDestination(destination);
return MessageBuilder.createMessage(payload, headers.getMessageHeaders());
}
private boolean messageCaptured(String sessionId, String subscriptionId, String destination) {
for (Message<?> message : this.messageCaptor.getAllValues()) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
if (sessionId.equals(headers.getSessionId())) {
if (subscriptionId.equals(headers.getSubscriptionId())) {
if (destination.equals(headers.getDestination())) {
return true;
}
}
}
}
return false;
}
}
| SimpleBrokerMessageHandlerTests |
java | redisson__redisson | redisson/src/main/java/org/redisson/mapreduce/MapReduceTimeoutException.java | {
"start": 736,
"end": 868
} | class ____ extends RedisException {
private static final long serialVersionUID = -198991995396319360L;
}
| MapReduceTimeoutException |
java | apache__hadoop | hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/Nfs3Status.java | {
"start": 917,
"end": 5636
} | class ____ {
/** Indicates the call completed successfully. */
public final static int NFS3_OK = 0;
/**
* The operation was not allowed because the caller is either not a
* privileged user (root) or not the owner of the target of the operation.
*/
public final static int NFS3ERR_PERM = 1;
/**
* No such file or directory. The file or directory name specified does not
* exist.
*/
public final static int NFS3ERR_NOENT = 2;
/**
* I/O error. A hard error (for example, a disk error) occurred while
* processing the requested operation.
*/
public final static int NFS3ERR_IO = 5;
/** I/O error. No such device or address. */
public final static int NFS3ERR_NXIO = 6;
/**
* Permission denied. The caller does not have the correct permission to
* perform the requested operation. Contrast this with NFS3ERR_PERM, which
* restricts itself to owner or privileged user permission failures.
*/
public final static int NFS3ERR_ACCES = 13;
/** File exists. The file specified already exists. */
public final static int NFS3ERR_EXIST = 17;
/** Attempt to do a cross-device hard link. */
public final static int NFS3ERR_XDEV = 18;
/** No such device. */
public final static int NFS3ERR_NODEV = 19;
/** The caller specified a non-directory in a directory operation. */
public static int NFS3ERR_NOTDIR = 20;
/** The caller specified a directory in a non-directory operation. */
public final static int NFS3ERR_ISDIR = 21;
/**
* Invalid argument or unsupported argument for an operation. Two examples are
* attempting a READLINK on an object other than a symbolic link or attempting
* to SETATTR a time field on a server that does not support this operation.
*/
public final static int NFS3ERR_INVAL = 22;
/**
* File too large. The operation would have caused a file to grow beyond the
* server's limit.
*/
public final static int NFS3ERR_FBIG = 27;
/**
* No space left on device. The operation would have caused the server's file
* system to exceed its limit.
*/
public final static int NFS3ERR_NOSPC = 28;
/**
* Read-only file system. A modifying operation was attempted on a read-only
* file system.
*/
public final static int NFS3ERR_ROFS = 30;
/** Too many hard links. */
public final static int NFS3ERR_MLINK = 31;
/** The filename in an operation was too long. */
public final static int NFS3ERR_NAMETOOLONG = 63;
/** An attempt was made to remove a directory that was not empty. */
public final static int NFS3ERR_NOTEMPTY = 66;
/**
* Resource (quota) hard limit exceeded. The user's resource limit on the
* server has been exceeded.
*/
public final static int NFS3ERR_DQUOT = 69;
/**
* The file handle given in the arguments was invalid. The file referred to by
* that file handle no longer exists or access to it has been revoked.
*/
public final static int NFS3ERR_STALE = 70;
/**
* The file handle given in the arguments referred to a file on a non-local
* file system on the server.
*/
public final static int NFS3ERR_REMOTE = 71;
/** The file handle failed internal consistency checks */
public final static int NFS3ERR_BADHANDLE = 10001;
/**
* Update synchronization mismatch was detected during a SETATTR operation.
*/
public final static int NFS3ERR_NOT_SYNC = 10002;
/** READDIR or READDIRPLUS cookie is stale */
public final static int NFS3ERR_BAD_COOKIE = 10003;
/** Operation is not supported */
public final static int NFS3ERR_NOTSUPP = 10004;
/** Buffer or request is too small */
public final static int NFS3ERR_TOOSMALL = 10005;
/**
* An error occurred on the server which does not map to any of the legal NFS
* version 3 protocol error values. The client should translate this into an
* appropriate error. UNIX clients may choose to translate this to EIO.
*/
public final static int NFS3ERR_SERVERFAULT = 10006;
/**
* An attempt was made to create an object of a type not supported by the
* server.
*/
public final static int NFS3ERR_BADTYPE = 10007;
/**
* The server initiated the request, but was not able to complete it in a
* timely fashion. The client should wait and then try the request with a new
* RPC transaction ID. For example, this error should be returned from a
* server that supports hierarchical storage and receives a request to process
* a file that has been migrated. In this case, the server should start the
* immigration process and respond to client with this error.
*/
public final static int NFS3ERR_JUKEBOX = 10008;
}
| Nfs3Status |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/vld/ValidatePolymBaseTypeTest.java | {
"start": 1505,
"end": 1687
} | class ____ {
public BadValue value;
protected DefTypeBadWrapper() { value = new BadValue(); }
}
// // // Validator implementations
static | DefTypeBadWrapper |
java | apache__logging-log4j2 | log4j-1.2-api/src/main/java/org/apache/log4j/builders/rolling/TimeBasedRollingPolicyBuilder.java | {
"start": 1430,
"end": 2204
} | class ____ extends AbstractBuilder<TriggeringPolicy>
implements TriggeringPolicyBuilder {
public TimeBasedRollingPolicyBuilder(final String prefix, final Properties props) {
super(prefix, props);
}
public TimeBasedRollingPolicyBuilder() {
super();
}
@Override
public TimeBasedTriggeringPolicy parse(final Element element, final XmlConfiguration configuration) {
return createTriggeringPolicy();
}
@Override
public TimeBasedTriggeringPolicy parse(final PropertiesConfiguration configuration) {
return createTriggeringPolicy();
}
private TimeBasedTriggeringPolicy createTriggeringPolicy() {
return TimeBasedTriggeringPolicy.newBuilder().build();
}
}
| TimeBasedRollingPolicyBuilder |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/TorchserveComponentBuilderFactory.java | {
"start": 1429,
"end": 1957
} | interface ____ {
/**
* TorchServe (camel-torchserve)
* Provide access to PyTorch TorchServe servers to run inference with
* PyTorch models remotely
*
* Category: ai
* Since: 4.9
* Maven coordinates: org.apache.camel:camel-torchserve
*
* @return the dsl builder
*/
static TorchserveComponentBuilder torchserve() {
return new TorchserveComponentBuilderImpl();
}
/**
* Builder for the TorchServe component.
*/
| TorchserveComponentBuilderFactory |
java | spring-projects__spring-boot | module/spring-boot-servlet/src/test/java/org/springframework/boot/servlet/autoconfigure/HttpEncodingAutoConfigurationTests.java | {
"start": 6745,
"end": 7004
} | class ____ {
@Bean
OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter();
}
@Bean
OrderedFormContentFilter formContentFilter() {
return new OrderedFormContentFilter();
}
}
}
| OrderedConfiguration |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/googlevertexai/embeddings/GoogleVertexAiEmbeddingsRequestTaskSettingsTests.java | {
"start": 572,
"end": 3380
} | class ____ extends ESTestCase {
public void testFromMap_ReturnsEmptySettings_IfMapEmpty() {
var requestTaskSettings = GoogleVertexAiEmbeddingsRequestTaskSettings.fromMap(new HashMap<>());
assertThat(requestTaskSettings, is(GoogleVertexAiEmbeddingsRequestTaskSettings.EMPTY_SETTINGS));
}
public void testFromMap_ReturnsEmptySettings_IfMapNull() {
var requestTaskSettings = GoogleVertexAiEmbeddingsRequestTaskSettings.fromMap(null);
assertThat(requestTaskSettings, is(GoogleVertexAiEmbeddingsRequestTaskSettings.EMPTY_SETTINGS));
}
public void testFromMap_DoesNotThrowValidationException_IfAutoTruncateIsMissing() {
var requestTaskSettings = GoogleVertexAiEmbeddingsRequestTaskSettings.fromMap(new HashMap<>(Map.of("unrelated", true)));
assertThat(requestTaskSettings, is(new GoogleVertexAiEmbeddingsRequestTaskSettings(null, null)));
}
public void testFromMap_ExtractsAutoTruncate() {
var autoTruncate = true;
var requestTaskSettings = GoogleVertexAiEmbeddingsRequestTaskSettings.fromMap(
new HashMap<>(Map.of(GoogleVertexAiEmbeddingsTaskSettings.AUTO_TRUNCATE, autoTruncate))
);
assertThat(requestTaskSettings, is(new GoogleVertexAiEmbeddingsRequestTaskSettings(autoTruncate, null)));
}
public void testFromMap_ThrowsValidationException_IfAutoTruncateIsInvalidValue() {
expectThrows(
ValidationException.class,
() -> GoogleVertexAiEmbeddingsRequestTaskSettings.fromMap(
new HashMap<>(Map.of(GoogleVertexAiEmbeddingsTaskSettings.AUTO_TRUNCATE, "invalid"))
)
);
}
public void testFromMap_ExtractsInputType() {
var requestTaskSettings = GoogleVertexAiEmbeddingsRequestTaskSettings.fromMap(
new HashMap<>(Map.of(GoogleVertexAiEmbeddingsTaskSettings.INPUT_TYPE, InputType.INGEST.toString()))
);
assertThat(requestTaskSettings, is(new GoogleVertexAiEmbeddingsRequestTaskSettings(null, InputType.INGEST)));
}
public void testFromMap_ThrowsValidationException_IfInputTypeIsInvalidValue() {
expectThrows(
ValidationException.class,
() -> GoogleVertexAiEmbeddingsRequestTaskSettings.fromMap(
new HashMap<>(Map.of(GoogleVertexAiEmbeddingsTaskSettings.INPUT_TYPE, "abc"))
)
);
}
public void testFromMap_ThrowsValidationException_IfInputTypeIsUnspecified() {
expectThrows(
ValidationException.class,
() -> GoogleVertexAiEmbeddingsRequestTaskSettings.fromMap(
new HashMap<>(Map.of(GoogleVertexAiEmbeddingsTaskSettings.INPUT_TYPE, InputType.UNSPECIFIED.toString()))
)
);
}
}
| GoogleVertexAiEmbeddingsRequestTaskSettingsTests |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/SoapDataFormat.java | {
"start": 4729,
"end": 4827
} | class ____ a given
* soap fault name.
* <p/>
* The following three element strategy | for |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/InsecureCipherModeTest.java | {
"start": 5514,
"end": 8444
} | class ____ {
Cipher cipher;
// Make sure that the checker is enabled inside constructors.
public CipherWrapper() {
try {
// BUG: Diagnostic contains: the mode and padding must be explicitly specified
cipher = Cipher.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
// We don't handle any exception as this code is not meant to be executed.
} catch (NoSuchPaddingException e) {
// We don't handle any exception as this code is not meant to be executed.
}
}
}
static Cipher complexCipher1;
static {
try {
String algorithm = "AES";
// BUG: Diagnostic contains: the transformation is not a compile-time constant
complexCipher1 = Cipher.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
// We don't handle any exception as this code is not meant to be executed.
} catch (NoSuchPaddingException e) {
// We don't handle any exception as this code is not meant to be executed.
}
}
static Cipher complexCipher2;
static {
try {
String transformation = "AES";
transformation += "/ECB";
transformation += "/NoPadding";
// BUG: Diagnostic contains: the transformation is not a compile-time constant
complexCipher2 = Cipher.getInstance(transformation);
} catch (NoSuchAlgorithmException e) {
// We don't handle any exception as this code is not meant to be executed.
} catch (NoSuchPaddingException e) {
// We don't handle any exception as this code is not meant to be executed.
}
}
static Cipher IesCipher;
static {
try {
// BUG: Diagnostic contains: the mode and padding must be explicitly specified
IesCipher = Cipher.getInstance("ECIES");
// BUG: Diagnostic contains: IES
IesCipher = Cipher.getInstance("ECIES/DHAES/NoPadding");
// BUG: Diagnostic contains: IES
IesCipher = Cipher.getInstance("ECIESWITHAES/NONE/PKCS5Padding");
// BUG: Diagnostic contains: IES
IesCipher = Cipher.getInstance("DHIESWITHAES/DHAES/PKCS7Padding");
// BUG: Diagnostic contains: IES
IesCipher = Cipher.getInstance("ECIESWITHDESEDE/NONE/NOPADDING");
// BUG: Diagnostic contains: IES
IesCipher = Cipher.getInstance("DHIESWITHDESEDE/DHAES/PKCS5PADDING");
// BUG: Diagnostic contains: IES
IesCipher = Cipher.getInstance("ECIESWITHAES/CBC/PKCS7PADDING");
// BUG: Diagnostic contains: IES
IesCipher = Cipher.getInstance("ECIESWITHAES-CBC/NONE/PKCS5PADDING");
// BUG: Diagnostic contains: IES
IesCipher = Cipher.getInstance("ECIESwithDESEDE-CBC/DHAES/NOPADDING");
} catch (NoSuchAlgorithmException e) {
// We don't handle any exception as this code is not meant to be executed.
} catch (NoSuchPaddingException e) {
// We don't handle any exception as this code is not meant to be executed.
}
}
| CipherWrapper |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/RedisHandshake.java | {
"start": 16157,
"end": 19149
} | class ____ {
private static final Pattern DECIMALS = Pattern.compile("(\\d+)");
private final static RedisVersion UNKNOWN = new RedisVersion("0.0.0");
private final static RedisVersion UNSTABLE = new RedisVersion("255.255.255");
private final int major;
private final int minor;
private final int bugfix;
private RedisVersion(String version) {
int major = 0;
int minor = 0;
int bugfix = 0;
LettuceAssert.notNull(version, "Version must not be null");
Matcher matcher = DECIMALS.matcher(version);
if (matcher.find()) {
major = Integer.parseInt(matcher.group(1));
if (matcher.find()) {
minor = Integer.parseInt(matcher.group(1));
}
if (matcher.find()) {
bugfix = Integer.parseInt(matcher.group(1));
}
}
this.major = major;
this.minor = minor;
this.bugfix = bugfix;
}
/**
* Construct a new {@link RedisVersion} from a version string containing major, minor and bugfix version such as
* {@code 7.2.0}.
*
* @param version
* @return
*/
public static RedisVersion of(String version) {
return new RedisVersion(version);
}
public boolean isGreaterThan(RedisVersion version) {
return this.compareTo(version) > 0;
}
public boolean isGreaterThanOrEqualTo(RedisVersion version) {
return this.compareTo(version) >= 0;
}
public boolean is(RedisVersion version) {
return this.equals(version);
}
public boolean isLessThan(RedisVersion version) {
return this.compareTo(version) < 0;
}
public boolean isLessThanOrEqualTo(RedisVersion version) {
return this.compareTo(version) <= 0;
}
public int compareTo(RedisVersion that) {
if (this.major != that.major) {
return this.major - that.major;
} else if (this.minor != that.minor) {
return this.minor - that.minor;
} else {
return this.bugfix - that.bugfix;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RedisVersion that = (RedisVersion) o;
return major == that.major && minor == that.minor && bugfix == that.bugfix;
}
@Override
public int hashCode() {
return Objects.hash(major, minor, bugfix);
}
@Override
public String toString() {
return major + "." + minor + "." + bugfix;
}
}
}
| RedisVersion |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/SameNameButDifferentTest.java | {
"start": 1462,
"end": 1635
} | class ____ {}
}
""")
.addSourceLines(
"B.java",
"""
import java.util.function.Supplier;
| Supplier |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inject/guice/InjectOnFinalFieldTest.java | {
"start": 898,
"end": 1514
} | class ____ {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(InjectOnFinalField.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceLines(
"InjectOnFinalFieldPositiveCases.java",
"""
package com.google.errorprone.bugpatterns.inject.guice.testdata;
import com.google.inject.Inject;
import org.jspecify.annotations.Nullable;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
public | InjectOnFinalFieldTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/ReloadAssociatedEntitiesTest.java | {
"start": 6816,
"end": 7414
} | class ____<ONE extends AbsOne<?>, THREE> {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "three_id")
private THREE three;
@OneToMany(mappedBy = "two")
private Set<ONE> ones = new HashSet<>();
public AbsTwo() {
}
public AbsTwo(String name, THREE three) {
this.name = name;
this.three = three;
}
public Long getId() {
return id;
}
public THREE getThree() {
return three;
}
public Set<ONE> getOnes() {
return ones;
}
}
@Entity(name = "ConcreteThree")
public static | AbsTwo |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/dev/testing/TestClassUsages.java | {
"start": 4863,
"end": 5826
} | class ____ implements Serializable {
private final String className;
private final UniqueId uniqueId;
private ClassAndMethod(String className, UniqueId uniqueId) {
this.className = className;
this.uniqueId = uniqueId;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ClassAndMethod that = (ClassAndMethod) o;
return Objects.equals(className, that.className) &&
Objects.equals(uniqueId, that.uniqueId);
}
@Override
public int hashCode() {
return Objects.hash(className, uniqueId);
}
public String getClassName() {
return className;
}
public UniqueId getUniqueId() {
return uniqueId;
}
}
}
| ClassAndMethod |
java | google__error-prone | core/src/test/java/com/google/errorprone/matchers/MethodReturnsNonNullNextTokenTest.java | {
"start": 1070,
"end": 1288
} | class ____ extends CompilerBasedAbstractTest {
@Test
public void shouldMatch() {
writeFile(
"A.java",
"""
import java.util.StringTokenizer;
public | MethodReturnsNonNullNextTokenTest |
java | elastic__elasticsearch | plugins/repository-hdfs/src/yamlRestTest/java/org/elasticsearch/repositories/hdfs/RepositoryHdfsClientYamlTestSuiteIT.java | {
"start": 1427,
"end": 2413
} | class ____ extends ESClientYamlSuiteTestCase {
public static HdfsFixture hdfsFixture = new HdfsFixture();
public static ElasticsearchCluster cluster = ElasticsearchCluster.local()
.distribution(DistributionType.DEFAULT)
.plugin("repository-hdfs")
.setting("xpack.license.self_generated.type", "trial")
.setting("xpack.security.enabled", "false")
.build();
@ClassRule
public static TestRule ruleChain = RuleChain.outerRule(hdfsFixture).around(cluster);
public RepositoryHdfsClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) {
super(testCandidate);
}
@Override
protected String getTestRestCluster() {
return cluster.getHttpAddresses();
}
@ParametersFactory
public static Iterable<Object[]> parameters() throws Exception {
return createParameters(Map.of("hdfs_port", hdfsFixture.getPort()), "hdfs_repository");
}
}
| RepositoryHdfsClientYamlTestSuiteIT |
java | apache__camel | components/camel-thrift/src/test/java/org/apache/camel/component/thrift/generated/Calculator.java | {
"start": 175936,
"end": 185380
} | enum ____ implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short) 0, "success");
private static final java.util.Map<java.lang.String, _Fields> byName
= new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 0: // SUCCESS
return SUCCESS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
@Override
public short getThriftFieldId() {
return _thriftId;
}
@Override
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap
= new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(
"success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, Work.class)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_result.class, metaDataMap);
}
public echo_result() {
}
public echo_result(
Work success) {
this();
this.success = success;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public echo_result(echo_result other) {
if (other.isSetSuccess()) {
this.success = new Work(other.success);
}
}
@Override
public echo_result deepCopy() {
return new echo_result(this);
}
@Override
public void clear() {
this.success = null;
}
@org.apache.thrift.annotation.Nullable
public Work getSuccess() {
return this.success;
}
public echo_result setSuccess(@org.apache.thrift.annotation.Nullable Work success) {
this.success = success;
return this;
}
public void unsetSuccess() {
this.success = null;
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return this.success != null;
}
public void setSuccessIsSet(boolean value) {
if (!value) {
this.success = null;
}
}
@Override
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((Work) value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
@Override
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return getSuccess();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
@Override
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof echo_result)
return this.equals((echo_result) that);
return false;
}
public boolean equals(echo_result that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_success = true && this.isSetSuccess();
boolean that_present_success = true && that.isSetSuccess();
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (!this.success.equals(that.success))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287);
if (isSetSuccess())
hashCode = hashCode * 8191 + success.hashCode();
return hashCode;
}
@Override
public int compareTo(echo_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetSuccess(), other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
@Override
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("echo_result(");
boolean first = true;
sb.append("success:");
if (this.success == null) {
sb.append("null");
} else {
sb.append(this.success);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
if (success != null) {
success.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static | _Fields |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/MyProduceBean.java | {
"start": 941,
"end": 1098
} | class ____ {
@Produce("seda:bar")
private ProducerTemplate bar;
public void doSomething(String s) {
bar.sendBody(s);
}
}
| MyProduceBean |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/model/Key.java | {
"start": 4515,
"end": 4657
} | class ____
* contributes it to the graph.
*
* @see #multibindingContributionIdentifier()
*/
@AutoValue
public abstract static | that |
java | elastic__elasticsearch | x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/BaseFilteredMonitoringDocTestCase.java | {
"start": 1056,
"end": 4491
} | class ____<F extends FilteredMonitoringDoc> extends BaseMonitoringDocTestCase<F> {
@Override
protected final void assertMonitoringDoc(final F document) {
assertFilteredMonitoringDoc(document);
assertXContentFilters(document);
}
/**
* Asserts that the specific fields of a {@link FilteredMonitoringDoc} have
* the expected values.
*/
protected abstract void assertFilteredMonitoringDoc(F document);
/**
* Returns the expected list of XContent filters for the {@link FilteredMonitoringDoc}
*/
protected abstract Set<String> getExpectedXContentFilters();
/**
* Asserts that the XContent filters of a {@link FilteredMonitoringDoc} contains
* the common filters and the expected custom ones.
*/
private void assertXContentFilters(final F document) {
final Set<String> expectedFilters = Sets.union(COMMON_XCONTENT_FILTERS, getExpectedXContentFilters());
final Set<String> actualFilters = document.getFilters();
expectedFilters.forEach(filter -> assertThat(actualFilters, hasItem(filter)));
assertThat(actualFilters.size(), equalTo(expectedFilters.size()));
}
public void testConstructorFiltersMustNotBeNull() {
expectThrows(
NullPointerException.class,
() -> new TestFilteredMonitoringDoc(cluster, timestamp, interval, node, system, type, id, null)
);
}
public void testConstructorFiltersMustNotBeEmpty() {
final IllegalArgumentException e = expectThrows(
IllegalArgumentException.class,
() -> new TestFilteredMonitoringDoc(cluster, timestamp, interval, node, system, type, id, emptySet())
);
assertThat(e.getMessage(), equalTo("xContentFilters must not be empty"));
}
public void testFilteredMonitoringDocToXContent() throws IOException {
final Set<String> filters = Sets.newHashSetWithExpectedSize(5);
filters.add("_type.field_1");
filters.add("_type.field_3");
filters.add("_type.field_5.sub_*");
final MonitoringDoc.Node node = new MonitoringDoc.Node("_uuid", "_host", "_addr", "_ip", "_name", 1504169190855L);
final TestFilteredMonitoringDoc document = new TestFilteredMonitoringDoc(
"_cluster",
1502266739402L,
1506593717631L,
node,
MonitoredSystem.ES,
"_type",
"_id",
filters
);
final BytesReference xContent = XContentHelper.toXContent(document, XContentType.JSON, false);
final String expected = """
{
"cluster_uuid": "_cluster",
"timestamp": "2017-08-09T08:18:59.402Z",
"interval_ms": 1506593717631,
"type": "_type",
"source_node": {
"uuid": "_uuid",
"host": "_host",
"transport_address": "_addr",
"ip": "_ip",
"name": "_name",
"timestamp": "2017-08-31T08:46:30.855Z"
},
"_type": {
"field_1": 1,
"field_3": {
"sub_field_3": 3
},
"field_5": [ { "sub_field_5": 5 } ]
}
}""";
assertEquals(XContentHelper.stripWhitespace(expected), xContent.utf8ToString());
}
| BaseFilteredMonitoringDocTestCase |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/junit4/FailureExpectedHandler.java | {
"start": 2164,
"end": 2424
} | class ____ extends Exception {
public FailureExpectedTestPassedException(FrameworkMethod frameworkMethod) {
super( "Test marked as FailureExpected, but did not fail : " + Helper.extractTestName( frameworkMethod ) );
}
}
}
| FailureExpectedTestPassedException |
java | apache__camel | components/camel-mllp/src/test/java/org/apache/camel/test/junit/rule/mllp/MllpClientResource.java | {
"start": 17273,
"end": 17334
} | enum ____ {
CLOSE,
RESET
}
}
| DisconnectMethod |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/operators/MailOptionsImpl.java | {
"start": 979,
"end": 1699
} | class ____ implements MailboxExecutor.MailOptions {
static final MailboxExecutor.MailOptions DEFAULT = new MailOptionsImpl(false, false);
static final MailboxExecutor.MailOptions DEFERRABLE = new MailOptionsImpl(false, true);
static final MailboxExecutor.MailOptions URGENT = new MailOptionsImpl(true, false);
private final boolean isUrgent;
private final boolean deferrable;
private MailOptionsImpl(boolean isUrgent, boolean deferrable) {
this.isUrgent = isUrgent;
this.deferrable = deferrable;
}
@Override
public boolean isDeferrable() {
return deferrable;
}
@Override
public boolean isUrgent() {
return isUrgent;
}
}
| MailOptionsImpl |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/features/CollectionFeature.java | {
"start": 4133,
"end": 4249
} | interface ____ {
CollectionFeature[] value() default {};
CollectionFeature[] absent() default {};
}
}
| Require |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/operators/CollectionExecutor.java | {
"start": 23045,
"end": 25448
} | class ____ implements Visitor<Operator<?>> {
private final Set<Operator<?>> visited = new HashSet<Operator<?>>();
private final Set<Operator<?>> dynamicPathOperations;
public DynamicPathCollector(Set<Operator<?>> dynamicPathOperations) {
this.dynamicPathOperations = dynamicPathOperations;
}
@Override
public boolean preVisit(Operator<?> op) {
return visited.add(op);
}
@Override
public void postVisit(Operator<?> op) {
if (op instanceof SingleInputOperator) {
SingleInputOperator<?, ?, ?> siop = (SingleInputOperator<?, ?, ?>) op;
if (dynamicPathOperations.contains(siop.getInput())) {
dynamicPathOperations.add(op);
} else {
for (Operator<?> o : siop.getBroadcastInputs().values()) {
if (dynamicPathOperations.contains(o)) {
dynamicPathOperations.add(op);
break;
}
}
}
} else if (op instanceof DualInputOperator) {
DualInputOperator<?, ?, ?, ?> siop = (DualInputOperator<?, ?, ?, ?>) op;
if (dynamicPathOperations.contains(siop.getFirstInput())) {
dynamicPathOperations.add(op);
} else if (dynamicPathOperations.contains(siop.getSecondInput())) {
dynamicPathOperations.add(op);
} else {
for (Operator<?> o : siop.getBroadcastInputs().values()) {
if (dynamicPathOperations.contains(o)) {
dynamicPathOperations.add(op);
break;
}
}
}
} else if (op.getClass() == PartialSolutionPlaceHolder.class
|| op.getClass() == WorksetPlaceHolder.class
|| op.getClass() == SolutionSetPlaceHolder.class) {
dynamicPathOperations.add(op);
} else if (op instanceof GenericDataSourceBase) {
// skip
} else {
throw new RuntimeException(
"Cannot handle operator type " + op.getClass().getName());
}
}
}
private | DynamicPathCollector |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/RemoveUnusedImportsTest.java | {
"start": 14824,
"end": 14975
} | class ____ extends A {
int test() {
return MINUTES;
}
}
""")
.doTest();
}
}
| B |
java | elastic__elasticsearch | test/fixtures/minio-fixture/src/main/java/org/elasticsearch/test/fixtures/minio/MinioTestContainer.java | {
"start": 741,
"end": 2945
} | class ____ extends DockerEnvironmentAwareTestContainer {
/*
* Known issues broken down by MinIO release date:
* [< 2025-05-24 ] known issue https://github.com/minio/minio/issues/21189; workaround in #127166
* [= 2025-05-24 ] known issue https://github.com/minio/minio/issues/21377; no workaround
* [> 2025-05-24 && < 2025-09-07] known issue https://github.com/minio/minio/issues/21456; workaround in #131815
* [>= 2025-09-07 ] no known issues (yet)
*/
public static final String DOCKER_BASE_IMAGE = "minio/minio:RELEASE.2025-09-07T16-13-09Z";
private static final int servicePort = 9000;
private final boolean enabled;
/**
* for packer caching only
* see CacheCacheableTestFixtures.
* */
protected MinioTestContainer() {
this(true, "minio", "minio123", "test-bucket");
}
public MinioTestContainer(boolean enabled, String accessKey, String secretKey, String bucketName) {
super(
new ImageFromDockerfile("es-minio-testfixture").withDockerfileFromBuilder(
builder -> builder.from(DOCKER_BASE_IMAGE)
.env("MINIO_ACCESS_KEY", accessKey)
.env("MINIO_SECRET_KEY", secretKey)
.run("mkdir -p /minio/data/" + bucketName)
.cmd("server", "/minio/data")
.build()
)
);
if (enabled) {
addExposedPort(servicePort);
// The following waits for a specific log message as the readiness signal. When the minio docker image
// gets upgraded in future, we must ensure the log message still exists or update it here accordingly.
// Otherwise the tests using the minio fixture will fail with timeout on waiting the container to be ready.
setWaitStrategy(Wait.forLogMessage("API: .*:9000.*", 1));
}
this.enabled = enabled;
}
@Override
public void start() {
if (enabled) {
super.start();
}
}
public String getAddress() {
return "http://127.0.0.1:" + getMappedPort(servicePort);
}
}
| MinioTestContainer |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/dialect/OffsetFetchLimitHandlerTest.java | {
"start": 302,
"end": 483
} | class ____ extends AbstractLimitHandlerTest {
@Override
protected AbstractLimitHandler getLimitHandler() {
return OffsetFetchLimitHandler.INSTANCE;
}
}
| OffsetFetchLimitHandlerTest |
java | spring-projects__spring-security | crypto/src/main/java/org/springframework/security/crypto/password4j/Password4jPasswordEncoder.java | {
"start": 1116,
"end": 1484
} | class ____ package-private and should not be used directly. Instead, use the
* specific public subclasses that support verified hashing algorithms such as BCrypt,
* Argon2, and SCrypt implementations.
* </p>
*
* <p>
* This implementation is thread-safe and can be shared across multiple threads.
* </p>
*
* @author Mehrdad Bozorgmehr
* @since 7.0
*/
abstract | is |
java | netty__netty | transport/src/main/java/io/netty/channel/socket/nio/NioChannelOption.java | {
"start": 1217,
"end": 4365
} | class ____<T> extends ChannelOption<T> {
private final SocketOption<T> option;
@SuppressWarnings("deprecation")
private NioChannelOption(SocketOption<T> option) {
super(option.name());
this.option = option;
}
/**
* Returns a {@link ChannelOption} for the given {@link java.net.SocketOption}.
*/
public static <T> ChannelOption<T> of(SocketOption<T> option) {
return new NioChannelOption<T>(option);
}
// Internal helper methods to remove code duplication between Nio*Channel implementations.
static <T> boolean setOption(Channel jdkChannel, NioChannelOption<T> option, T value) {
NetworkChannel channel = (NetworkChannel) jdkChannel;
if (!channel.supportedOptions().contains(option.option)) {
return false;
}
if (channel instanceof ServerSocketChannel && option.option == StandardSocketOptions.IP_TOS) {
// Skip IP_TOS as a workaround for a JDK bug:
// See https://mail.openjdk.java.net/pipermail/nio-dev/2018-August/005365.html
return false;
}
try {
channel.setOption(option.option, value);
return true;
} catch (IOException e) {
throw new ChannelException(e);
}
}
static <T> T getOption(Channel jdkChannel, NioChannelOption<T> option) {
NetworkChannel channel = (NetworkChannel) jdkChannel;
if (!channel.supportedOptions().contains(option.option)) {
return null;
}
if (channel instanceof ServerSocketChannel && option.option == StandardSocketOptions.IP_TOS) {
// Skip IP_TOS as a workaround for a JDK bug:
// See https://mail.openjdk.java.net/pipermail/nio-dev/2018-August/005365.html
return null;
}
try {
return channel.getOption(option.option);
} catch (IOException e) {
throw new ChannelException(e);
}
}
@SuppressWarnings("unchecked")
static ChannelOption<?>[] getOptions(Channel jdkChannel) {
NetworkChannel channel = (NetworkChannel) jdkChannel;
Set<SocketOption<?>> supportedOpts = channel.supportedOptions();
if (channel instanceof ServerSocketChannel) {
List<ChannelOption<?>> extraOpts = new ArrayList<ChannelOption<?>>(supportedOpts.size());
for (SocketOption<?> opt : supportedOpts) {
if (opt == StandardSocketOptions.IP_TOS) {
// Skip IP_TOS as a workaround for a JDK bug:
// See https://mail.openjdk.java.net/pipermail/nio-dev/2018-August/005365.html
continue;
}
extraOpts.add(new NioChannelOption(opt));
}
return extraOpts.toArray(new ChannelOption[0]);
} else {
ChannelOption<?>[] extraOpts = new ChannelOption[supportedOpts.size()];
int i = 0;
for (SocketOption<?> opt : supportedOpts) {
extraOpts[i++] = new NioChannelOption(opt);
}
return extraOpts;
}
}
}
| NioChannelOption |
java | apache__camel | core/camel-core-languages/src/main/java/org/apache/camel/language/simple/SimpleExpressionBuilder.java | {
"start": 42739,
"end": 46271
} | enum ____
if (type.isEnum()) {
Class<Enum<?>> enumClass = (Class<Enum<?>>) type;
for (Enum<?> enumValue : enumClass.getEnumConstants()) {
if (enumValue.name().equalsIgnoreCase(after)) {
return type.cast(enumValue);
}
}
throw CamelExecutionException.wrapCamelExecutionException(exchange,
new ClassNotFoundException("Cannot find enum: " + after + " on type: " + type));
} else {
// we assume it is a field constant
Object answer = ObjectHelper.lookupConstantFieldValue(type, after);
if (answer != null) {
return answer;
}
}
}
}
throw CamelExecutionException.wrapCamelExecutionException(exchange,
new ClassNotFoundException("Cannot find type: " + text));
}
@Override
public String toString() {
return "type:" + name;
}
};
}
/**
* Returns an expression for the property value of exchange with the given name invoking methods defined in a simple
* OGNL notation
*
* @param ognl methods to invoke on the property in a simple OGNL syntax
*/
public static Expression propertyOgnlExpression(final String ognl) {
return new KeyedOgnlExpressionAdapter(
ognl, "propertyOgnl(" + ognl + ")",
(exchange, exp) -> {
String text = exp.evaluate(exchange, String.class);
return exchange.getProperty(text);
});
}
/**
* Returns the expression for the exchange's exception invoking methods defined in a simple OGNL notation
*
* @param ognl methods to invoke on the body in a simple OGNL syntax
*/
public static Expression exchangeExceptionOgnlExpression(final String ognl) {
return new ExpressionAdapter() {
private Language bean;
@Override
public Object evaluate(Exchange exchange) {
Object exception = exchange.getException();
if (exception == null) {
exception = exchange.getProperty(ExchangePropertyKey.EXCEPTION_CAUGHT, Exception.class);
}
if (exception == null) {
return null;
}
// ognl is able to evaluate method name if it contains nested functions
// so we should not eager evaluate ognl as a string
Expression ognlExp = bean.createExpression(null, new Object[] { null, exception, ognl });
ognlExp.init(exchange.getContext());
return ognlExp.evaluate(exchange, Object.class);
}
@Override
public void init(CamelContext context) {
bean = context.resolveLanguage("bean");
}
@Override
public String toString() {
return "exchangeExceptionOgnl(" + ognl + ")";
}
};
}
/**
* Expression adapter for OGNL expression from Message Header or Exchange property
*/
public static | constants |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/user/AuthenticateResponse.java | {
"start": 786,
"end": 2726
} | class ____ extends ActionResponse implements ToXContent {
public static final TransportVersion VERSION_OPERATOR_FIELD = TransportVersions.V_8_10_X;
private final Authentication authentication;
private final boolean operator;
public AuthenticateResponse(StreamInput in) throws IOException {
authentication = new Authentication(in);
if (in.getTransportVersion().onOrAfter(VERSION_OPERATOR_FIELD)) {
operator = in.readBoolean();
} else {
operator = false;
}
}
public AuthenticateResponse(Authentication authentication, boolean operator) {
this.authentication = Objects.requireNonNull(authentication);
this.operator = operator;
}
public Authentication authentication() {
return authentication;
}
public boolean isOperator() {
return operator;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
authentication.writeTo(out);
if (out.getTransportVersion().onOrAfter(VERSION_OPERATOR_FIELD)) {
out.writeBoolean(operator);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
authentication.toXContentFragment(builder);
if (this.operator) {
builder.field("operator", true);
}
return builder.endObject();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AuthenticateResponse that = (AuthenticateResponse) o;
return this.operator == that.operator && this.authentication.equals(that.authentication);
}
@Override
public int hashCode() {
return Objects.hash(authentication, operator);
}
}
| AuthenticateResponse |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/inheritance/singletable/PaperTrash.java | {
"start": 249,
"end": 284
} | class ____ extends Trash {
}
| PaperTrash |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/builtin/mapper/CalendarToStringMapper.java | {
"start": 457,
"end": 794
} | interface ____ {
CalendarToStringMapper INSTANCE = Mappers.getMapper( CalendarToStringMapper.class );
@Mappings( {
@Mapping( target = "prop", dateFormat = "dd.MM.yyyy" ),
@Mapping( target = "publicProp", dateFormat = "dd.MM.yyyy" )
} )
StringProperty map( CalendarProperty source );
}
| CalendarToStringMapper |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/google/ListGenerators.java | {
"start": 4868,
"end": 5096
} | class ____ extends TestUnhashableListGenerator {
@Override
public List<UnhashableObject> create(UnhashableObject[] elements) {
return ImmutableList.copyOf(elements);
}
}
}
| UnhashableElementsImmutableListGenerator |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryBasedWrapperOptions.java | {
"start": 587,
"end": 1399
} | class ____ implements WrapperOptions {
private final SessionFactoryImplementor factory;
SessionFactoryBasedWrapperOptions(SessionFactoryImplementor factory) {
this.factory = factory;
}
@Override
public SharedSessionContractImplementor getSession() {
throw new UnsupportedOperationException( "No session" );
}
@Override
public SessionFactoryImplementor getSessionFactory() {
return factory;
}
@Override
public LobCreator getLobCreator() {
return factory.getJdbcServices().getLobCreator( getSession() );
}
@Override
public FormatMapper getXmlFormatMapper() {
return factory.getSessionFactoryOptions().getXmlFormatMapper();
}
@Override
public FormatMapper getJsonFormatMapper() {
return factory.getSessionFactoryOptions().getJsonFormatMapper();
}
}
| SessionFactoryBasedWrapperOptions |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/convert/CoerceEmptyToInt3234Test.java | {
"start": 402,
"end": 477
} | class ____ {
public long value = 7L;
}
static | BasicLongWrapper |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/metainfo/StateMetaInfoSnapshotReadersWriters.java | {
"start": 3716,
"end": 5313
} | class ____ implements StateMetaInfoWriter {
private static final CurrentWriterImpl INSTANCE = new CurrentWriterImpl();
@Override
public void writeStateMetaInfoSnapshot(
@Nonnull StateMetaInfoSnapshot snapshot, @Nonnull DataOutputView outputView)
throws IOException {
final Map<String, String> optionsMap = snapshot.getOptionsImmutable();
final Map<String, TypeSerializerSnapshot<?>> serializerConfigSnapshotsMap =
snapshot.getSerializerSnapshotsImmutable();
outputView.writeUTF(snapshot.getName());
outputView.writeInt(snapshot.getBackendStateType().ordinal());
outputView.writeInt(optionsMap.size());
for (Map.Entry<String, String> entry : optionsMap.entrySet()) {
outputView.writeUTF(entry.getKey());
outputView.writeUTF(entry.getValue());
}
outputView.writeInt(serializerConfigSnapshotsMap.size());
for (Map.Entry<String, TypeSerializerSnapshot<?>> entry :
serializerConfigSnapshotsMap.entrySet()) {
final String key = entry.getKey();
outputView.writeUTF(entry.getKey());
TypeSerializerSnapshotSerializationUtil.writeSerializerSnapshot(
outputView, (TypeSerializerSnapshot) entry.getValue());
}
}
}
/**
* Implementation of {@link StateMetaInfoReader} for the current version and generic for all
* state types.
*/
static | CurrentWriterImpl |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/booleanarrays/BooleanArrays_assertEmpty_Test.java | {
"start": 1489,
"end": 2240
} | class ____ extends BooleanArraysBaseTest {
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertEmpty(someInfo(), null))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_is_not_empty() {
AssertionInfo info = someInfo();
boolean[] actual = { true, false };
Throwable error = catchThrowable(() -> arrays.assertEmpty(info, actual));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldBeEmpty(actual));
}
@Test
void should_pass_if_actual_is_empty() {
arrays.assertEmpty(someInfo(), emptyArray());
}
}
| BooleanArrays_assertEmpty_Test |
java | elastic__elasticsearch | modules/lang-painless/src/doc/java/org/elasticsearch/painless/PainlessInfoJson.java | {
"start": 13144,
"end": 16663
} | class ____ implements ToXContentObject {
private final String declaring;
private final List<String> parameters;
private final List<String> parameterNames;
private final JavadocExtractor.ParsedJavadoc javadoc;
public static final ParseField JAVADOC = new ParseField("javadoc");
public static final ParseField PARAMETER_NAMES = new ParseField("parameter_names");
private Constructor(
String declaring,
List<String> parameters,
List<String> parameterNames,
JavadocExtractor.ParsedJavadoc javadoc
) {
this.declaring = declaring;
this.parameters = parameters;
this.parameterNames = parameterNames;
this.javadoc = javadoc;
}
public static List<Constructor> fromInfos(List<PainlessContextConstructorInfo> infos, Map<String, String> javaNamesToDisplayNames) {
List<Constructor> constructors = new ArrayList<>(infos.size());
for (PainlessContextConstructorInfo info : infos) {
List<String> parameterTypes = toDisplayParameterTypes(info.getParameters(), javaNamesToDisplayNames);
constructors.add(new Constructor(info.getDeclaring(), parameterTypes, null, null));
}
return constructors;
}
private static List<Constructor> fromInfos(
List<PainlessContextConstructorInfo> infos,
Map<String, String> javaNamesToDisplayNames,
JavadocExtractor.ParsedJavaClass parsed,
JavadocExtractor extractor,
String className
) throws IOException {
List<Constructor> constructors = new ArrayList<>(infos.size());
for (PainlessContextConstructorInfo info : infos) {
List<String> parameterTypes = toDisplayParameterTypes(info.getParameters(), javaNamesToDisplayNames);
List<String> parameterNames = null;
JavadocExtractor.ParsedJavadoc javadoc = null;
JavadocExtractor.ParsedMethod parsedMethod = parsed.getConstructor(parameterTypes);
if ((parsedMethod == null || parsedMethod.isEmpty()) && className.equals(info.getDeclaring()) == false) {
parsedMethod = extractor.parseClass(info.getDeclaring()).getConstructor(parameterTypes);
}
if (parsedMethod != null) {
parameterNames = parsedMethod.parameterNames();
javadoc = parsedMethod.javadoc();
}
constructors.add(new Constructor(info.getDeclaring(), parameterTypes, parameterNames, javadoc));
}
return constructors;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(PainlessContextConstructorInfo.DECLARING.getPreferredName(), declaring);
builder.field(PainlessContextConstructorInfo.PARAMETERS.getPreferredName(), parameters);
if (parameterNames != null && parameterNames.size() > 0) {
builder.field(PARAMETER_NAMES.getPreferredName(), parameterNames);
}
if (javadoc != null && javadoc.isEmpty() == false) {
builder.field(JAVADOC.getPreferredName(), javadoc);
}
builder.endObject();
return builder;
}
}
public static | Constructor |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/id/insert/Binder.java | {
"start": 234,
"end": 336
} | interface ____ {
void bindValues(PreparedStatement ps) throws SQLException;
Object getEntity();
}
| Binder |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/FluxScan.java | {
"start": 1515,
"end": 2113
} | class ____<T> extends InternalFluxOperator<T, T> {
final BiFunction<T, ? super T, T> accumulator;
FluxScan(Flux<? extends T> source, BiFunction<T, ? super T, T> accumulator) {
super(source);
this.accumulator = Objects.requireNonNull(accumulator, "accumulator");
}
@Override
public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) {
return new ScanSubscriber<>(actual, accumulator);
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return super.scanUnsafe(key);
}
static final | FluxScan |
java | google__gson | gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java | {
"start": 23613,
"end": 23725
} | class ____ one of its fields
@JsonAdapter(WithDelegatingFactoryOnClassAndField.Factory.class)
private static | and |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCSQueueStore.java | {
"start": 1740,
"end": 11613
} | class ____ {
private final ResourceCalculator resourceCalculator =
new DefaultResourceCalculator();
private CSQueue root;
private CapacitySchedulerContext csContext;
private CapacitySchedulerQueueContext queueContext;
@BeforeEach
public void setUp() throws IOException {
CapacitySchedulerConfiguration csConf =
new CapacitySchedulerConfiguration();
YarnConfiguration conf = new YarnConfiguration();
RMContext rmContext = TestUtils.getMockRMContext();
Resource clusterResource = Resources.createResource(
10 * 16 * 1024, 10 * 32);
csContext = mock(CapacitySchedulerContext.class);
when(csContext.getConfiguration()).thenReturn(csConf);
when(csContext.getConf()).thenReturn(conf);
when(csContext.getMinimumResourceCapability()).
thenReturn(Resources.createResource(1024, 1));
when(csContext.getMaximumResourceCapability()).
thenReturn(Resources.createResource(16*1024, 32));
when(csContext.getClusterResource()).
thenReturn(clusterResource);
when(csContext.getResourceCalculator()).
thenReturn(resourceCalculator);
when(csContext.getRMContext()).thenReturn(rmContext);
when(csContext.getCapacitySchedulerQueueManager()).thenReturn(
new CapacitySchedulerQueueManager(csConf, null, null));
queueContext = new CapacitySchedulerQueueContext(csContext);
CSQueueStore queues = new CSQueueStore();
root = CapacitySchedulerQueueManager
.parseQueue(queueContext, csConf, null, "root",
queues, queues,
TestUtils.spyHook);
}
public CSQueue createLeafQueue(String name, CSQueue parent)
throws IOException {
return new LeafQueue(queueContext, name, parent, null);
}
public CSQueue createParentQueue(String name, CSQueue parent)
throws IOException {
return new ParentQueue(queueContext, name, parent, null);
}
/**
* Asserts the queue can be accessed via it's full path and short name.
* @param store Store against we do the assertion
* @param queue The queue we need to look up
*/
public void assertAccessibleByAllNames(CSQueueStore store, CSQueue queue) {
assertEquals(queue, store.get(queue.getQueueShortName()));
assertEquals(queue, store.get(queue.getQueuePath()));
}
/**
* Asserts the queue can be accessed via it's full path only, using it's
* short name supposed to return something else.
*
* This is a result of forcefully making root always referencing the root
* since "root" is considered a full path, hence no other queue with short
* name root should be accessible via root.
*
* @param store Store against we do the assertion
* @param queue The queue we need to look up
*/
public void assertAccessibleByFullNameOnly(
CSQueueStore store, CSQueue queue) {
assertFalse(store.isAmbiguous(queue.getQueueShortName()));
assertNotEquals(queue, store.get(queue.getQueueShortName()));
assertEquals(queue, store.get(queue.getQueuePath()));
}
/**
* Asserts the queue can be accessed via it's full path only, using it's
* short name supposed to return null, this is the case when there are two
* leaf queues are present with the same name. (or two parent queues with
* no leaf queue with the same name)
* @param store Store against we do the assertion
* @param queue The queue we need to look up
*/
public void assertAmbiguous(CSQueueStore store, CSQueue queue) {
assertTrue(store.isAmbiguous(queue.getQueueShortName()));
assertNull(store.get(queue.getQueueShortName()));
assertEquals(queue, store.get(queue.getQueuePath()));
}
/**
* Asserts the queue is not present in the store.
* @param store Store against we do the assertion
* @param queue The queue we need to look up
*/
public void assertQueueNotPresent(CSQueueStore store, CSQueue queue) {
assertNotEquals(queue, store.get(queue.getQueueShortName()));
assertNull(store.get(queue.getQueuePath()));
}
@Test
public void testSimpleMapping() throws IOException {
CSQueueStore store = new CSQueueStore();
//root.main
CSQueue main = createParentQueue("main", root);
//root.main.A
CSQueue mainA = createLeafQueue("A", main);
//root.main.B
CSQueue mainB = createParentQueue("B", main);
//root.main.B.C
CSQueue mainBC = createLeafQueue("C", mainB);
store.add(main);
store.add(mainA);
store.add(mainB);
store.add(mainBC);
assertAccessibleByAllNames(store, main);
assertAccessibleByAllNames(store, mainA);
assertAccessibleByAllNames(store, mainB);
assertAccessibleByAllNames(store, mainBC);
}
@Test
public void testAmbiguousMapping() throws IOException {
CSQueueStore store = new CSQueueStore();
//root.main
CSQueue main = createParentQueue("main", root);
//root.main.A
CSQueue mainA = createParentQueue("A", main);
//root.main.A.C
CSQueue mainAC = createLeafQueue("C", mainA);
//root.main.A.D
CSQueue mainAD = createParentQueue("D", mainA);
//root.main.A.D.E
CSQueue mainADE = createLeafQueue("E", mainAD);
//root.main.A.D.F
CSQueue mainADF = createLeafQueue("F", mainAD);
//root.main.B
CSQueue mainB = createParentQueue("B", main);
//root.main.B.C
CSQueue mainBC = createLeafQueue("C", mainB);
//root.main.B.D
CSQueue mainBD = createParentQueue("D", mainB);
//root.main.B.D.E
CSQueue mainBDE = createLeafQueue("E", mainBD);
//root.main.B.D.G
CSQueue mainBDG = createLeafQueue("G", mainBD);
store.add(main);
store.add(mainA);
store.add(mainAC);
store.add(mainAD);
store.add(mainADE);
store.add(mainADF);
store.add(mainB);
store.add(mainBC);
store.add(mainBD);
store.add(mainBDE);
store.add(mainBDG);
assertAccessibleByAllNames(store, main);
assertAccessibleByAllNames(store, mainA);
assertAccessibleByAllNames(store, mainB);
assertAccessibleByAllNames(store, mainADF);
assertAccessibleByAllNames(store, mainBDG);
assertAmbiguous(store, mainAC);
assertAmbiguous(store, mainAD);
assertAmbiguous(store, mainADE);
assertAmbiguous(store, mainBC);
assertAmbiguous(store, mainBD);
assertAmbiguous(store, mainBDE);
}
@Test
public void testDynamicModifications() throws IOException {
CSQueueStore store = new CSQueueStore();
//root.main
CSQueue main = createParentQueue("main", root);
//root.main.A
CSQueue mainA = createParentQueue("A", main);
//root.main.B
CSQueue mainB = createParentQueue("B", main);
//root.main.A.C
CSQueue mainAC = createLeafQueue("C", mainA);
//root.main.B.C
CSQueue mainBC = createLeafQueue("C", mainB);
store.add(main);
store.add(mainA);
store.add(mainB);
assertAccessibleByAllNames(store, main);
assertAccessibleByAllNames(store, mainA);
assertAccessibleByAllNames(store, mainB);
assertQueueNotPresent(store, mainAC);
assertQueueNotPresent(store, mainBC);
store.add(mainAC);
assertAccessibleByAllNames(store, mainAC);
assertQueueNotPresent(store, mainBC);
store.add(mainBC);
assertAmbiguous(store, mainAC);
assertAmbiguous(store, mainBC);
store.remove(mainAC);
assertQueueNotPresent(store, mainAC);
assertAccessibleByAllNames(store, mainBC);
store.remove(mainBC);
assertQueueNotPresent(store, mainAC);
assertQueueNotPresent(store, mainBC);
}
@Test
public void testQueueOverwrites() throws IOException {
CSQueueStore store = new CSQueueStore();
//root.main
CSQueue main = createParentQueue("main", root);
//root.main.A
CSQueue mainA = createLeafQueue("A", main);
//root.main.B
CSQueue newA = createLeafQueue("A", main);
store.add(main);
store.add(mainA);
assertAccessibleByAllNames(store, mainA);
store.add(newA);
//this implicitly checks mainA is not longer accessible by it's names
assertAccessibleByAllNames(store, newA);
}
@Test
public void testQueueReferencePrecedence() throws IOException {
CSQueueStore store = new CSQueueStore();
//root.main.a.b
//root.second.a.d.b.c
// a - ambiguous both instances are parent queues
// b - leaf queue b takes precedence over parent queue b
//root.main
CSQueue main = createParentQueue("main", root);
//root.main.A
CSQueue mainA = createParentQueue("A", main);
//root.main.A.B
CSQueue mainAB = createLeafQueue("B", mainA);
//root.second
CSQueue second = createParentQueue("second", root);
//root.second.A
CSQueue secondA = createParentQueue("A", second);
//root.second.A.B
CSQueue secondAD = createParentQueue("D", secondA);
//root.second.A.B.D
CSQueue secondADB = createParentQueue("B", secondAD);
//root.second.A.B.D.C
CSQueue secondADBC = createLeafQueue("C", secondADB);
store.add(main);
store.add(mainA);
store.add(mainAB);
store.add(second);
store.add(secondA);
store.add(secondAD);
store.add(secondADB);
store.add(secondADBC);
assertAccessibleByAllNames(store, main);
assertAccessibleByAllNames(store, second);
assertAmbiguous(store, mainA);
assertAmbiguous(store, secondA);
assertAmbiguous(store, mainAB);
assertAccessibleByAllNames(store, secondAD);
assertAmbiguous(store, secondADB);
assertAccessibleByAllNames(store, secondADBC);
}
@Test
public void testRootIsAlwaysAccesible() throws IOException {
CSQueueStore store = new CSQueueStore();
//root.root
CSQueue rootroot = createParentQueue("root", root);
store.add(root);
store.add(rootroot);
assertAccessibleByAllNames(store, root);
assertAccessibleByFullNameOnly(store, rootroot);
assertFalse(store.isAmbiguous("root"));
}
} | TestCSQueueStore |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/support/caching/MapCacheAccessor.java | {
"start": 248,
"end": 657
} | class ____<K, V> implements CacheAccessor<K, V> {
private final Map<K, V> map;
MapCacheAccessor(Map<K, V> map) {
this.map = map;
}
@Override
public V get(K key) {
return map.get(key);
}
@Override
public void put(K key, V value) {
map.put(key, value);
}
@Override
public void evict(K key) {
map.remove(key);
}
}
| MapCacheAccessor |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/store/op/NodeToLabelOp.java | {
"start": 1444,
"end": 2555
} | class ____
extends FSNodeStoreLogOp<CommonNodeLabelsManager> {
private Map<NodeId, Set<String>> nodeToLabels;
public static final int OPCODE = 1;
@Override
public void write(OutputStream os, CommonNodeLabelsManager mgr)
throws IOException {
((ReplaceLabelsOnNodeRequestPBImpl) ReplaceLabelsOnNodeRequest
.newInstance(nodeToLabels)).getProto().writeDelimitedTo(os);
}
@Override
public void recover(InputStream is, CommonNodeLabelsManager mgr)
throws IOException {
nodeToLabels = new ReplaceLabelsOnNodeRequestPBImpl(
YarnServerResourceManagerServiceProtos.ReplaceLabelsOnNodeRequestProto
.parseDelimitedFrom(is)).getNodeToLabels();
if (mgr.isCentralizedConfiguration()) {
mgr.replaceLabelsOnNode(nodeToLabels);
}
}
public NodeToLabelOp setNodeToLabels(
Map<NodeId, Set<String>> nodeToLabelsList) {
this.nodeToLabels = nodeToLabelsList;
return this;
}
public Map<NodeId, Set<String>> getNodeToLabels() {
return nodeToLabels;
}
@Override
public int getOpCode() {
return OPCODE;
}
} | NodeToLabelOp |
java | netty__netty | transport-udt/src/main/java/io/netty/channel/udt/UdtServerChannelConfig.java | {
"start": 1471,
"end": 3492
} | interface ____ extends UdtChannelConfig {
/**
* Gets {@link KindUDT#ACCEPTOR} channel backlog via
* {@link ChannelOption#SO_BACKLOG}.
*/
int getBacklog();
/**
* Sets {@link KindUDT#ACCEPTOR} channel backlog via
* {@link ChannelOption#SO_BACKLOG}.
*/
UdtServerChannelConfig setBacklog(int backlog);
@Override
UdtServerChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis);
@Override
@Deprecated
UdtServerChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead);
@Override
UdtServerChannelConfig setWriteSpinCount(int writeSpinCount);
@Override
UdtServerChannelConfig setAllocator(ByteBufAllocator allocator);
@Override
UdtServerChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator);
@Override
UdtServerChannelConfig setAutoRead(boolean autoRead);
@Override
UdtServerChannelConfig setAutoClose(boolean autoClose);
@Override
UdtServerChannelConfig setProtocolReceiveBufferSize(int size);
@Override
UdtServerChannelConfig setProtocolSendBufferSize(int size);
@Override
UdtServerChannelConfig setReceiveBufferSize(int receiveBufferSize);
@Override
UdtServerChannelConfig setReuseAddress(boolean reuseAddress);
@Override
UdtServerChannelConfig setSendBufferSize(int sendBufferSize);
@Override
UdtServerChannelConfig setSoLinger(int soLinger);
@Override
UdtServerChannelConfig setSystemReceiveBufferSize(int size);
@Override
UdtServerChannelConfig setSystemSendBufferSize(int size);
@Override
UdtServerChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark);
@Override
UdtServerChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark);
@Override
UdtServerChannelConfig setWriteBufferWaterMark(WriteBufferWaterMark writeBufferWaterMark);
@Override
UdtServerChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator);
}
| UdtServerChannelConfig |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/InternalTimersSnapshotReaderWriters.java | {
"start": 7484,
"end": 7872
} | interface ____<K, N> {
/**
* Reads a timers snapshot from the provided input view.
*
* @param in the input view
* @return the read timers snapshot
* @throws IOException
*/
InternalTimersSnapshot<K, N> readTimersSnapshot(DataInputView in) throws IOException;
}
private abstract static | InternalTimersSnapshotReader |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/GlobalWindow.java | {
"start": 1220,
"end": 1805
} | class ____ extends Window {
private static final GlobalWindow INSTANCE = new GlobalWindow();
private GlobalWindow() {}
public static GlobalWindow get() {
return INSTANCE;
}
@Override
public long maxTimestamp() {
return Long.MAX_VALUE;
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object o) {
return this == o || !(o == null || getClass() != o.getClass());
}
@Override
public int compareTo(Window o) {
return 0;
}
public static | GlobalWindow |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_236.java | {
"start": 815,
"end": 2216
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "SELECT count(1) AS userCount,count(t.telephone) AS userWithPhoneCount,count(t.email) AS userWithEmailCount FROM (SELECT t.user_id , dw.telephone,dw.email FROM (SELECT dw.userid AS user_id FROM dw_user_property_wide_table_merged_v2 dw WHERE ((dw.is_sub = true))) t INNER JOIN dw_user_property_wide_table_merged_v2 dw ON t.user_id = dw.userid) t /*+META({\"s\": \"com.qunhe.logcomplex.userinformation.mapper.ads.UserPropertyMapper.countUser\"})*/";
SQLSelectStatement stmt = (SQLSelectStatement) SQLUtils.parseSingleMysqlStatement(sql);
assertEquals("SELECT count(1) AS userCount, count(t.telephone) AS userWithPhoneCount\n" +
"\t, count(t.email) AS userWithEmailCount\n" +
"FROM (\n" +
"\tSELECT t.user_id, dw.telephone, dw.email\n" +
"\tFROM (\n" +
"\t\tSELECT dw.userid AS user_id\n" +
"\t\tFROM dw_user_property_wide_table_merged_v2 dw\n" +
"\t\tWHERE (dw.is_sub = true)\n" +
"\t) t\n" +
"\t\tINNER JOIN dw_user_property_wide_table_merged_v2 dw ON t.user_id = dw.userid\n" +
") t /*+META({\"s\": \"com.qunhe.logcomplex.userinformation.mapper.ads.UserPropertyMapper.countUser\"})*/", stmt.toString());
}
}
| MySqlSelectTest_236 |
java | apache__camel | core/camel-core-reifier/src/main/java/org/apache/camel/reifier/errorhandler/DeadLetterChannelReifier.java | {
"start": 1756,
"end": 7895
} | class ____ extends ErrorHandlerReifier<DeadLetterChannelDefinition> {
public DeadLetterChannelReifier(Route route, DeadLetterChannelDefinition definition) {
super(route, definition);
}
@Override
public Processor createErrorHandler(Processor processor) throws Exception {
String uri = parseString(definition.getDeadLetterUri());
ObjectHelper.notNull(uri, "deadLetterUri", this);
// optimize to use shared default instance if using out of the box settings
RedeliveryPolicy redeliveryPolicy = resolveRedeliveryPolicy(definition, camelContext);
CamelLogger logger = resolveLogger(definition);
Processor deadLetterProcessor = createDeadLetterChannelProcessor(uri);
DeadLetterChannel answer = new DeadLetterChannel(
camelContext, processor, logger,
getProcessor(definition.getOnRedeliveryProcessor(), definition.getOnRedeliveryRef()),
redeliveryPolicy, deadLetterProcessor, uri,
parseBoolean(definition.getDeadLetterHandleNewException(), true),
parseBoolean(definition.getUseOriginalMessage(), false),
parseBoolean(definition.getUseOriginalBody(), false),
resolveRetryWhilePolicy(definition, camelContext),
getExecutorService(definition.getExecutorServiceBean(), definition.getExecutorServiceRef()),
getProcessor(definition.getOnPrepareFailureProcessor(), definition.getOnPrepareFailureRef()),
getProcessor(definition.getOnExceptionOccurredProcessor(), definition.getOnExceptionOccurredRef()));
// configure error handler before we can use it
configure(answer);
return answer;
}
private Predicate resolveRetryWhilePolicy(DeadLetterChannelDefinition definition, CamelContext camelContext) {
Predicate answer = definition.getRetryWhilePredicate();
if (answer == null && definition.getRetryWhileRef() != null) {
// it is a bean expression
Language bean = camelContext.resolveLanguage("bean");
answer = bean.createPredicate(definition.getRetryWhileRef());
answer.initPredicate(camelContext);
}
return answer;
}
private CamelLogger resolveLogger(DeadLetterChannelDefinition definition) {
CamelLogger answer = definition.getLoggerBean();
if (answer == null && definition.getLoggerRef() != null) {
answer = mandatoryLookup(definition.getLoggerRef(), CamelLogger.class);
}
if (answer == null) {
answer = new CamelLogger(LoggerFactory.getLogger(DeadLetterChannel.class), LoggingLevel.ERROR);
}
if (definition.getLevel() != null) {
answer.setLevel(parse(LoggingLevel.class, definition.getLevel()));
}
return answer;
}
private Processor createDeadLetterChannelProcessor(String uri) {
// wrap in our special safe fallback error handler if sending to
// dead letter channel fails
Processor child = new SendProcessor(camelContext.getEndpoint(uri), ExchangePattern.InOnly);
// force MEP to be InOnly so when sending to DLQ we would not expect
// a reply if the MEP was InOut
return new FatalFallbackErrorHandler(child, true);
}
private RedeliveryPolicy resolveRedeliveryPolicy(DeadLetterChannelDefinition definition, CamelContext camelContext) {
if (definition.hasRedeliveryPolicy() && definition.getRedeliveryPolicyRef() != null) {
throw new IllegalArgumentException(
"Cannot have both redeliveryPolicy and redeliveryPolicyRef set at the same time.");
}
RedeliveryPolicy answer = null;
RedeliveryPolicyDefinition def = definition.hasRedeliveryPolicy() ? definition.getRedeliveryPolicy() : null;
if (def == null && definition.getRedeliveryPolicyRef() != null) {
// ref may point to a definition
def = lookupByNameAndType(definition.getRedeliveryPolicyRef(), RedeliveryPolicyDefinition.class);
}
if (def != null) {
answer = ErrorHandlerReifier.createRedeliveryPolicy(def, camelContext, null);
}
if (def == null && definition.getRedeliveryPolicyRef() != null) {
answer = mandatoryLookup(definition.getRedeliveryPolicyRef(), RedeliveryPolicy.class);
}
if (answer == null) {
answer = RedeliveryPolicy.DEFAULT_POLICY;
}
return answer;
}
protected ScheduledExecutorService getExecutorService(
ScheduledExecutorService executorService, String executorServiceRef) {
lock.lock();
try {
if (executorService == null || executorService.isShutdown()) {
// camel context will shutdown the executor when it shutdown so no
// need to shut it down when stopping
if (executorServiceRef != null) {
executorService = lookupByNameAndType(executorServiceRef, ScheduledExecutorService.class);
if (executorService == null) {
ExecutorServiceManager manager = camelContext.getExecutorServiceManager();
ThreadPoolProfile profile = manager.getThreadPoolProfile(executorServiceRef);
executorService = manager.newScheduledThreadPool(this, executorServiceRef, profile);
}
if (executorService == null) {
throw new IllegalArgumentException("ExecutorService " + executorServiceRef + " not found in registry.");
}
} else {
// no explicit configured thread pool, so leave it up to the
// error handler to decide if it need a default thread pool from
// CamelContext#getErrorHandlerExecutorService
executorService = null;
}
}
return executorService;
} finally {
lock.unlock();
}
}
}
| DeadLetterChannelReifier |
java | spring-projects__spring-framework | spring-context-support/src/main/java/org/springframework/scheduling/quartz/JobDetailFactoryBean.java | {
"start": 1779,
"end": 6924
} | class ____
implements FactoryBean<JobDetail>, BeanNameAware, ApplicationContextAware, InitializingBean {
private @Nullable String name;
private @Nullable String group;
private @Nullable Class<? extends Job> jobClass;
private JobDataMap jobDataMap = new JobDataMap();
private boolean durability = false;
private boolean requestsRecovery = false;
private @Nullable String description;
private @Nullable String beanName;
private @Nullable ApplicationContext applicationContext;
private @Nullable String applicationContextJobDataKey;
private @Nullable JobDetail jobDetail;
/**
* Specify the job's name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Specify the job's group.
*/
public void setGroup(String group) {
this.group = group;
}
/**
* Specify the job's implementation class.
*/
public void setJobClass(Class<? extends Job> jobClass) {
this.jobClass = jobClass;
}
/**
* Set the job's JobDataMap.
* @see #setJobDataAsMap
*/
public void setJobDataMap(JobDataMap jobDataMap) {
this.jobDataMap = jobDataMap;
}
/**
* Return the job's JobDataMap.
*/
public JobDataMap getJobDataMap() {
return this.jobDataMap;
}
/**
* Register objects in the JobDataMap via a given Map.
* <p>These objects will be available to this Job only,
* in contrast to objects in the SchedulerContext.
* <p>Note: When using persistent Jobs whose JobDetail will be kept in the
* database, do not put Spring-managed beans or an ApplicationContext
* reference into the JobDataMap but rather into the SchedulerContext.
* @param jobDataAsMap a Map with String keys and any objects as values
* (for example Spring-managed beans)
* @see org.springframework.scheduling.quartz.SchedulerFactoryBean#setSchedulerContextAsMap
*/
public void setJobDataAsMap(Map<String, ?> jobDataAsMap) {
getJobDataMap().putAll(jobDataAsMap);
}
/**
* Specify the job's durability, i.e. whether it should remain stored
* in the job store even if no triggers point to it anymore.
*/
public void setDurability(boolean durability) {
this.durability = durability;
}
/**
* Set the recovery flag for this job, i.e. whether the job should
* get re-executed if a 'recovery' or 'fail-over' situation is encountered.
*/
public void setRequestsRecovery(boolean requestsRecovery) {
this.requestsRecovery = requestsRecovery;
}
/**
* Set a textual description for this job.
*/
public void setDescription(String description) {
this.description = description;
}
@Override
public void setBeanName(String beanName) {
this.beanName = beanName;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* Set the key of an ApplicationContext reference to expose in the JobDataMap,
* for example "applicationContext". Default is none.
* Only applicable when running in a Spring ApplicationContext.
* <p>In case of a QuartzJobBean, the reference will be applied to the Job
* instance as bean property. An "applicationContext" attribute will correspond
* to a "setApplicationContext" method in that scenario.
* <p>Note that BeanFactory callback interfaces like ApplicationContextAware
* are not automatically applied to Quartz Job instances, because Quartz
* itself is responsible for the lifecycle of its Jobs.
* <p><b>Note: When using persistent job stores where JobDetail contents will
* be kept in the database, do not put an ApplicationContext reference into
* the JobDataMap but rather into the SchedulerContext.</b>
* @see org.springframework.scheduling.quartz.SchedulerFactoryBean#setApplicationContextSchedulerContextKey
* @see org.springframework.context.ApplicationContext
*/
public void setApplicationContextJobDataKey(String applicationContextJobDataKey) {
this.applicationContextJobDataKey = applicationContextJobDataKey;
}
@Override
public void afterPropertiesSet() {
Assert.notNull(this.jobClass, "Property 'jobClass' is required");
if (this.name == null) {
this.name = this.beanName;
}
if (this.group == null) {
this.group = Scheduler.DEFAULT_GROUP;
}
if (this.applicationContextJobDataKey != null) {
if (this.applicationContext == null) {
throw new IllegalStateException(
"JobDetailBean needs to be set up in an ApplicationContext " +
"to be able to handle an 'applicationContextJobDataKey'");
}
getJobDataMap().put(this.applicationContextJobDataKey, this.applicationContext);
}
JobDetailImpl jdi = new JobDetailImpl();
jdi.setName(this.name != null ? this.name : toString());
jdi.setGroup(this.group);
jdi.setJobClass(this.jobClass);
jdi.setJobDataMap(this.jobDataMap);
jdi.setDurability(this.durability);
jdi.setRequestsRecovery(this.requestsRecovery);
jdi.setDescription(this.description);
this.jobDetail = jdi;
}
@Override
public @Nullable JobDetail getObject() {
return this.jobDetail;
}
@Override
public Class<?> getObjectType() {
return JobDetail.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
| JobDetailFactoryBean |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/store/RoleReference.java | {
"start": 8226,
"end": 9149
} | class ____ implements RoleReference {
private final RoleDescriptor roleDescriptor;
private final String source;
public FixedRoleReference(RoleDescriptor roleDescriptor, String source) {
this.roleDescriptor = roleDescriptor;
this.source = source;
}
@Override
public RoleKey id() {
return new RoleKey(Set.of(roleDescriptor.getName()), source);
}
@Override
public void resolve(RoleReferenceResolver resolver, ActionListener<RolesRetrievalResult> listener) {
final RolesRetrievalResult rolesRetrievalResult = new RolesRetrievalResult();
rolesRetrievalResult.addDescriptors(Set.of(roleDescriptor));
listener.onResponse(rolesRetrievalResult);
}
}
/**
* Same as {@link ApiKeyRoleReference} but for BWC purpose (prior to v7.9.0)
*/
final | FixedRoleReference |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/ThreadPoolProfileDefinition.java | {
"start": 1344,
"end": 7013
} | class ____ extends OptionalIdentifiedDefinition<ThreadPoolProfileDefinition> {
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean")
private String defaultProfile;
@XmlAttribute
@Metadata(javaType = "java.lang.Integer")
private String poolSize;
@XmlAttribute
@Metadata(javaType = "java.lang.Integer")
private String maxPoolSize;
@XmlAttribute
@Metadata(javaType = "java.lang.Long")
private String keepAliveTime;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.util.concurrent.TimeUnit",
enums = "NANOSECONDS,MICROSECONDS,MILLISECONDS,SECONDS,MINUTES,HOURS,DAYS")
private String timeUnit;
@XmlAttribute
@Metadata(javaType = "java.lang.Integer")
private String maxQueueSize;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean")
private String allowCoreThreadTimeOut;
@XmlAttribute
@Metadata(label = "advanced", javaType = "org.apache.camel.util.concurrent.ThreadPoolRejectedPolicy",
enums = "Abort,CallerRuns")
private String rejectedPolicy;
public ThreadPoolProfileDefinition() {
}
@Override
public String getShortName() {
return "threadPoolProfile";
}
@Override
public String getLabel() {
return "ThreadPoolProfile " + getId();
}
public ThreadPoolProfileDefinition poolSize(int poolSize) {
return poolSize(Integer.toString(poolSize));
}
public ThreadPoolProfileDefinition poolSize(String poolSize) {
setPoolSize(poolSize);
return this;
}
public ThreadPoolProfileDefinition maxPoolSize(int maxPoolSize) {
return maxPoolSize(Integer.toString(maxPoolSize));
}
public ThreadPoolProfileDefinition maxPoolSize(String maxPoolSize) {
setMaxPoolSize(maxPoolSize);
return this;
}
public ThreadPoolProfileDefinition keepAliveTime(long keepAliveTime) {
return keepAliveTime(Long.toString(keepAliveTime));
}
public ThreadPoolProfileDefinition keepAliveTime(String keepAliveTime) {
setKeepAliveTime(keepAliveTime);
return this;
}
public ThreadPoolProfileDefinition timeUnit(TimeUnit timeUnit) {
return timeUnit(timeUnit.name());
}
public ThreadPoolProfileDefinition timeUnit(String timeUnit) {
setTimeUnit(timeUnit);
return this;
}
public ThreadPoolProfileDefinition maxQueueSize(int maxQueueSize) {
return maxQueueSize(Integer.toString(maxQueueSize));
}
public ThreadPoolProfileDefinition maxQueueSize(String maxQueueSize) {
setMaxQueueSize(maxQueueSize);
return this;
}
public ThreadPoolProfileDefinition rejectedPolicy(ThreadPoolRejectedPolicy rejectedPolicy) {
setRejectedPolicy(rejectedPolicy.name());
return this;
}
public ThreadPoolProfileDefinition rejectedPolicy(String rejectedPolicy) {
setRejectedPolicy(rejectedPolicy);
return this;
}
public ThreadPoolProfileDefinition allowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) {
return allowCoreThreadTimeOut(Boolean.toString(allowCoreThreadTimeOut));
}
public ThreadPoolProfileDefinition allowCoreThreadTimeOut(String allowCoreThreadTimeOut) {
setAllowCoreThreadTimeOut(allowCoreThreadTimeOut);
return this;
}
public String getDefaultProfile() {
return defaultProfile;
}
/**
* Whether this profile is the default thread pool profile
*/
public void setDefaultProfile(String defaultProfile) {
this.defaultProfile = defaultProfile;
}
public String getPoolSize() {
return poolSize;
}
/**
* Sets the core pool size
*/
public void setPoolSize(String poolSize) {
this.poolSize = poolSize;
}
public String getMaxPoolSize() {
return maxPoolSize;
}
/**
* Sets the maximum pool size
*/
public void setMaxPoolSize(String maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public String getKeepAliveTime() {
return keepAliveTime;
}
/**
* Sets the keep alive time for idle threads in the pool
*/
public void setKeepAliveTime(String keepAliveTime) {
this.keepAliveTime = keepAliveTime;
}
public String getMaxQueueSize() {
return maxQueueSize;
}
/**
* Sets the maximum number of tasks in the work queue.
* <p/>
* Use <tt>-1</tt> or <tt>Integer.MAX_VALUE</tt> for an unbounded queue
*/
public void setMaxQueueSize(String maxQueueSize) {
this.maxQueueSize = maxQueueSize;
}
public String getAllowCoreThreadTimeOut() {
return allowCoreThreadTimeOut;
}
/**
* Whether idle core threads is allowed to timeout and therefore can shrink the pool size below the core pool size
* <p/>
* Is by default <tt>true</tt>
*/
public void setAllowCoreThreadTimeOut(String allowCoreThreadTimeOut) {
this.allowCoreThreadTimeOut = allowCoreThreadTimeOut;
}
public String getTimeUnit() {
return timeUnit;
}
/**
* Sets the time unit to use for keep alive time By default SECONDS is used.
*/
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
public String getRejectedPolicy() {
return rejectedPolicy;
}
/**
* Sets the handler for tasks which cannot be executed by the thread pool.
*/
public void setRejectedPolicy(String rejectedPolicy) {
this.rejectedPolicy = rejectedPolicy;
}
}
| ThreadPoolProfileDefinition |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/mock/MockPredicateTest.java | {
"start": 1028,
"end": 2050
} | class ____ extends ContextTestSupport {
@Test
public void testMockPredicate() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:foo");
mock.message(0).predicate().header("foo");
mock.expectedMessageCount(1);
template.sendBodyAndHeader("direct:start", "Hello World", "foo", "bar");
assertMockEndpointsSatisfied();
}
@Test
public void testMockPredicateAsParameter() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:foo");
mock.message(0).predicate(PredicateBuilder.isNotNull(header("foo")));
mock.expectedMessageCount(1);
template.sendBodyAndHeader("direct:start", "Hello World", "foo", "bar");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").to("mock:foo");
}
};
}
}
| MockPredicateTest |
java | spring-projects__spring-boot | core/spring-boot-testcontainers/src/test/java/org/springframework/boot/testcontainers/service/connection/ServiceConnectionContextCustomizerFactoryTests.java | {
"start": 7848,
"end": 8004
} | class ____ {
@ServiceConnection
private static InputStream service2 = new ByteArrayInputStream(new byte[0]);
}
static | ServiceConnectionOnWrongFieldType |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/search/arguments/AggregateArgs.java | {
"start": 29801,
"end": 32690
} | class ____<K, V> implements PipelineOperation<K, V> {
private final V expression;
private final K name;
public Apply(V expression, K name) {
this.expression = expression;
this.name = name;
}
@Override
public void build(CommandArgs<K, V> args) {
args.add(CommandKeyword.APPLY);
args.addValue(expression);
args.add(CommandKeyword.AS);
args.add(name.toString());
}
/**
* Static factory method to create an Apply instance with a single name and expression pair.
*
* @param name the name of the expression
* @param expression the expression to apply
* @param <K> Key type
* @param <V> Value type
* @return new Apply instance
*/
public static <K, V> Apply<K, V> of(V expression, K name) {
return new Apply<>(expression, name);
}
}
/**
* Represents a REDUCE function in a GROUPBY clause.
*
* <p>
* Reducers handle group entries in a GROUPBY operation, performing aggregate operations like counting, summing, averaging,
* or finding min/max values. Each reducer can have an optional alias using the AS keyword.
* </p>
*
* <h3>Example Usage:</h3>
*
* <pre>
*
* {
* @code
* // Count items in each group
* Reducer<String, String> count = Reducer.count().as("item_count");
*
* // Sum numeric values
* Reducer<String, String> totalSales = Reducer.sum("@sales").as("total_sales");
*
* // Calculate average
* Reducer<String, String> avgPrice = Reducer.avg("@price").as("average_price");
*
* // Find extremes
* Reducer<String, String> maxScore = Reducer.max("@score").as("highest_score");
* Reducer<String, String> minPrice = Reducer.min("@price").as("lowest_price");
*
* // Count distinct values
* Reducer<String, String> uniqueUsers = Reducer.countDistinct("@user_id").as("unique_users");
* }
* </pre>
*
* <h3>Available Reducer Functions:</h3>
* <ul>
* <li><strong>COUNT</strong> - Count the number of records in the group</li>
* <li><strong>SUM</strong> - Sum all numeric values of a field</li>
* <li><strong>AVG</strong> - Calculate the average of numeric values</li>
* <li><strong>MIN</strong> - Find the minimum value</li>
* <li><strong>MAX</strong> - Find the maximum value</li>
* <li><strong>COUNT_DISTINCT</strong> - Count unique values of a field</li>
* </ul>
*
* <p>
* If no alias is provided using {@code as()}, the resulting field name will be the function name combined with the field
* name (e.g., "count_distinct(@user_id)").
* </p>
*/
public static | Apply |
java | google__dagger | javatests/dagger/functional/producers/optional/OptionalBindingComponentsPresentTest.java | {
"start": 1277,
"end": 3184
} | class ____ {
@Parameters(name = "{0}")
public static Iterable<Object[]> parameters() {
return ImmutableList.copyOf(
new Object[][] {
{DaggerOptionalBindingComponents_PresentOptionalBindingComponent.create()},
{DaggerOptionalBindingComponents_AbsentOptionalBindingComponent.create().presentChild()},
{DaggerOptionalBindingComponents_PresentOptionalProvisionBindingComponent.create()}
});
}
private final OptionalBindingComponent component;
public OptionalBindingComponentsPresentTest(OptionalBindingComponent component) {
this.component = component;
}
@Test
public void optional() throws Exception {
assertThat(component.optionalInstance().get()).hasValue(VALUE);
}
@Test
public void optionalProducer() throws Exception {
assertThat(component.optionalProducer().get().get().get().get()).isEqualTo(VALUE);
}
@Test
public void optionalProduced() throws Exception {
assertThat(component.optionalProduced().get().get().get()).isEqualTo(VALUE);
}
@Test
public void qualifiedOptional() throws Exception {
assertThat(component.qualifiedOptionalInstance().get()).hasValue(QUALIFIED_VALUE);
}
@Test
public void qualifiedOptionalProducer() throws Exception {
assertThat(component.qualifiedOptionalProducer().get().get().get().get())
.isEqualTo(QUALIFIED_VALUE);
}
@Test
public void qualifiedOptionalProduced() throws Exception {
assertThat(component.qualifiedOptionalProduced().get().get().get()).isEqualTo(QUALIFIED_VALUE);
}
@Test
public void optionalNullableProducer() throws Exception {
assertThat(component.optionalNullableProducer().get().get().get().get()).isNull();
}
@Test
public void optionalNullableProduced() throws Exception {
assertThat(component.optionalNullableProduced().get().get().get()).isNull();
}
}
| OptionalBindingComponentsPresentTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/routing/allocation/shards/ShardsAvailabilityHealthIndicatorService.java | {
"start": 6036,
"end": 25285
} | class ____ implements HealthIndicatorService {
private static final Logger LOGGER = LogManager.getLogger(ShardsAvailabilityHealthIndicatorService.class);
public static final String NAME = "shards_availability";
private static final String DATA_TIER_ALLOCATION_DECIDER_NAME = "data_tier";
/**
* Changes the behavior of isNewlyCreatedAndInitializingReplica so that the
* shard_availability health indicator returns YELLOW if a primary
* is STARTED, but a replica is still INITIALIZING and the replica has been
* unassigned for less than the value of this setting. This function is
* only used in serverless, so this setting has no effect in stateless.
*/
public static final Setting<TimeValue> REPLICA_UNASSIGNED_BUFFER_TIME = Setting.timeSetting(
"health.shards_availability.replica_unassigned_buffer_time",
TimeValue.timeValueSeconds(5),
TimeValue.timeValueSeconds(0),
TimeValue.timeValueSeconds(20),
Setting.Property.NodeScope,
Setting.Property.Dynamic
);
private final ClusterService clusterService;
private final AllocationService allocationService;
private final SystemIndices systemIndices;
protected final ProjectResolver projectResolver;
private volatile TimeValue replicaUnassignedBufferTime;
public ShardsAvailabilityHealthIndicatorService(
ClusterService clusterService,
AllocationService allocationService,
SystemIndices systemIndices,
ProjectResolver projectResolver
) {
this.clusterService = clusterService;
this.allocationService = allocationService;
this.systemIndices = systemIndices;
this.replicaUnassignedBufferTime = REPLICA_UNASSIGNED_BUFFER_TIME.get(clusterService.getSettings());
clusterService.getClusterSettings().addSettingsUpdateConsumer(REPLICA_UNASSIGNED_BUFFER_TIME, this::setReplicaUnassignedBufferTime);
this.projectResolver = projectResolver;
}
private void setReplicaUnassignedBufferTime(TimeValue replicaUnassignedBufferTime) {
this.replicaUnassignedBufferTime = replicaUnassignedBufferTime;
}
@Override
public String name() {
return NAME;
}
/**
* Creates a new {@link ShardAllocationStatus} that will be used to track
* primary and replica availability, providing the color, diagnosis, and
* messages about the available or unavailable shards in the cluster.
* @param metadata Metadata for the cluster
* @param maxAffectedResourcesCount Max number of affect resources to return
* @return A new ShardAllocationStatus that has not yet been filled.
*/
public ShardAllocationStatus createNewStatus(Metadata metadata, int maxAffectedResourcesCount) {
return new ShardAllocationStatus(metadata, maxAffectedResourcesCount);
}
@Override
public HealthIndicatorResult calculate(boolean verbose, int maxAffectedResourcesCount, HealthInfo healthInfo) {
var state = clusterService.state();
var shutdown = state.getMetadata().custom(NodesShutdownMetadata.TYPE, NodesShutdownMetadata.EMPTY);
var status = createNewStatus(state.getMetadata(), maxAffectedResourcesCount);
updateShardAllocationStatus(status, state, shutdown, verbose, replicaUnassignedBufferTime);
return createIndicator(
status.getStatus(),
status.getSymptom(),
status.getDetails(verbose),
status.getImpacts(),
status.getDiagnosis(verbose, maxAffectedResourcesCount)
);
}
static void updateShardAllocationStatus(
ShardAllocationStatus status,
ClusterState state,
NodesShutdownMetadata shutdown,
boolean verbose,
TimeValue replicaUnassignedBufferTime
) {
for (Map.Entry<ProjectId, RoutingTable> entries : state.globalRoutingTable().routingTables().entrySet()) {
ProjectId projectId = entries.getKey();
RoutingTable projectRoutingTable = entries.getValue();
for (IndexRoutingTable indexShardRouting : projectRoutingTable.indicesRouting().values()) {
for (int i = 0; i < indexShardRouting.size(); i++) {
IndexShardRoutingTable shardRouting = indexShardRouting.shard(i);
status.addPrimary(projectId, shardRouting.primaryShard(), state, shutdown, verbose);
for (ShardRouting replicaShard : shardRouting.replicaShards()) {
status.addReplica(projectId, replicaShard, state, shutdown, verbose, replicaUnassignedBufferTime);
}
}
}
}
status.updateSearchableSnapshotsOfAvailableIndices();
}
// Impact IDs
public static final String PRIMARY_UNASSIGNED_IMPACT_ID = "primary_unassigned";
public static final String READ_ONLY_PRIMARY_UNASSIGNED_IMPACT_ID = "read_only_primary_unassigned";
public static final String REPLICA_UNASSIGNED_IMPACT_ID = "replica_unassigned";
public static final String RESTORE_FROM_SNAPSHOT_ACTION_GUIDE = "https://ela.st/restore-snapshot";
public static final Diagnosis.Definition ACTION_RESTORE_FROM_SNAPSHOT = new Diagnosis.Definition(
NAME,
"restore_from_snapshot",
"Elasticsearch isn't allowed to allocate some shards because there are no copies of the shards in the cluster. Elasticsearch will "
+ "allocate these shards when nodes holding good copies of the data join the cluster.",
"If no such node is available, restore these indices from a recent snapshot.",
RESTORE_FROM_SNAPSHOT_ACTION_GUIDE
);
public static final String DIAGNOSE_SHARDS_ACTION_GUIDE = "https://ela.st/diagnose-shards";
public static final Diagnosis.Definition ACTION_CHECK_ALLOCATION_EXPLAIN_API = new Diagnosis.Definition(
NAME,
"explain_allocations",
"Elasticsearch isn't allowed to allocate some shards from these indices to any of the nodes in the cluster.",
"Diagnose the issue by calling the allocation explain API for an index [GET _cluster/allocation/explain]. Choose a node to which "
+ "you expect a shard to be allocated, find this node in the node-by-node explanation, and address the reasons which prevent "
+ "Elasticsearch from allocating the shard.",
DIAGNOSE_SHARDS_ACTION_GUIDE
);
public static final String FIX_DELAYED_SHARDS_GUIDE = "https://ela.st/fix-delayed-shard-allocation";
public static final Diagnosis.Definition DIAGNOSIS_WAIT_FOR_OR_FIX_DELAYED_SHARDS = new Diagnosis.Definition(
NAME,
"delayed_shard_allocations",
"Elasticsearch is not allocating some shards because they are marked for delayed allocation. Shards that have become "
+ "unavailable are usually marked for delayed allocation because it is more efficient to wait and see if the shards return "
+ "on their own than to recover the shard immediately.",
"Elasticsearch will reallocate the shards when the delay has elapsed. No action is required by the user.",
FIX_DELAYED_SHARDS_GUIDE
);
public static final String WAIT_FOR_INITIALIZATION_GUIDE = "https://ela.st/wait-for-shard-initialization";
public static final Diagnosis.Definition DIAGNOSIS_WAIT_FOR_INITIALIZATION = new Diagnosis.Definition(
NAME,
"initializing_shards",
"Elasticsearch is currently initializing the unavailable shards. Please wait for the initialization to finish.",
"The shards will become available when the initialization completes. No action is required by the user, you can"
+ " monitor the progress of the initializing shards at "
+ WAIT_FOR_INITIALIZATION_GUIDE
+ ".",
WAIT_FOR_INITIALIZATION_GUIDE
);
public static final String ENABLE_INDEX_ALLOCATION_GUIDE = "https://ela.st/fix-index-allocation";
public static final Diagnosis.Definition ACTION_ENABLE_INDEX_ROUTING_ALLOCATION = new Diagnosis.Definition(
NAME,
"enable_index_allocations",
"Elasticsearch isn't allowed to allocate some shards from these indices because allocation for those shards has been disabled at "
+ "the index level.",
"Check that the ["
+ INDEX_ROUTING_ALLOCATION_ENABLE_SETTING.getKey()
+ "] index settings are set to ["
+ EnableAllocationDecider.Allocation.ALL.toString().toLowerCase(Locale.getDefault())
+ "].",
ENABLE_INDEX_ALLOCATION_GUIDE
);
public static final String ENABLE_CLUSTER_ALLOCATION_ACTION_GUIDE = "https://ela.st/fix-cluster-allocation";
public static final Diagnosis.Definition ACTION_ENABLE_CLUSTER_ROUTING_ALLOCATION = new Diagnosis.Definition(
NAME,
"enable_cluster_allocations",
"Elasticsearch isn't allowed to allocate some shards from these indices because allocation for those shards has been disabled at "
+ "the cluster level.",
"Check that the ["
+ EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE_SETTING.getKey()
+ "] cluster setting is set to ["
+ EnableAllocationDecider.Allocation.ALL.toString().toLowerCase(Locale.getDefault())
+ "].",
ENABLE_CLUSTER_ALLOCATION_ACTION_GUIDE
);
public static final String ENABLE_TIER_ACTION_GUIDE = "https://ela.st/enable-tier";
private static final Map<String, Diagnosis.Definition> ACTION_ENABLE_TIERS_LOOKUP = DataTier.ALL_DATA_TIERS.stream()
.collect(
Collectors.toUnmodifiableMap(
tier -> tier,
tier -> new Diagnosis.Definition(
NAME,
"enable_data_tiers:tier:" + tier,
"Elasticsearch isn't allowed to allocate some shards from these indices because the indices expect to be allocated to "
+ "data tier nodes, but there were not any nodes with the expected tiers found in the cluster.",
"Add nodes with the [" + tier + "] role to the cluster.",
ENABLE_TIER_ACTION_GUIDE
)
)
);
public static final String INCREASE_SHARD_LIMIT_ACTION_GUIDE = "https://ela.st/index-total-shards";
public static final Diagnosis.Definition ACTION_INCREASE_SHARD_LIMIT_INDEX_SETTING = new Diagnosis.Definition(
NAME,
"increase_shard_limit_index_setting",
"Elasticsearch isn't allowed to allocate some shards from these indices to any data nodes because each node has reached the index "
+ "shard limit.",
"Increase the values for the ["
+ INDEX_TOTAL_SHARDS_PER_NODE_SETTING.getKey()
+ "] index setting on each index or add more nodes to the target tiers.",
INCREASE_SHARD_LIMIT_ACTION_GUIDE
);
private static final Map<String, Diagnosis.Definition> ACTION_INCREASE_SHARD_LIMIT_INDEX_SETTING_LOOKUP = DataTier.ALL_DATA_TIERS
.stream()
.collect(
Collectors.toUnmodifiableMap(
tier -> tier,
tier -> new Diagnosis.Definition(
NAME,
"increase_shard_limit_index_setting:tier:" + tier,
"Elasticsearch isn't allowed to allocate some shards from these indices because each node in the ["
+ tier
+ "] tier has reached the index shard limit.",
"Increase the values for the ["
+ INDEX_TOTAL_SHARDS_PER_NODE_SETTING.getKey()
+ "] index setting on each index or add more nodes to the target tiers.",
INCREASE_SHARD_LIMIT_ACTION_GUIDE
)
)
);
public static final String INCREASE_CLUSTER_SHARD_LIMIT_ACTION_GUIDE = "https://ela.st/cluster-total-shards";
public static final Diagnosis.Definition ACTION_INCREASE_SHARD_LIMIT_CLUSTER_SETTING = new Diagnosis.Definition(
NAME,
"increase_shard_limit_cluster_setting",
"Elasticsearch isn't allowed to allocate some shards from these indices to any data nodes because each node has reached the "
+ "cluster shard limit.",
"Increase the values for the ["
+ CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING.getKey()
+ "] cluster setting or add more nodes to the target tiers.",
INCREASE_CLUSTER_SHARD_LIMIT_ACTION_GUIDE
);
private static final Map<String, Diagnosis.Definition> ACTION_INCREASE_SHARD_LIMIT_CLUSTER_SETTING_LOOKUP = DataTier.ALL_DATA_TIERS
.stream()
.collect(
Collectors.toUnmodifiableMap(
tier -> tier,
tier -> new Diagnosis.Definition(
NAME,
"increase_shard_limit_cluster_setting:tier:" + tier,
"Elasticsearch isn't allowed to allocate some shards from these indices because each node in the ["
+ tier
+ "] tier has reached the cluster shard limit.",
"Increase the values for the ["
+ CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING.getKey()
+ "] cluster setting or add more nodes to the target tiers.",
INCREASE_CLUSTER_SHARD_LIMIT_ACTION_GUIDE
)
)
);
public static final String MIGRATE_TO_TIERS_ACTION_GUIDE = "https://ela.st/migrate-to-tiers";
public static final Diagnosis.Definition ACTION_MIGRATE_TIERS_AWAY_FROM_REQUIRE_DATA = new Diagnosis.Definition(
NAME,
"migrate_data_tiers_require_data",
"Elasticsearch isn't allowed to allocate some shards from these indices to any nodes in the desired data tiers because the "
+ "indices are configured with allocation filter rules that are incompatible with the nodes in this tier.",
"Remove ["
+ INDEX_ROUTING_REQUIRE_GROUP_PREFIX
+ ".data] from the index settings or try migrating to data tiers by first stopping ILM [POST /_ilm/stop] and then using "
+ "the data tier migration action [POST /_ilm/migrate_to_data_tiers]. Finally, restart ILM [POST /_ilm/start].",
MIGRATE_TO_TIERS_ACTION_GUIDE
);
public static final Map<String, Diagnosis.Definition> ACTION_MIGRATE_TIERS_AWAY_FROM_REQUIRE_DATA_LOOKUP = DataTier.ALL_DATA_TIERS
.stream()
.collect(
Collectors.toUnmodifiableMap(
tier -> tier,
tier -> new Diagnosis.Definition(
NAME,
"migrate_data_tiers_require_data:tier:" + tier,
"Elasticsearch isn't allowed to allocate some shards from these indices to any nodes in the ["
+ tier
+ "] data tier because the indices are configured with allocation filter rules that are incompatible with the "
+ "nodes in this tier.",
"Remove ["
+ INDEX_ROUTING_REQUIRE_GROUP_PREFIX
+ ".data] from the index settings or try migrating to data tiers by first stopping ILM [POST /_ilm/stop] and then "
+ "using the data tier migration action [POST /_ilm/migrate_to_data_tiers]. "
+ "Finally, restart ILM [POST /_ilm/start].",
MIGRATE_TO_TIERS_ACTION_GUIDE
)
)
);
public static final Diagnosis.Definition ACTION_MIGRATE_TIERS_AWAY_FROM_INCLUDE_DATA = new Diagnosis.Definition(
NAME,
"migrate_data_tiers_include_data",
"Elasticsearch isn't allowed to allocate some shards from these indices to any nodes in the desired data tiers because the "
+ "indices are configured with allocation filter rules that are incompatible with the nodes in this tier.",
"Remove ["
+ INDEX_ROUTING_INCLUDE_GROUP_PREFIX
+ ".data] from the index settings or try migrating to data tiers by first stopping ILM [POST /_ilm/stop] and then using "
+ "the data tier migration action [POST /_ilm/migrate_to_data_tiers]. Finally, restart ILM [POST /_ilm/start].",
MIGRATE_TO_TIERS_ACTION_GUIDE
);
public static final Map<String, Diagnosis.Definition> ACTION_MIGRATE_TIERS_AWAY_FROM_INCLUDE_DATA_LOOKUP = DataTier.ALL_DATA_TIERS
.stream()
.collect(
Collectors.toUnmodifiableMap(
tier -> tier,
tier -> new Diagnosis.Definition(
NAME,
"migrate_data_tiers_include_data:tier:" + tier,
"Elasticsearch isn't allowed to allocate some shards from these indices to any nodes in the ["
+ tier
+ "] data tier because the indices are configured with allocation filter rules that are incompatible with the "
+ "nodes in this tier.",
"Remove ["
+ INDEX_ROUTING_INCLUDE_GROUP_PREFIX
+ ".data] from the index settings or try migrating to data tiers by first stopping ILM [POST /_ilm/stop] and then "
+ "using the data tier migration action [POST /_ilm/migrate_to_data_tiers]. Finally, restart ILM "
+ "[POST /_ilm/start].",
MIGRATE_TO_TIERS_ACTION_GUIDE
)
)
);
public static final String TIER_CAPACITY_ACTION_GUIDE = "https://ela.st/tier-capacity";
public static final Diagnosis.Definition ACTION_INCREASE_NODE_CAPACITY = new Diagnosis.Definition(
NAME,
"increase_node_capacity_for_allocations",
"Elasticsearch isn't allowed to allocate some shards from these indices because there are not enough nodes in the cluster to "
+ "allocate each shard copy on a different node.",
"Increase the number of nodes in the cluster or decrease the number of replica shards in the affected indices.",
TIER_CAPACITY_ACTION_GUIDE
);
// Visible for testing
public static final Map<String, Diagnosis.Definition> ACTION_INCREASE_TIER_CAPACITY_LOOKUP = DataTier.ALL_DATA_TIERS.stream()
.collect(
Collectors.toUnmodifiableMap(
tier -> tier,
tier -> new Diagnosis.Definition(
NAME,
"increase_tier_capacity_for_allocations:tier:" + tier,
"Elasticsearch isn't allowed to allocate some shards from these indices to any of the nodes in the desired data tier "
+ "because there are not enough nodes in the ["
+ tier
+ "] tier to allocate each shard copy on a different node.",
"Increase the number of nodes in this tier or decrease the number of replica shards in the affected indices.",
TIER_CAPACITY_ACTION_GUIDE
)
)
);
public | ShardsAvailabilityHealthIndicatorService |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/request/VariantQuality.java | {
"start": 310,
"end": 3378
} | class ____ {
private QualityValue mediaTypeQualityValue = QualityValue.DEFAULT;
private QualityValue characterSetQualityValue = QualityValue.DEFAULT;
private QualityValue encodingQualityValue = QualityValue.DEFAULT;
private QualityValue languageQualityValue = QualityValue.DEFAULT;
private MediaType requestMediaType;
public VariantQuality() {
}
public VariantQuality setMediaTypeQualityValue(QualityValue value) {
if (value == null) {
mediaTypeQualityValue = QualityValue.DEFAULT;
} else {
mediaTypeQualityValue = value;
}
return this;
}
public VariantQuality setCharacterSetQualityValue(QualityValue value) {
if (value == null) {
characterSetQualityValue = QualityValue.DEFAULT;
} else {
characterSetQualityValue = value;
}
return this;
}
public VariantQuality setEncodingQualityValue(QualityValue value) {
if (value == null) {
encodingQualityValue = QualityValue.DEFAULT;
} else {
encodingQualityValue = value;
}
return this;
}
public VariantQuality setLanguageQualityValue(QualityValue value) {
if (value == null) {
languageQualityValue = QualityValue.DEFAULT;
} else {
languageQualityValue = value;
}
return this;
}
public MediaType getRequestMediaType() {
return requestMediaType;
}
public void setRequestMediaType(MediaType requestMediaType) {
this.requestMediaType = requestMediaType;
}
/**
* @return the quality value between zero and one with five decimal places after the point.
* @see "3.3 Computing overall quality values"
*/
public BigDecimal getOverallQuality() {
BigDecimal qt = BigDecimal.valueOf(mediaTypeQualityValue.intValue(), 3);
BigDecimal qc = BigDecimal.valueOf(characterSetQualityValue.intValue(), 3);
BigDecimal qe = BigDecimal.valueOf(encodingQualityValue.intValue(), 3);
BigDecimal ql = BigDecimal.valueOf(languageQualityValue.intValue(), 3);
assert qt.compareTo(BigDecimal.ZERO) >= 0 && qt.compareTo(BigDecimal.ONE) <= 0;
assert qc.compareTo(BigDecimal.ZERO) >= 0 && qc.compareTo(BigDecimal.ONE) <= 0;
assert qe.compareTo(BigDecimal.ZERO) >= 0 && qe.compareTo(BigDecimal.ONE) <= 0;
assert ql.compareTo(BigDecimal.ZERO) >= 0 && ql.compareTo(BigDecimal.ONE) <= 0;
BigDecimal result = qt;
result = result.multiply(qc, MathContext.DECIMAL32);
result = result.multiply(qe, MathContext.DECIMAL32);
result = result.multiply(ql, MathContext.DECIMAL32);
assert result.compareTo(BigDecimal.ZERO) >= 0 && result.compareTo(BigDecimal.ONE) <= 0;
long round5 = result.scaleByPowerOfTen(5).longValue();
result = BigDecimal.valueOf(round5, 5);
assert result.compareTo(BigDecimal.ZERO) >= 0 && result.compareTo(BigDecimal.ONE) <= 0;
return result;
}
}
| VariantQuality |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/external/response/BaseResponseEntity.java | {
"start": 631,
"end": 842
} | class ____ providing InferenceServiceResults from a response. This is a lightweight wrapper
* to be able to override the `fromReponse` method to avoid using a static reference to the method.
*/
public abstract | for |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/annotation/IfProfileValue.java | {
"start": 4747,
"end": 5402
} | interface ____ {
/**
* The {@code name} of the <em>profile value</em> against which to test.
*/
String name();
/**
* A single, permissible {@code value} of the <em>profile value</em>
* for the given {@link #name}.
* <p>Note: Assigning values to both {@code #value} and {@link #values}
* will lead to a configuration conflict.
*/
String value() default "";
/**
* A list of all permissible {@code values} of the <em>profile value</em>
* for the given {@link #name}.
* <p>Note: Assigning values to both {@link #value} and {@code #values}
* will lead to a configuration conflict.
*/
String[] values() default {};
}
| IfProfileValue |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java | {
"start": 2121,
"end": 12001
} | class ____ extends RMStateStore {
RMState state = new RMState();
private long epoch = 0L;
@VisibleForTesting
public RMState getState() {
return state;
}
@Override
public void checkVersion() throws Exception {
}
@Override
public synchronized long getAndIncrementEpoch() throws Exception {
long currentEpoch = epoch;
epoch = nextEpoch(epoch);
return currentEpoch;
}
@Override
public synchronized RMState loadState() throws Exception {
// return a copy of the state to allow for modification of the real state
RMState returnState = new RMState();
returnState.appState.putAll(state.appState);
returnState.rmSecretManagerState.getMasterKeyState()
.addAll(state.rmSecretManagerState.getMasterKeyState());
returnState.rmSecretManagerState.getTokenState().putAll(
state.rmSecretManagerState.getTokenState());
returnState.rmSecretManagerState.dtSequenceNumber =
state.rmSecretManagerState.dtSequenceNumber;
returnState.amrmTokenSecretManagerState =
state.amrmTokenSecretManagerState == null ? null
: AMRMTokenSecretManagerState
.newInstance(state.amrmTokenSecretManagerState);
if (state.proxyCAState.getCaCert() != null) {
byte[] caCertData = state.proxyCAState.getCaCert().getEncoded();
returnState.proxyCAState.setCaCert(caCertData);
}
if (state.proxyCAState.getCaPrivateKey() != null) {
byte[] caPrivateKeyData
= state.proxyCAState.getCaPrivateKey().getEncoded();
returnState.proxyCAState.setCaPrivateKey(caPrivateKeyData);
}
return returnState;
}
@Override
public synchronized void initInternal(Configuration conf) {
epoch = baseEpoch;
}
@Override
protected synchronized void startInternal() throws Exception {
}
@Override
protected synchronized void closeInternal() throws Exception {
}
@Override
public synchronized void storeApplicationStateInternal(
ApplicationId appId, ApplicationStateData appState)
throws Exception {
state.appState.put(appId, appState);
}
@Override
public synchronized void updateApplicationStateInternal(
ApplicationId appId, ApplicationStateData appState)
throws Exception {
LOG.info("Updating final state " + appState.getState() + " for app: "
+ appId);
if (state.appState.get(appId) != null) {
// add the earlier attempts back
appState.attempts.putAll(state.appState.get(appId).attempts);
}
state.appState.put(appId, appState);
}
@Override
public synchronized void storeApplicationAttemptStateInternal(
ApplicationAttemptId appAttemptId,
ApplicationAttemptStateData attemptState)
throws Exception {
ApplicationStateData appState = state.getApplicationState().get(
attemptState.getAttemptId().getApplicationId());
if (appState == null) {
throw new YarnRuntimeException("Application doesn't exist");
}
appState.attempts.put(attemptState.getAttemptId(), attemptState);
}
@Override
public synchronized void updateApplicationAttemptStateInternal(
ApplicationAttemptId appAttemptId,
ApplicationAttemptStateData attemptState)
throws Exception {
ApplicationStateData appState =
state.getApplicationState().get(appAttemptId.getApplicationId());
if (appState == null) {
throw new YarnRuntimeException("Application doesn't exist");
}
LOG.info("Updating final state " + attemptState.getState()
+ " for attempt: " + attemptState.getAttemptId());
appState.attempts.put(attemptState.getAttemptId(), attemptState);
}
@Override
public synchronized void removeApplicationAttemptInternal(
ApplicationAttemptId appAttemptId) throws Exception {
ApplicationStateData appState =
state.getApplicationState().get(appAttemptId.getApplicationId());
ApplicationAttemptStateData attemptState =
appState.attempts.remove(appAttemptId);
LOG.info("Removing state for attempt: " + appAttemptId);
if (attemptState == null) {
throw new YarnRuntimeException("Application doesn't exist");
}
}
@Override
public synchronized void removeApplicationStateInternal(
ApplicationStateData appState) throws Exception {
ApplicationId appId =
appState.getApplicationSubmissionContext().getApplicationId();
ApplicationStateData removed = state.appState.remove(appId);
if (removed == null) {
throw new YarnRuntimeException("Removing non-existing application state");
}
}
private void storeOrUpdateRMDT(RMDelegationTokenIdentifier rmDTIdentifier,
Long renewDate, boolean isUpdate) throws Exception {
Map<RMDelegationTokenIdentifier, Long> rmDTState =
state.rmSecretManagerState.getTokenState();
if (rmDTState.containsKey(rmDTIdentifier)) {
IOException e = new IOException("RMDelegationToken: " + rmDTIdentifier
+ "is already stored.");
LOG.info("Error storing info for RMDelegationToken: " + rmDTIdentifier, e);
throw e;
}
rmDTState.put(rmDTIdentifier, renewDate);
if(!isUpdate) {
state.rmSecretManagerState.dtSequenceNumber =
rmDTIdentifier.getSequenceNumber();
}
LOG.info("Store RMDT with sequence number "
+ rmDTIdentifier.getSequenceNumber());
}
@Override
public synchronized void storeRMDelegationTokenState(
RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate)
throws Exception {
storeOrUpdateRMDT(rmDTIdentifier, renewDate, false);
}
@Override
public synchronized void removeRMDelegationTokenState(
RMDelegationTokenIdentifier rmDTIdentifier) throws Exception{
Map<RMDelegationTokenIdentifier, Long> rmDTState =
state.rmSecretManagerState.getTokenState();
rmDTState.remove(rmDTIdentifier);
LOG.info("Remove RMDT with sequence number "
+ rmDTIdentifier.getSequenceNumber());
}
@Override
protected synchronized void updateRMDelegationTokenState(
RMDelegationTokenIdentifier rmDTIdentifier, Long renewDate)
throws Exception {
removeRMDelegationTokenState(rmDTIdentifier);
storeOrUpdateRMDT(rmDTIdentifier, renewDate, true);
LOG.info("Update RMDT with sequence number "
+ rmDTIdentifier.getSequenceNumber());
}
@Override
public synchronized void storeRMDTMasterKeyState(DelegationKey delegationKey)
throws Exception {
Set<DelegationKey> rmDTMasterKeyState =
state.rmSecretManagerState.getMasterKeyState();
if (rmDTMasterKeyState.contains(delegationKey)) {
IOException e = new IOException("RMDTMasterKey with keyID: "
+ delegationKey.getKeyId() + " is already stored");
LOG.info("Error storing info for RMDTMasterKey with keyID: "
+ delegationKey.getKeyId(), e);
throw e;
}
state.getRMDTSecretManagerState().getMasterKeyState().add(delegationKey);
LOG.info("Store RMDT master key with key id: " + delegationKey.getKeyId()
+ ". Currently rmDTMasterKeyState size: " + rmDTMasterKeyState.size());
}
@Override
public synchronized void removeRMDTMasterKeyState(DelegationKey delegationKey)
throws Exception {
LOG.info("Remove RMDT master key with key id: " + delegationKey.getKeyId());
Set<DelegationKey> rmDTMasterKeyState =
state.rmSecretManagerState.getMasterKeyState();
rmDTMasterKeyState.remove(delegationKey);
}
@Override
protected synchronized void storeReservationState(
ReservationAllocationStateProto reservationAllocation, String planName,
String reservationIdName) throws Exception {
LOG.info("Storing reservationallocation for " + reservationIdName + " " +
"for plan " + planName);
Map<ReservationId, ReservationAllocationStateProto> planState =
state.getReservationState().get(planName);
if (planState == null) {
planState = new HashMap<>();
state.getReservationState().put(planName, planState);
}
ReservationId reservationId =
ReservationId.parseReservationId(reservationIdName);
planState.put(reservationId, reservationAllocation);
}
@Override
protected synchronized void removeReservationState(
String planName, String reservationIdName) throws Exception {
LOG.info("Removing reservationallocation " + reservationIdName
+ " for plan " + planName);
Map<ReservationId, ReservationAllocationStateProto> planState =
state.getReservationState().get(planName);
if (planState == null) {
throw new YarnRuntimeException("State for plan " + planName + " does " +
"not exist");
}
ReservationId reservationId =
ReservationId.parseReservationId(reservationIdName);
planState.remove(reservationId);
if (planState.isEmpty()) {
state.getReservationState().remove(planName);
}
}
@Override
protected void storeProxyCACertState(
X509Certificate caCert, PrivateKey caPrivateKey) throws Exception {
state.getProxyCAState().setCaCert(caCert);
state.getProxyCAState().setCaPrivateKey(caPrivateKey);
}
@Override
protected Version loadVersion() throws Exception {
return null;
}
@Override
protected void storeVersion() throws Exception {
}
@Override
protected Version getCurrentVersion() {
return null;
}
@Override
public synchronized void storeOrUpdateAMRMTokenSecretManagerState(
AMRMTokenSecretManagerState amrmTokenSecretManagerState,
boolean isUpdate) {
if (amrmTokenSecretManagerState != null) {
state.amrmTokenSecretManagerState = AMRMTokenSecretManagerState
.newInstance(amrmTokenSecretManagerState);
}
}
@Override
public void deleteStore() throws Exception {
}
@Override
public void removeApplication(ApplicationId removeAppId) throws Exception {
}
}
| MemoryRMStateStore |
java | spring-projects__spring-security | buildSrc/src/test/resources/samples/showcase/sgbcs-docs/src/main/java/example/StringUtils.java | {
"start": 25,
"end": 203
} | class ____ {
// tag::contains[]
public boolean contains(String haystack, String needle) {
return haystack.contains(needle);
}
// end::contains[]
}
| StringUtils |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/deser/EnumTest.java | {
"start": 1190,
"end": 1240
} | enum ____ {
A, B, C
}
public static | E |
java | quarkusio__quarkus | integration-tests/main/src/test/java/io/quarkus/it/main/QuarkusTestCallbacksITCase.java | {
"start": 879,
"end": 2596
} | class ____ {
private static boolean throwsCustomException = false;
@AfterEach
void afterEachWithTestInfo() {
if (throwsCustomException) {
throw new QuarkusTestCallbacksTestCase.CustomException();
}
}
@Test
@QuarkusTestCallbacksTestCase.TestAnnotation
@Order(1)
public void testTestMethodHasAnnotation() {
assertTrue(TestContextCheckerBeforeEachCallback.testAnnotationChecked);
}
@Test
@Order(2)
public void testBeforeClass() {
assertEquals(1, SimpleAnnotationCheckerBeforeClassCallback.count.get());
}
@Test
@QuarkusTestCallbacksTestCase.TestAnnotation
@Order(3)
public void testInfoTestCase(TestInfo testInfo) throws NoSuchMethodException {
assertEquals(testInfo.getTestClass().get(), QuarkusTestCallbacksITCase.class);
Method testMethod = testInfo.getTestMethod().get();
assertEquals(testMethod, QuarkusTestCallbacksITCase.class.getDeclaredMethod("testInfoTestCase", TestInfo.class));
assertEquals(1, testMethod.getAnnotationsByType(QuarkusTestCallbacksTestCase.TestAnnotation.class).length);
assertEquals(QuarkusTestCallbacksITCase.class, testInfo.getTestClass().get());
}
@Test
@Order(4)
public void testCallbackContextIsNotFailed() {
assertFalse(TestContextCheckerBeforeEachCallback.CONTEXT.getTestStatus().isTestFailed());
// To force the exception in the before each handler.
throwsCustomException = true;
}
@Test
@Order(5)
public void testCallbackContextIsFailed() {
assertTrue(TestContextCheckerBeforeEachCallback.CONTEXT.getTestStatus().isTestFailed());
}
}
| QuarkusTestCallbacksITCase |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/stream/keyselector/AttributeBasedJoinKeyExtractor.java | {
"start": 35664,
"end": 39097
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
private final int inputIdToAccess;
private final int fieldIndexInSourceRow;
private final int absoluteFieldIndex;
private final LogicalType fieldType;
private transient RowData.FieldGetter leftFieldGetter;
private transient RowData.FieldGetter rightFieldGetter;
public KeyExtractor(
final int inputIdToAccess,
final int fieldIndexInSourceRow,
final int absoluteFieldIndex,
final LogicalType fieldType) {
this.inputIdToAccess = inputIdToAccess;
this.fieldIndexInSourceRow = fieldIndexInSourceRow;
this.absoluteFieldIndex = absoluteFieldIndex;
this.fieldType = fieldType;
this.rightFieldGetter =
RowData.createFieldGetter(this.fieldType, this.fieldIndexInSourceRow);
this.leftFieldGetter =
RowData.createFieldGetter(this.fieldType, this.absoluteFieldIndex);
}
/**
* Returns the key value from a single input row (right/current side of the current join
* step).
*
* <p>Example: for a step joining t1 (input 0) and t2 (input 1) t1.id1 = t2.user_id2, the
* extractor configured for t2 (input 1) returns t2.user_id2 value from the provided t2 row.
*/
public Object getRightSideKey(final RowData row) {
if (row == null) {
return null;
}
if (this.rightFieldGetter == null) {
this.rightFieldGetter =
RowData.createFieldGetter(this.fieldType, this.fieldIndexInSourceRow);
}
return this.rightFieldGetter.getFieldOrNull(row);
}
/**
* Returns the key value from the already-joined row (left side of the current join step).
*
* <p>Example: for a step joining t1 (input 0) and t2 (input 1) t1.id1 = t2.user_id2, the
* extractor configured for t2 (input 1) returns t1.id1 value from the provided t1 row.
*/
public Object getLeftSideKey(final RowData joinedRowData) {
if (joinedRowData == null) {
return null;
}
if (this.leftFieldGetter == null) {
this.leftFieldGetter =
RowData.createFieldGetter(this.fieldType, this.absoluteFieldIndex);
}
return this.leftFieldGetter.getFieldOrNull(joinedRowData);
}
public int getInputIdToAccess() {
return inputIdToAccess;
}
public int getFieldIndexInSourceRow() {
return fieldIndexInSourceRow;
}
private void readObject(final java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
in.defaultReadObject();
if (this.fieldType != null) {
this.rightFieldGetter =
RowData.createFieldGetter(this.fieldType, this.fieldIndexInSourceRow);
this.leftFieldGetter =
RowData.createFieldGetter(this.fieldType, this.absoluteFieldIndex);
}
}
}
/** Reference to a specific field (fieldIndex) within a specific input stream (inputId). */
public static final | KeyExtractor |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherFactoryTests.java | {
"start": 18617,
"end": 18845
} | class ____ implements AutoCloseable {
private static boolean closed = false;
@Override
public void close() {
closed = true;
}
public boolean isClosed() {
return closed;
}
}
private static | CloseTrackingResource |
java | quarkusio__quarkus | extensions/devui/runtime/src/main/java/io/quarkus/devui/runtime/jsonrpc/JsonRpcRequestCreator.java | {
"start": 435,
"end": 3212
} | class ____ {
private final JsonMapper jsonMapper;
JsonRpcRequestCreator(JsonMapper jsonMapper) {
this.jsonMapper = jsonMapper;
}
/**
* This creates a Request as is from Dev UI
*
* @param jsonObject the JsonObject from the JS
* @return JsonRpcRequest
*/
public JsonRpcRequest create(JsonObject jsonObject) {
return createWithFilter(jsonObject, null);
}
/**
* This creates a Request from an MCP Client.
* It might contain meta data in the parameters that is not applicable for the Java method
*
* @param jsonObject the JsonObject from the MCP
* @return JsonRpcRequest
*/
public JsonRpcRequest mcpCreate(JsonObject jsonObject) {
return remap(createWithFilter(jsonObject, "_meta", "cursor"));
}
/**
* This remaps a MCP Tool Call to a normal json-rpc method
*
* @param jsonRpcRequest the tools call request
* @return JsonRpcRequest the remapped request
*/
private JsonRpcRequest remap(JsonRpcRequest jsonRpcRequest) {
if (jsonRpcRequest.getMethod().equalsIgnoreCase(TOOLS_SLASH_CALL)) {
Map params = jsonRpcRequest.getParams();
String mappedName = (String) params.remove("name");
Map mappedParams = (Map) params.remove("arguments");
JsonRpcRequest mapped = new JsonRpcRequest(this.jsonMapper);
mapped.setId(jsonRpcRequest.getId());
mapped.setJsonrpc(jsonRpcRequest.getJsonrpc());
mapped.setMethod(mappedName);
if (mappedParams != null && !mappedParams.isEmpty())
mapped.setParams(mappedParams);
return mapped;
}
return jsonRpcRequest;
}
public String toJson(JsonRpcRequest jsonRpcRequest) {
return jsonMapper.toString(jsonRpcRequest, true);
}
private JsonRpcRequest createWithFilter(JsonObject jsonObject, String... filter) {
JsonRpcRequest jsonRpcRequest = new JsonRpcRequest(this.jsonMapper);
if (jsonObject.containsKey(ID)) {
jsonRpcRequest.setId(jsonObject.getInteger(ID));
}
if (jsonObject.containsKey(JSONRPC)) {
jsonRpcRequest.setJsonrpc(jsonObject.getString(JSONRPC));
}
jsonRpcRequest.setMethod(jsonObject.getString(METHOD));
if (jsonObject.containsKey(PARAMS)) {
Map<String, Object> map = jsonObject.getJsonObject(PARAMS).getMap();
if (filter != null) {
for (String p : filter) {
map.remove(p);
}
}
jsonRpcRequest.setParams(map);
}
return jsonRpcRequest;
}
private static final String TOOLS_SLASH_CALL = "tools/call";
}
| JsonRpcRequestCreator |
java | micronaut-projects__micronaut-core | http-server-netty/src/test/groovy/io/micronaut/http/server/netty/websocket/QueryParamServerWebSocket.java | {
"start": 563,
"end": 1292
} | class ____ {
private WebSocketBroadcaster broadcaster;
private String dinner;
private WebSocketSession session;
public QueryParamServerWebSocket(WebSocketBroadcaster broadcaster) {
this.broadcaster = broadcaster;
}
@OnOpen
public void onOpen(@QueryValue String dinner, WebSocketSession session) {
this.dinner = dinner;
this.session = session;
}
@OnMessage
public void onMessage(
String dinner,
WebSocketSession session) {
}
@OnClose
public void onClose() {
}
public String getDinner() {
return dinner;
}
public WebSocketSession getSession() {
return session;
}
}
| QueryParamServerWebSocket |
java | spring-projects__spring-security | rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/PayloadExchangeMatcherEntry.java | {
"start": 722,
"end": 1089
} | class ____<T> {
private final PayloadExchangeMatcher matcher;
private final T entry;
public PayloadExchangeMatcherEntry(PayloadExchangeMatcher matcher, T entry) {
this.matcher = matcher;
this.entry = entry;
}
public PayloadExchangeMatcher getMatcher() {
return this.matcher;
}
public T getEntry() {
return this.entry;
}
}
| PayloadExchangeMatcherEntry |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/query/FieldMaskingSpanQueryBuilder.java | {
"start": 1267,
"end": 7414
} | class ____ extends AbstractQueryBuilder<FieldMaskingSpanQueryBuilder> implements SpanQueryBuilder {
public static final ParseField NAME = new ParseField("span_field_masking", "field_masking_span");
private static final ParseField FIELD_FIELD = new ParseField("field");
private static final ParseField QUERY_FIELD = new ParseField("query");
private final SpanQueryBuilder queryBuilder;
private final String fieldName;
/**
* Constructs a new {@link FieldMaskingSpanQueryBuilder} given an inner {@link SpanQueryBuilder} for
* a given field
* @param queryBuilder inner {@link SpanQueryBuilder}
* @param fieldName the field name
*/
public FieldMaskingSpanQueryBuilder(SpanQueryBuilder queryBuilder, String fieldName) {
if (Strings.isEmpty(fieldName)) {
throw new IllegalArgumentException("field name is null or empty");
}
if (queryBuilder == null) {
throw new IllegalArgumentException("inner clause [query] cannot be null.");
}
this.queryBuilder = queryBuilder;
this.fieldName = fieldName;
}
/**
* Read from a stream.
*/
public FieldMaskingSpanQueryBuilder(StreamInput in) throws IOException {
super(in);
queryBuilder = (SpanQueryBuilder) in.readNamedWriteable(QueryBuilder.class);
fieldName = in.readString();
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeNamedWriteable(queryBuilder);
out.writeString(fieldName);
}
/**
* @return the field name for this query
*/
public String fieldName() {
return this.fieldName;
}
/**
* @return the inner {@link QueryBuilder}
*/
public SpanQueryBuilder innerQuery() {
return this.queryBuilder;
}
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME.getPreferredName());
builder.field(QUERY_FIELD.getPreferredName());
queryBuilder.toXContent(builder, params);
builder.field(FIELD_FIELD.getPreferredName(), fieldName);
boostAndQueryNameToXContent(builder);
builder.endObject();
}
public static FieldMaskingSpanQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
SpanQueryBuilder inner = null;
String field = null;
String queryName = null;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (QUERY_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(
parser.getTokenLocation(),
"[" + NAME.getPreferredName() + "] query must be of type span query"
);
}
inner = (SpanQueryBuilder) query;
checkNoBoost(NAME.getPreferredName(), currentFieldName, parser, inner);
} else {
throw new ParsingException(
parser.getTokenLocation(),
"[" + NAME.getPreferredName() + "] query does not support [" + currentFieldName + "]"
);
}
} else {
if (AbstractQueryBuilder.BOOST_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
boost = parser.floatValue();
} else if (FIELD_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
field = parser.text();
} else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
queryName = parser.text();
} else {
throw new ParsingException(
parser.getTokenLocation(),
"[" + NAME.getPreferredName() + "] query does not support [" + currentFieldName + "]"
);
}
}
}
if (inner == null) {
throw new ParsingException(parser.getTokenLocation(), NAME.getPreferredName() + " must have [query] span query clause");
}
if (field == null) {
throw new ParsingException(parser.getTokenLocation(), NAME.getPreferredName() + " must have [field] set for it");
}
FieldMaskingSpanQueryBuilder queryBuilder = new FieldMaskingSpanQueryBuilder(inner, field);
queryBuilder.boost(boost);
queryBuilder.queryName(queryName);
return queryBuilder;
}
@Override
protected Query doToQuery(SearchExecutionContext context) throws IOException {
String fieldInQuery = fieldName;
MappedFieldType fieldType = context.getFieldType(fieldName);
if (fieldType != null) {
fieldInQuery = fieldType.name();
}
Query innerQuery = queryBuilder.toQuery(context);
assert innerQuery instanceof SpanQuery;
return new FieldMaskingSpanQuery((SpanQuery) innerQuery, fieldInQuery);
}
@Override
protected int doHashCode() {
return Objects.hash(queryBuilder, fieldName);
}
@Override
protected boolean doEquals(FieldMaskingSpanQueryBuilder other) {
return Objects.equals(queryBuilder, other.queryBuilder) && Objects.equals(fieldName, other.fieldName);
}
@Override
public String getWriteableName() {
return NAME.getPreferredName();
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersion.zero();
}
}
| FieldMaskingSpanQueryBuilder |
java | spring-projects__spring-security | saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilter.java | {
"start": 1986,
"end": 6561
} | class ____ extends OncePerRequestFilter {
public static final String DEFAULT_METADATA_FILE_NAME = "saml-{registrationId}-metadata.xml";
private final Saml2MetadataResponseResolver metadataResolver;
public Saml2MetadataFilter(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver,
Saml2MetadataResolver saml2MetadataResolver) {
Assert.notNull(relyingPartyRegistrationResolver, "relyingPartyRegistrationResolver cannot be null");
Assert.notNull(saml2MetadataResolver, "saml2MetadataResolver cannot be null");
this.metadataResolver = new Saml2MetadataResponseResolverAdapter(relyingPartyRegistrationResolver,
saml2MetadataResolver);
}
/**
* Constructs an instance of {@link Saml2MetadataFilter} using the provided
* parameters. The {@link #metadataResolver} field will be initialized with a
* {@link DefaultRelyingPartyRegistrationResolver} instance using the provided
* {@link RelyingPartyRegistrationRepository}
* @param relyingPartyRegistrationRepository the
* {@link RelyingPartyRegistrationRepository} to use
* @param saml2MetadataResolver the {@link Saml2MetadataResolver} to use
* @since 6.1
*/
public Saml2MetadataFilter(RelyingPartyRegistrationRepository relyingPartyRegistrationRepository,
Saml2MetadataResolver saml2MetadataResolver) {
this(new DefaultRelyingPartyRegistrationResolver(relyingPartyRegistrationRepository), saml2MetadataResolver);
}
/**
* Constructs an instance of {@link Saml2MetadataFilter}
* @param metadataResponseResolver the strategy for producing metadata
* @since 6.1
*/
public Saml2MetadataFilter(Saml2MetadataResponseResolver metadataResponseResolver) {
this.metadataResolver = metadataResponseResolver;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
Saml2MetadataResponse metadata;
try {
metadata = this.metadataResolver.resolve(request);
}
catch (Saml2Exception ex) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
if (metadata == null) {
chain.doFilter(request, response);
return;
}
writeMetadataToResponse(response, metadata);
}
private void writeMetadataToResponse(HttpServletResponse response, Saml2MetadataResponse metadata)
throws IOException {
response.setContentType("application/samlmetadata+xml");
String format = "attachment; filename=\"%s\"; filename*=UTF-8''%s";
String fileName = metadata.getFileName();
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format(format, fileName, encodedFileName));
response.setContentLength(metadata.getMetadata().getBytes(StandardCharsets.UTF_8).length);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.getWriter().write(metadata.getMetadata());
}
/**
* Set the {@link RequestMatcher} that determines whether this filter should handle
* the incoming {@link HttpServletRequest}
* @param requestMatcher the {@link RequestMatcher} to identify requests for metadata
*/
public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
Assert.isInstanceOf(Saml2MetadataResponseResolverAdapter.class, this.metadataResolver,
"a Saml2MetadataResponseResolver and RequestMatcher cannot be both set on this filter. Please set the request matcher on the Saml2MetadataResponseResolver itself.");
((Saml2MetadataResponseResolverAdapter) this.metadataResolver).setRequestMatcher(requestMatcher);
}
/**
* Sets the metadata filename template containing the {@code {registrationId}}
* template variable.
*
* <p>
* The default value is {@code saml-{registrationId}-metadata.xml}
* @param metadataFilename metadata filename, must contain a {registrationId}
* @since 5.5
*/
public void setMetadataFilename(String metadataFilename) {
Assert.hasText(metadataFilename, "metadataFilename cannot be empty");
Assert.isTrue(metadataFilename.contains("{registrationId}"),
"metadataFilename must contain a {registrationId} match variable");
Assert.isInstanceOf(Saml2MetadataResponseResolverAdapter.class, this.metadataResolver,
"a Saml2MetadataResponseResolver and file name cannot be both set on this filter. Please set the file name on the Saml2MetadataResponseResolver itself.");
((Saml2MetadataResponseResolverAdapter) this.metadataResolver).setMetadataFilename(metadataFilename);
}
private static final | Saml2MetadataFilter |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/util/collections/binary/BytesMultiMapTestBase.java | {
"start": 2146,
"end": 5680
} | class ____<K> extends BytesMapTestBase {
protected static final int NUM_VALUE_PER_KEY = 50;
static final LogicalType[] KEY_TYPES =
new LogicalType[] {
new IntType(),
VarCharType.STRING_TYPE,
new DoubleType(),
new BigIntType(),
new BooleanType(),
new FloatType(),
new SmallIntType()
};
static final LogicalType[] VALUE_TYPES =
new LogicalType[] {
VarCharType.STRING_TYPE, new IntType(),
};
protected final PagedTypeSerializer<K> keySerializer;
protected final BinaryRowDataSerializer valueSerializer;
public BytesMultiMapTestBase(PagedTypeSerializer<K> keySerializer) {
this.keySerializer = keySerializer;
this.valueSerializer = new BinaryRowDataSerializer(VALUE_TYPES.length);
}
/**
* Creates the specific BytesHashMap, either {@link BytesMultiMap} or {@link
* WindowBytesMultiMap}.
*/
public abstract AbstractBytesMultiMap<K> createBytesMultiMap(
MemoryManager memoryManager,
int memorySize,
LogicalType[] keyTypes,
LogicalType[] valueTypes);
/**
* Generates {@code num} random keys, the types of key fields are defined in {@link #KEY_TYPES}.
*/
public abstract K[] generateRandomKeys(int num);
// ------------------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------------------
@Test
void testBuildAndRetrieve() throws Exception {
final int numMemSegments =
needNumMemSegments(
NUM_ENTRIES,
rowLength(RowType.of(VALUE_TYPES)),
rowLength(RowType.of(KEY_TYPES)),
PAGE_SIZE);
int memorySize = numMemSegments * PAGE_SIZE;
MemoryManager memoryManager =
MemoryManagerBuilder.newBuilder().setMemorySize(numMemSegments * PAGE_SIZE).build();
AbstractBytesMultiMap<K> table =
createBytesMultiMap(memoryManager, memorySize, KEY_TYPES, VALUE_TYPES);
K[] keys = generateRandomKeys(NUM_ENTRIES / 10);
BinaryRowData[] values = genValues(NUM_VALUE_PER_KEY);
for (K key : keys) {
BytesMap.LookupInfo<K, Iterator<RowData>> lookupInfo;
for (BinaryRowData value : values) {
lookupInfo = table.lookup(key);
table.append(lookupInfo, value);
}
}
KeyValueIterator<K, Iterator<RowData>> iter = table.getEntryIterator(false);
while (iter.advanceNext()) {
int i = 0;
Iterator<RowData> valueIter = iter.getValue();
while (valueIter.hasNext()) {
assertThat(values[i++]).isEqualTo(valueIter.next());
}
}
}
private BinaryRowData[] genValues(int num) {
BinaryRowData[] values = new BinaryRowData[num];
final Random rnd = new Random(RANDOM_SEED);
for (int i = 0; i < num; i++) {
values[i] = new BinaryRowData(2);
BinaryRowWriter writer = new BinaryRowWriter(values[i]);
writer.writeString(0, StringData.fromString("string" + rnd.nextInt()));
writer.writeInt(1, rnd.nextInt());
writer.complete();
}
return values;
}
}
| BytesMultiMapTestBase |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestMapReduce.java | {
"start": 7660,
"end": 8033
} | class ____
extends Mapper<IntWritable, IntWritable, IntWritable, IntWritable> {
public void map(IntWritable key, IntWritable val,
Context context) throws IOException, InterruptedException {
int keyint = key.get();
int valint = val.get();
context.write(new IntWritable(keyint), new IntWritable(valint));
}
}
static | MergeMapper |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/jdk/TypedArraySerTest.java | {
"start": 1966,
"end": 4250
} | class ____ {
@JsonView({Object.class})
public List<Bean> beans = new ArrayList<Bean>();
{
beans.add(new Bean());
}
}
/*
/**********************************************************
/* Unit tests, Lists
/**********************************************************
*/
// Since one of the tests uses VIEW inclusion, let's specify inclusion
// (as default varies between Jackson 2.x and 3.x)
private final ObjectMapper MAPPER = jsonMapperBuilder()
.enable(MapperFeature.DEFAULT_VIEW_INCLUSION)
.build();
@Test
public void testListWithPolymorphic() throws Exception
{
BeanListWrapper beans = new BeanListWrapper();
assertEquals("{\"beans\":[{\"@type\":\"bean\",\"x\":0}]}", MAPPER.writeValueAsString(beans));
// Related to [JACKSON-364]
ObjectWriter w = MAPPER.writerWithView(Object.class);
assertEquals("{\"beans\":[{\"@type\":\"bean\",\"x\":0}]}", w.writeValueAsString(beans));
}
@Test
public void testIntList() throws Exception
{
TypedList<Integer> input = new TypedList<Integer>();
input.add(5);
input.add(13);
// uses WRAPPER_ARRAY inclusion:
assertEquals("[\""+TypedList.class.getName()+"\",[5,13]]",
MAPPER.writeValueAsString(input));
}
// Similar to above, but this time let's request adding type info
// as property. That would not work (since there's no JSON Object to
// add property in), so it should revert to method used with
// ARRAY_WRAPPER method.
@Test
public void testStringListAsProp() throws Exception
{
TypedListAsProp<String> input = new TypedListAsProp<String>();
input.add("a");
input.add("b");
assertEquals("[\""+TypedListAsProp.class.getName()+"\",[\"a\",\"b\"]]",
MAPPER.writeValueAsString(input));
}
@Test
public void testStringListAsObjectWrapper() throws Exception
{
TypedListAsWrapper<Boolean> input = new TypedListAsWrapper<Boolean>();
input.add(true);
input.add(null);
input.add(false);
// Can wrap in JSON Object for wrapped style... also, will use
// non-qualified | BeanListWrapper |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.