language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__camel
components/camel-olingo4/camel-olingo4-api/src/main/java/org/apache/camel/component/olingo4/api/Olingo4ResponseHandler.java
{ "start": 891, "end": 956 }
interface ____ asynchronously process Olingo4 response. */ public
to
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/javadoc/NotJavadocTest.java
{ "start": 1407, "end": 1609 }
class ____ { void test() { /** Not Javadoc. */ } } """) .addOutputLines( "Test.java", """
Test
java
elastic__elasticsearch
modules/repository-gcs/src/test/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageServiceTests.java
{ "start": 1956, "end": 13718 }
class ____ extends ESTestCase { public void testClientInitializer() throws Exception { final String clientName = randomAlphaOfLength(randomIntBetween(1, 10)).toLowerCase(Locale.ROOT); final TimeValue connectTimeValue = TimeValue.timeValueNanos(randomIntBetween(0, 2000000)); final TimeValue readTimeValue = TimeValue.timeValueNanos(randomIntBetween(0, 2000000)); final String applicationName = randomAlphaOfLength(randomIntBetween(1, 10)).toLowerCase(Locale.ROOT); final String endpoint = randomFrom("http://", "https://") + randomFrom("www.elastic.co", "www.googleapis.com", "localhost/api", "google.com/oauth") + ":" + randomIntBetween(1, 65535); final String projectIdName = randomAlphaOfLength(randomIntBetween(1, 10)).toLowerCase(Locale.ROOT); final Settings settings = Settings.builder() .put( GoogleCloudStorageClientSettings.CONNECT_TIMEOUT_SETTING.getConcreteSettingForNamespace(clientName).getKey(), connectTimeValue.getStringRep() ) .put( GoogleCloudStorageClientSettings.READ_TIMEOUT_SETTING.getConcreteSettingForNamespace(clientName).getKey(), readTimeValue.getStringRep() ) .put( GoogleCloudStorageClientSettings.APPLICATION_NAME_SETTING.getConcreteSettingForNamespace(clientName).getKey(), applicationName ) .put(GoogleCloudStorageClientSettings.ENDPOINT_SETTING.getConcreteSettingForNamespace(clientName).getKey(), endpoint) .put(GoogleCloudStorageClientSettings.PROJECT_ID_SETTING.getConcreteSettingForNamespace(clientName).getKey(), projectIdName) .put(GoogleCloudStorageClientSettings.PROXY_TYPE_SETTING.getConcreteSettingForNamespace(clientName).getKey(), "HTTP") .put(GoogleCloudStorageClientSettings.PROXY_HOST_SETTING.getConcreteSettingForNamespace(clientName).getKey(), "192.168.52.15") .put(GoogleCloudStorageClientSettings.PROXY_PORT_SETTING.getConcreteSettingForNamespace(clientName).getKey(), 8080) .build(); SetOnce<Proxy> proxy = new SetOnce<>(); final var clusterService = ClusterServiceUtils.createClusterService(new DeterministicTaskQueue().getThreadPool()); final GoogleCloudStorageService service = new GoogleCloudStorageService(clusterService, TestProjectResolvers.DEFAULT_PROJECT_ONLY) { @Override void notifyProxyIsSet(Proxy p) { proxy.set(p); } }; service.refreshAndClearCache(GoogleCloudStorageClientSettings.load(settings)); var statsCollector = new GcsRepositoryStatsCollector(); final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> service.client(projectIdForClusterClient(), "another_client", "repo", statsCollector) ); assertThat(e.getMessage(), Matchers.startsWith("Unknown client name")); assertSettingDeprecationsAndWarnings( new Setting<?>[] { GoogleCloudStorageClientSettings.APPLICATION_NAME_SETTING.getConcreteSettingForNamespace(clientName) } ); final var storage = service.client(projectIdForClusterClient(), clientName, "repo", statsCollector); assertThat(storage.getOptions().getApplicationName(), Matchers.containsString(applicationName)); assertThat(storage.getOptions().getHost(), Matchers.is(endpoint)); assertThat(storage.getOptions().getProjectId(), Matchers.is(projectIdName)); assertThat(storage.getOptions().getTransportOptions(), Matchers.instanceOf(HttpTransportOptions.class)); assertThat( ((HttpTransportOptions) storage.getOptions().getTransportOptions()).getConnectTimeout(), Matchers.is((int) connectTimeValue.millis()) ); assertThat( ((HttpTransportOptions) storage.getOptions().getTransportOptions()).getReadTimeout(), Matchers.is((int) readTimeValue.millis()) ); assertThat(proxy.get().toString(), equalTo("HTTP @ /192.168.52.15:8080")); } public void testReinitClientSettings() throws Exception { final MockSecureSettings secureSettings1 = new MockSecureSettings(); secureSettings1.setFile("gcs.client.gcs1.credentials_file", serviceAccountFileContent("project_gcs11")); secureSettings1.setFile("gcs.client.gcs2.credentials_file", serviceAccountFileContent("project_gcs12")); final Settings settings1 = Settings.builder().setSecureSettings(secureSettings1).build(); final MockSecureSettings secureSettings2 = new MockSecureSettings(); secureSettings2.setFile("gcs.client.gcs1.credentials_file", serviceAccountFileContent("project_gcs21")); secureSettings2.setFile("gcs.client.gcs3.credentials_file", serviceAccountFileContent("project_gcs23")); final Settings settings2 = Settings.builder().setSecureSettings(secureSettings2).build(); final var pluginServices = mock(Plugin.PluginServices.class); when(pluginServices.clusterService()).thenReturn( ClusterServiceUtils.createClusterService(new DeterministicTaskQueue().getThreadPool()) ); when(pluginServices.projectResolver()).thenReturn(TestProjectResolvers.DEFAULT_PROJECT_ONLY); try (GoogleCloudStoragePlugin plugin = new GoogleCloudStoragePlugin(settings1)) { plugin.createComponents(pluginServices); final GoogleCloudStorageService storageService = plugin.storageService.get(); var statsCollector = new GcsRepositoryStatsCollector(); final var client11 = storageService.client(projectIdForClusterClient(), "gcs1", "repo1", statsCollector); assertThat(client11.getOptions().getProjectId(), equalTo("project_gcs11")); final var client12 = storageService.client(projectIdForClusterClient(), "gcs2", "repo2", statsCollector); assertThat(client12.getOptions().getProjectId(), equalTo("project_gcs12")); // client 3 is missing final IllegalArgumentException e1 = expectThrows( IllegalArgumentException.class, () -> storageService.client(projectIdForClusterClient(), "gcs3", "repo3", statsCollector) ); assertThat(e1.getMessage(), containsString("Unknown client name [gcs3].")); // update client settings plugin.reload(settings2); // old client 1 not changed assertThat(client11.getOptions().getProjectId(), equalTo("project_gcs11")); // new client 1 is changed final var client21 = storageService.client(projectIdForClusterClient(), "gcs1", "repo1", statsCollector); assertThat(client21.getOptions().getProjectId(), equalTo("project_gcs21")); // old client 2 not changed assertThat(client12.getOptions().getProjectId(), equalTo("project_gcs12")); // new client2 is gone final IllegalArgumentException e2 = expectThrows( IllegalArgumentException.class, () -> storageService.client(projectIdForClusterClient(), "gcs2", "repo2", statsCollector) ); assertThat(e2.getMessage(), containsString("Unknown client name [gcs2].")); // client 3 emerged final var client23 = storageService.client(projectIdForClusterClient(), "gcs3", "repo3", statsCollector); assertThat(client23.getOptions().getProjectId(), equalTo("project_gcs23")); } } public void testClientsAreNotSharedAcrossRepositories() throws Exception { final MockSecureSettings secureSettings1 = new MockSecureSettings(); secureSettings1.setFile("gcs.client.gcs1.credentials_file", serviceAccountFileContent("test_project")); final Settings settings = Settings.builder().setSecureSettings(secureSettings1).build(); final var pluginServices = mock(Plugin.PluginServices.class); when(pluginServices.clusterService()).thenReturn( ClusterServiceUtils.createClusterService(new DeterministicTaskQueue().getThreadPool()) ); when(pluginServices.projectResolver()).thenReturn(TestProjectResolvers.DEFAULT_PROJECT_ONLY); try (GoogleCloudStoragePlugin plugin = new GoogleCloudStoragePlugin(settings)) { plugin.createComponents(pluginServices); final GoogleCloudStorageService storageService = plugin.storageService.get(); final MeteredStorage repo1Client = storageService.client( projectIdForClusterClient(), "gcs1", "repo1", new GcsRepositoryStatsCollector() ); final MeteredStorage repo2Client = storageService.client( projectIdForClusterClient(), "gcs1", "repo2", new GcsRepositoryStatsCollector() ); final MeteredStorage repo1ClientSecondInstance = storageService.client( projectIdForClusterClient(), "gcs1", "repo1", new GcsRepositoryStatsCollector() ); assertNotSame(repo1Client, repo2Client); assertSame(repo1Client, repo1ClientSecondInstance); } } private byte[] serviceAccountFileContent(String projectId) throws Exception { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final String encodedKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()); final XContentBuilder serviceAccountBuilder = jsonBuilder().startObject() .field("type", "service_account") .field("project_id", projectId) .field("private_key_id", UUID.randomUUID().toString()) .field("private_key", "-----BEGIN PRIVATE KEY-----\n" + encodedKey + "\n-----END PRIVATE KEY-----\n") .field("client_email", "integration_test@appspot.gserviceaccount.com") .field("client_id", "client_id") .endObject(); return BytesReference.toBytes(BytesReference.bytes(serviceAccountBuilder)); } public void testToTimeout() { assertEquals(-1, GoogleCloudStorageService.toTimeout(null).intValue()); assertEquals(-1, GoogleCloudStorageService.toTimeout(TimeValue.ZERO).intValue()); assertEquals(0, GoogleCloudStorageService.toTimeout(TimeValue.MINUS_ONE).intValue()); } public void testGetDefaultProjectIdViaProxy() throws Exception { String proxyProjectId = randomAlphaOfLength(16); var proxyServer = new MockHttpProxyServer() { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) { assertEquals( "GET http://metadata.google.internal/computeMetadata/v1/project/project-id HTTP/1.1", request.getRequestLine().toString() ); response.setEntity(new StringEntity(proxyProjectId, ContentType.TEXT_PLAIN)); } }; try (proxyServer) { var proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getLoopbackAddress(), proxyServer.getPort())); assertEquals(proxyProjectId, GoogleCloudStorageService.getDefaultProjectId(proxy)); } } private ProjectId projectIdForClusterClient() { return randomBoolean() ? ProjectId.DEFAULT : null; } }
GoogleCloudStorageServiceTests
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/support/ReflectionSupport.java
{ "start": 23600, "end": 24364 }
interface ____ which to find the fields; never {@code null} * @param predicate the field filter; never {@code null} * @param traversalMode the hierarchy traversal mode; never {@code null} * @return an immutable list of all such fields found; never {@code null} * but potentially empty * @since 1.4 */ @API(status = MAINTAINED, since = "1.4") public static List<Field> findFields(Class<?> clazz, Predicate<Field> predicate, HierarchyTraversalMode traversalMode) { Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null"); return ReflectionUtils.findFields(clazz, predicate, ReflectionUtils.HierarchyTraversalMode.valueOf(traversalMode.name())); } /** * Find all distinct {@linkplain Field fields} of the supplied
in
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/date/XMLGregorianCalendarTest.java
{ "start": 304, "end": 1363 }
class ____ extends TestCase { public void test_for_issue() throws Exception { GregorianCalendar gregorianCalendar = (GregorianCalendar) GregorianCalendar.getInstance(); XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar); String text = JSON.toJSONString(calendar); Assert.assertEquals(Long.toString(gregorianCalendar.getTimeInMillis()), text); XMLGregorianCalendar calendar1 = JSON.parseObject(text, XMLGregorianCalendar.class); assertEquals(calendar.toGregorianCalendar().getTimeInMillis(), calendar1.toGregorianCalendar().getTimeInMillis()); JSONObject jsonObject = new JSONObject(); jsonObject.put("calendar", calendar); String json = JSON.toJSONString(jsonObject); Model model = JSON.parseObject(json).toJavaObject(Model.class); assertEquals(calendar.toGregorianCalendar().getTimeInMillis(), model.calendar.toGregorianCalendar().getTimeInMillis()); } public static
XMLGregorianCalendarTest
java
google__truth
core/src/main/java/com/google/common/truth/TruthJUnit.java
{ "start": 1411, "end": 2196 }
class ____ { @SuppressWarnings("ConstantCaseForConstants") // Despite the "Builder" name, it's not mutable. private static final StandardSubjectBuilder ASSUME = StandardSubjectBuilder.forCustomFailureStrategy( failure -> { AssumptionViolatedException assumptionViolated = new AssumptionViolatedException(failure.getMessage(), failure.getCause()); assumptionViolated.setStackTrace(failure.getStackTrace()); throw assumptionViolated; }); /** * Begins a call chain with the fluent Truth API. If the check made by the chain fails, it will * throw {@link AssumptionViolatedException}. */ public static StandardSubjectBuilder assume() { return ASSUME; } private TruthJUnit() {} }
TruthJUnit
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/desktop/ConstructorPropertiesAnnotationTest.java
{ "start": 2145, "end": 2628 }
class ____ { @JsonProperty("name") private final String name; @JsonProperty("dumbMap") private final Map<String, String> dumbMap; @JsonCreator public Value3252(@JsonProperty("name") String name, @JsonProperty("dumbMap") Map<String, String> dumbMap) { this.name = name; this.dumbMap = (dumbMap == null) ? Collections.emptyMap() : dumbMap; } } // [databind#4310] static
Value3252
java
micronaut-projects__micronaut-core
http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/staticresources/StaticResourceTest.java
{ "start": 1280, "end": 2024 }
class ____ { public static final String SPEC_NAME = "StaticResourceTest"; @Test public void staticResource() throws IOException { asserts(SPEC_NAME, CollectionUtils.mapOf( "micronaut.router.static-resources.assets.mapping", "/assets/**", "micronaut.router.static-resources.assets.paths", "classpath:assets"), HttpRequest.GET(UriBuilder.of("/assets").path("hello.txt").build()).accept(MediaType.TEXT_PLAIN), (server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpStatus.OK, "Hello World", Collections.singletonMap(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN))); } }
StaticResourceTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/rules/physical/local/PushTopNToSource.java
{ "start": 3807, "end": 12329 }
interface ____ { PhysicalPlan rewrite(TopNExec topNExec); } private static final Pushable NO_OP = new NoOpPushable(); record NoOpPushable() implements Pushable { public PhysicalPlan rewrite(TopNExec topNExec) { return topNExec; } } record PushableQueryExec(EsQueryExec queryExec) implements Pushable { public PhysicalPlan rewrite(TopNExec topNExec) { var sorts = buildFieldSorts(topNExec.order()); var limit = topNExec.limit(); return queryExec.withSorts(sorts).withLimit(limit); } } record PushableGeoDistance(FieldAttribute fieldAttribute, Order order, Point point) { private EsQueryExec.Sort sort() { return new EsQueryExec.GeoDistanceSort(fieldAttribute.exactAttribute(), order.direction(), point.getLat(), point.getLon()); } private static PushableGeoDistance from(FoldContext ctx, StDistance distance, Order order) { if (distance.left() instanceof Attribute attr && distance.right().foldable()) { return from(ctx, attr, distance.right(), order); } else if (distance.right() instanceof Attribute attr && distance.left().foldable()) { return from(ctx, attr, distance.left(), order); } return null; } private static PushableGeoDistance from(FoldContext ctx, Attribute attr, Expression foldable, Order order) { if (attr instanceof FieldAttribute fieldAttribute) { Geometry geometry = SpatialRelatesUtils.makeGeometryFromLiteral(ctx, foldable); if (geometry instanceof Point point) { return new PushableGeoDistance(fieldAttribute, order, point); } } return null; } } record PushableCompoundExec(EvalExec evalExec, EsQueryExec queryExec, List<EsQueryExec.Sort> pushableSorts) implements Pushable { public PhysicalPlan rewrite(TopNExec topNExec) { // We need to keep the EVAL in place because the coordinator will have its own TopNExec so we need to keep the distance return evalExec.replaceChild(queryExec.withSorts(pushableSorts).withLimit(topNExec.limit())); } } private static Pushable evaluatePushable( PlannerSettings plannerSettings, FoldContext ctx, TopNExec topNExec, LucenePushdownPredicates lucenePushdownPredicates ) { PhysicalPlan child = topNExec.child(); if (child instanceof EsQueryExec queryExec && queryExec.canPushSorts() && canPushDownOrders(topNExec.order(), lucenePushdownPredicates) && canPushLimit(topNExec, plannerSettings)) { // With the simplest case of `FROM index | SORT ...` we only allow pushing down if the sort is on a field return new PushableQueryExec(queryExec); } if (child instanceof EvalExec evalExec && evalExec.child() instanceof EsQueryExec queryExec && queryExec.canPushSorts() && canPushLimit(topNExec, plannerSettings)) { // When we have an EVAL between the FROM and the SORT, we consider pushing down if the sort is on a field and/or // a distance function defined in the EVAL. We also move the EVAL to after the SORT. List<Order> orders = topNExec.order(); List<Alias> fields = evalExec.fields(); LinkedHashMap<NameId, StDistance> distances = new LinkedHashMap<>(); AttributeMap.Builder<Attribute> aliasReplacedByBuilder = AttributeMap.builder(); fields.forEach(alias -> { // TODO: can we support CARTESIAN also? if (alias.child() instanceof StDistance distance && distance.crsType() == BinarySpatialFunction.SpatialCrsType.GEO) { distances.put(alias.id(), distance); } else if (alias.child() instanceof Attribute attr) { aliasReplacedByBuilder.put(alias.toAttribute(), attr.toAttribute()); } }); AttributeMap<Attribute> aliasReplacedBy = aliasReplacedByBuilder.build(); List<EsQueryExec.Sort> pushableSorts = new ArrayList<>(); for (Order order : orders) { if (lucenePushdownPredicates.isPushableFieldAttribute(order.child())) { pushableSorts.add( new EsQueryExec.FieldSort( ((FieldAttribute) order.child()).exactAttribute(), order.direction(), order.nullsPosition() ) ); } else if (LucenePushdownPredicates.isPushableMetadataAttribute(order.child())) { pushableSorts.add(new EsQueryExec.ScoreSort(order.direction())); } else if (order.child() instanceof ReferenceAttribute referenceAttribute) { Attribute resolvedAttribute = aliasReplacedBy.resolve(referenceAttribute, referenceAttribute); if (distances.containsKey(resolvedAttribute.id())) { StDistance distance = distances.get(resolvedAttribute.id()); StDistance d = (StDistance) distance.transformDown(ReferenceAttribute.class, r -> aliasReplacedBy.resolve(r, r)); PushableGeoDistance pushableGeoDistance = PushableGeoDistance.from(ctx, d, order); if (pushableGeoDistance != null) { pushableSorts.add(pushableGeoDistance.sort()); } else { // As soon as we see a non-pushable sort, we know we need a final SORT command break; } } else if (aliasReplacedBy.resolve(referenceAttribute, referenceAttribute) instanceof FieldAttribute fieldAttribute && lucenePushdownPredicates.isPushableFieldAttribute(fieldAttribute)) { // If the SORT refers to a reference to a pushable field, we can push it down pushableSorts.add( new EsQueryExec.FieldSort(fieldAttribute.exactAttribute(), order.direction(), order.nullsPosition()) ); } else { // If the SORT refers to a non-pushable reference function, the EVAL must remain before the SORT, // and we can no longer push down anything break; } } else { // As soon as we see a non-pushable sort, we know we need a final SORT command break; } } if (pushableSorts.isEmpty() == false) { return new PushableCompoundExec(evalExec, queryExec, pushableSorts); } } return NO_OP; } private static boolean canPushDownOrders(List<Order> orders, LucenePushdownPredicates lucenePushdownPredicates) { // allow only exact FieldAttributes (no expressions) for sorting BiFunction<Expression, LucenePushdownPredicates, Boolean> isSortableAttribute = (exp, lpp) -> lpp.isPushableFieldAttribute(exp) // TODO: https://github.com/elastic/elasticsearch/issues/120219 || MetadataAttribute.isScoreAttribute(exp); return orders.stream().allMatch(o -> isSortableAttribute.apply(o.child(), lucenePushdownPredicates)); } private static boolean canPushLimit(TopNExec topn, PlannerSettings plannerSettings) { return Foldables.limitValue(topn.limit(), topn.sourceText()) <= plannerSettings.luceneTopNLimit(); } private static List<EsQueryExec.Sort> buildFieldSorts(List<Order> orders) { List<EsQueryExec.Sort> sorts = new ArrayList<>(orders.size()); for (Order o : orders) { if (o.child() instanceof FieldAttribute fa) { sorts.add(new EsQueryExec.FieldSort(fa.exactAttribute(), o.direction(), o.nullsPosition())); } else if (MetadataAttribute.isScoreAttribute(o.child())) { sorts.add(new EsQueryExec.ScoreSort(o.direction())); } else { assert false : "unexpected ordering on expression type " + o.child().getClass(); } } return sorts; } }
Pushable
java
quarkusio__quarkus
extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/KafkaProcessor.java
{ "start": 29521, "end": 29914 }
class ____ implements BooleanSupplier { private final KafkaBuildTimeConfig config; public HasSnappy(KafkaBuildTimeConfig config) { this.config = config; } @Override public boolean getAsBoolean() { return QuarkusClassLoader.isClassPresentAtRuntime("org.xerial.snappy.OSInfo") && config.snappyEnabled(); } } }
HasSnappy
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRuleTest.java
{ "start": 13105, "end": 13358 }
class ____ extends AsyncScalarFunction { @DataTypeHint("ROW<f0 INT, f1 String>") public void eval(CompletableFuture<Row> future, Integer a) { future.complete(Row.of(a + 1, "" + (a * a))); } } public static
Func5
java
apache__flink
flink-docs/src/test/java/org/apache/flink/docs/configuration/ConfigOptionsDocGeneratorTest.java
{ "start": 37687, "end": 37742 }
class ____ {} @Internal static
ExperimentalOptions
java
apache__camel
components/camel-ai/camel-torchserve/src/main/java/org/apache/camel/component/torchserve/client/model/UnregisterOptions.java
{ "start": 871, "end": 1678 }
class ____ { /** * Decides whether the call is synchronous or not, default: false. (optional, default to false) */ private Boolean synchronous = null; /** * Waiting up to the specified wait time if necessary for a worker to complete all pending requests. Use 0 to * terminate backend worker process immediately. Use -1 for wait infinitely. (optional) */ private Integer timeout = null; private UnregisterOptions() { } public static UnregisterOptions empty() { return new UnregisterOptions(); } public static Builder builder() { return new Builder(); } public Boolean getSynchronous() { return synchronous; } public Integer getTimeout() { return timeout; } public static
UnregisterOptions
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/support/TransportActionFilterChainTests.java
{ "start": 11754, "end": 11942 }
class ____ extends LegacyActionRequest { @Override public ActionRequestValidationException validate() { return null; } } private static
TestRequest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/event/FileSystemJobEventStore.java
{ "start": 2594, "end": 14057 }
class ____ implements JobEventStore { private static final Logger LOG = LoggerFactory.getLogger(FileSystemJobEventStore.class); private static final String FILE_PREFIX = "events."; private static final int INITIAL_FILE_INDEX = 0; private final FileSystem fileSystem; private final Path workingDir; private FsBatchFlushOutputStream outputStream; private Path writeFile; private int writeIndex; private ScheduledExecutorService eventWriterExecutor; private DataInputStream inputStream; private int readIndex; private List<Path> readFiles; /** * Flag indicating whether the event store has become corrupted. When this flag is true, the * store is considered to no longer be in a healthy state for enable writing new events. */ private volatile boolean corrupted = false; private final long flushIntervalInMs; private final int writeBufferSize; private final Map<Integer, SimpleVersionedSerializer<JobEvent>> jobEventSerializers = new HashMap<>(); public FileSystemJobEventStore(JobID jobID, Configuration configuration) throws IOException { this( new Path( HighAvailabilityServicesUtils.getClusterHighAvailableStoragePath( configuration), jobID.toString() + "/job-events"), configuration); } @VisibleForTesting public FileSystemJobEventStore(Path workingDir, Configuration configuration) throws IOException { this.workingDir = checkNotNull(workingDir); this.fileSystem = workingDir.getFileSystem(); this.flushIntervalInMs = configuration.get(JobEventStoreOptions.FLUSH_INTERVAL).toMillis(); this.writeBufferSize = (int) configuration.get(JobEventStoreOptions.WRITE_BUFFER_SIZE).getBytes(); registerJobEventSerializers(); } void registerJobEventSerializer( int eventType, SimpleVersionedSerializer<JobEvent> simpleVersionedSerializer) { checkState(!jobEventSerializers.containsKey(eventType)); jobEventSerializers.put(eventType, simpleVersionedSerializer); } private void registerJobEventSerializers() { registerJobEventSerializer( JobEvents.getTypeID(ExecutionVertexFinishedEvent.class), new ExecutionVertexFinishedEvent.Serializer()); registerJobEventSerializer( JobEvents.getTypeID(ExecutionVertexResetEvent.class), new GenericJobEventSerializer()); registerJobEventSerializer( JobEvents.getTypeID(ExecutionJobVertexInitializedEvent.class), new GenericJobEventSerializer()); } @VisibleForTesting Path getWorkingDir() { return workingDir; } @VisibleForTesting ScheduledExecutorService getEventWriterExecutor() { return eventWriterExecutor; } @VisibleForTesting FsBatchFlushOutputStream getOutputStream() { return outputStream; } @Override public void start() throws IOException { // create job event dir. if (!fileSystem.exists(workingDir)) { fileSystem.mkdirs(workingDir); LOG.info("Create job event dir {}.", workingDir); } // get read files. try { readIndex = 0; readFiles = getAllJobEventFiles(); } catch (IOException e) { throw new IOException("Cannot init filesystem job event store.", e); } // set write index writeIndex = readFiles.size(); // create job event write executor. this.eventWriterExecutor = createJobEventWriterExecutor(); eventWriterExecutor.scheduleAtFixedRate( () -> { if (outputStream != null && !corrupted) { try { outputStream.flush(); } catch (Exception e) { LOG.warn( "Error happens when flushing event file {}. Do not record events any more.", writeFile, e); corrupted = true; closeOutputStream(); } } }, 0L, flushIntervalInMs, TimeUnit.MILLISECONDS); corrupted = false; } /** Get all event files available in workingDir. */ private List<Path> getAllJobEventFiles() throws IOException { List<Path> paths = new ArrayList<>(); int index = INITIAL_FILE_INDEX; Set<String> fileNames = Arrays.stream(fileSystem.listStatus(workingDir)) .map(fileStatus -> fileStatus.getPath().getName()) .filter(name -> name.startsWith(FILE_PREFIX)) .collect(Collectors.toSet()); while (fileNames.contains(FILE_PREFIX + index)) { paths.add(new Path(workingDir, FILE_PREFIX + index)); index++; } return paths; } protected ScheduledExecutorService createJobEventWriterExecutor() { return Executors.newSingleThreadScheduledExecutor( new ExecutorThreadFactory("job-event-writer")); } @Override public void stop(boolean clearEventLogs) { try { eventWriterExecutor.execute(this::closeOutputStream); closeInputStream(); if (eventWriterExecutor != null) { eventWriterExecutor.shutdown(); try { if (!eventWriterExecutor.awaitTermination(10, TimeUnit.SECONDS)) { eventWriterExecutor.shutdownNow(); } } catch (InterruptedException ignored) { eventWriterExecutor.shutdownNow(); } eventWriterExecutor = null; } if (clearEventLogs) { fileSystem.delete(workingDir, true); } } catch (Exception exception) { LOG.warn("Fail to stop filesystem job event store.", exception); } } @Override public void writeEvent(JobEvent event, boolean cutBlock) { checkNotNull(fileSystem); checkNotNull(event); eventWriterExecutor.execute(() -> writeEventRunnable(event, cutBlock)); } @VisibleForTesting protected void writeEventRunnable(JobEvent event, boolean cutBlock) { if (corrupted) { if (LOG.isDebugEnabled()) { LOG.debug("Skip job event {} because write corrupted.", event); } return; } try { if (outputStream == null) { openNewOutputStream(); } // write event. SimpleVersionedSerializer<JobEvent> serializer = checkNotNull( jobEventSerializers.get(event.getType()), "There is no registered serializer for job event with type " + event.getType()); byte[] binaryEvent = serializer.serialize(event); outputStream.writeInt(event.getType()); outputStream.writeInt(binaryEvent.length); outputStream.write(binaryEvent); if (LOG.isDebugEnabled()) { LOG.debug("Write job event {}.", event); } if (cutBlock) { closeOutputStream(); } } catch (Throwable throwable) { LOG.warn( "Error happens when writing event {} into {}. Do not record events any more.", event, writeFile, throwable); corrupted = true; closeOutputStream(); } } @VisibleForTesting void writeEvent(JobEvent event) { writeEvent(event, false); } @Override public JobEvent readEvent() throws Exception { try { JobEvent event = null; while (event == null) { try { if (inputStream == null && tryGetNewInputStream() == null) { return null; } // read event. int binaryEventType = inputStream.readInt(); int binaryEventSize = inputStream.readInt(); byte[] binaryEvent = new byte[binaryEventSize]; inputStream.readFully(binaryEvent); SimpleVersionedSerializer<JobEvent> serializer = checkNotNull( jobEventSerializers.get(binaryEventType), "There is no registered serializer for job event with type " + binaryEventType); event = serializer.deserialize( GenericJobEventSerializer.INSTANCE.getVersion(), binaryEvent); } catch (EOFException eof) { closeInputStream(); } } return event; } catch (Exception e) { throw new IOException("Cannot read next event from event store.", e); } } @Override public boolean isEmpty() throws Exception { return !fileSystem.exists(workingDir) || fileSystem.listStatus(workingDir).length == 0; } /** If current inputStream is null, try to get a new one. */ private DataInputStream tryGetNewInputStream() throws IOException { if (inputStream == null) { if (readIndex < readFiles.size()) { Path file = readFiles.get(readIndex++); inputStream = new DataInputStream(fileSystem.open(file)); LOG.info("Start reading job event file {}", file.getPath()); } } return inputStream; } /** Try to open a new output stream. */ private void openNewOutputStream() throws IOException { // get write file. writeFile = new Path(workingDir, FILE_PREFIX + writeIndex); outputStream = new FsBatchFlushOutputStream( fileSystem, writeFile, FileSystem.WriteMode.NO_OVERWRITE, writeBufferSize); LOG.info("Job events will be written to {}.", writeFile); writeIndex++; } /** Close output stream. Should be invoked in {@link #eventWriterExecutor}. */ @VisibleForTesting void closeOutputStream() { if (outputStream != null) { try { outputStream.close(); } catch (IOException exception) { LOG.warn( "Error happens when closing the output stream for {}. Do not record events any more.", writeFile, exception); corrupted = true; } finally { outputStream = null; } } } /** Close input stream. */ private void closeInputStream() throws IOException { if (inputStream != null) { inputStream.close(); inputStream = null; } } }
FileSystemJobEventStore
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/collection_injection/immutable/ImmutableHouseMapper.java
{ "start": 750, "end": 906 }
interface ____ { List<ImmutableHouse> getAllHouses(); ImmutableHouse getHouse(int it); HousePortfolio getHousePortfolio(int id); }
ImmutableHouseMapper
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/config/DefaultJupiterConfigurationTests.java
{ "start": 2441, "end": 9714 }
class ____ { private static final String KEY = DEFAULT_TEST_INSTANCE_LIFECYCLE_PROPERTY_NAME; @SuppressWarnings("DataFlowIssue") @Test void getDefaultTestInstanceLifecyclePreconditions() { assertPreconditionViolationNotNullFor("ConfigurationParameters", () -> new DefaultJupiterConfiguration(null, dummyOutputDirectoryCreator(), mock())); } @Test void getDefaultTestInstanceLifecycleWithNoConfigParamSet() { JupiterConfiguration configuration = new DefaultJupiterConfiguration(configurationParameters(Map.of()), dummyOutputDirectoryCreator(), mock()); Lifecycle lifecycle = configuration.getDefaultTestInstanceLifecycle(); assertThat(lifecycle).isEqualTo(PER_METHOD); } @Test void getDefaultTempDirCleanupModeWithNoConfigParamSet() { JupiterConfiguration configuration = new DefaultJupiterConfiguration(configurationParameters(Map.of()), dummyOutputDirectoryCreator(), mock()); CleanupMode cleanupMode = configuration.getDefaultTempDirCleanupMode(); assertThat(cleanupMode).isEqualTo(ALWAYS); } @Test void getDefaultTestInstanceLifecycleWithConfigParamSet() { assertAll(// () -> assertDefaultConfigParam(null, PER_METHOD), // () -> assertThatThrownBy(() -> getDefaultTestInstanceLifecycleConfigParam("")) // .hasMessage("Invalid test instance lifecycle mode '' set via the '%s' configuration parameter.", DEFAULT_TEST_INSTANCE_LIFECYCLE_PROPERTY_NAME), // () -> assertThatThrownBy(() -> getDefaultTestInstanceLifecycleConfigParam("bogus")) // .hasMessage( "Invalid test instance lifecycle mode 'BOGUS' set via the '%s' configuration parameter.", DEFAULT_TEST_INSTANCE_LIFECYCLE_PROPERTY_NAME), // () -> assertDefaultConfigParam(PER_METHOD.name(), PER_METHOD), // () -> assertDefaultConfigParam(PER_METHOD.name().toLowerCase(), PER_METHOD), // () -> assertDefaultConfigParam(" " + PER_METHOD.name() + " ", PER_METHOD), // () -> assertDefaultConfigParam(PER_CLASS.name(), PER_CLASS), // () -> assertDefaultConfigParam(PER_CLASS.name().toLowerCase(), PER_CLASS), // () -> assertDefaultConfigParam(" " + PER_CLASS.name() + " ", Lifecycle.PER_CLASS) // ); } @Test void shouldGetDefaultDisplayNameGeneratorWithConfigParamSet() { var parameters = configurationParameters( Map.of(Constants.DEFAULT_DISPLAY_NAME_GENERATOR_PROPERTY_NAME, CustomDisplayNameGenerator.class.getName())); JupiterConfiguration configuration = new DefaultJupiterConfiguration(parameters, dummyOutputDirectoryCreator(), mock()); DisplayNameGenerator defaultDisplayNameGenerator = configuration.getDefaultDisplayNameGenerator(); assertThat(defaultDisplayNameGenerator).isInstanceOf(CustomDisplayNameGenerator.class); } @Test void shouldGetStandardAsDefaultDisplayNameGeneratorWithoutConfigParamSet() { JupiterConfiguration configuration = new DefaultJupiterConfiguration(configurationParameters(Map.of()), dummyOutputDirectoryCreator(), mock()); DisplayNameGenerator defaultDisplayNameGenerator = configuration.getDefaultDisplayNameGenerator(); assertThat(defaultDisplayNameGenerator).isInstanceOf(DisplayNameGenerator.Standard.class); } @Test void shouldGetNothingAsDefaultTestMethodOrderWithoutConfigParamSet() { JupiterConfiguration configuration = new DefaultJupiterConfiguration(configurationParameters(Map.of()), dummyOutputDirectoryCreator(), mock()); final Optional<MethodOrderer> defaultTestMethodOrder = configuration.getDefaultTestMethodOrderer(); assertThat(defaultTestMethodOrder).isEmpty(); } @Test void shouldGetDefaultTempDirFactorySupplierWithConfigParamSet() { var parameters = configurationParameters( Map.of(Constants.DEFAULT_TEMP_DIR_FACTORY_PROPERTY_NAME, CustomFactory.class.getName())); JupiterConfiguration configuration = new DefaultJupiterConfiguration(parameters, dummyOutputDirectoryCreator(), mock()); Supplier<TempDirFactory> supplier = configuration.getDefaultTempDirFactorySupplier(); assertThat(supplier.get()).isInstanceOf(CustomFactory.class); } @Test void shouldGetStandardAsDefaultTempDirFactorySupplierWithoutConfigParamSet() { JupiterConfiguration configuration = new DefaultJupiterConfiguration(configurationParameters(Map.of()), dummyOutputDirectoryCreator(), mock()); Supplier<TempDirFactory> supplier = configuration.getDefaultTempDirFactorySupplier(); assertThat(supplier.get()).isSameAs(TempDirFactory.Standard.INSTANCE); } @Test void doesNotReportAnyIssuesIfConfigurationParametersAreEmpty() { List<DiscoveryIssue> issues = new ArrayList<>(); new DefaultJupiterConfiguration(configurationParameters(Map.of()), dummyOutputDirectoryCreator(), DiscoveryIssueReporter.collecting(issues)).getDefaultTestInstanceLifecycle(); assertThat(issues).isEmpty(); } @ParameterizedTest @EnumSource(ParallelExecutorServiceType.class) void doesNotReportAnyIssuesIfParallelExecutionIsEnabledAndConfigurationParameterIsSet( ParallelExecutorServiceType executorServiceType) { var parameters = Map.of(JupiterConfiguration.PARALLEL_EXECUTION_ENABLED_PROPERTY_NAME, true, // JupiterConfiguration.PARALLEL_CONFIG_EXECUTOR_SERVICE_PROPERTY_NAME, executorServiceType); List<DiscoveryIssue> issues = new ArrayList<>(); new DefaultJupiterConfiguration(ConfigurationParametersFactoryForTests.create(parameters), dummyOutputDirectoryCreator(), DiscoveryIssueReporter.collecting(issues)).getDefaultTestInstanceLifecycle(); assertThat(issues).isEmpty(); } @Test void asksUsersToTryWorkerThreadPoolHierarchicalExecutorServiceIfParallelExecutionIsEnabled() { var parameters = Map.of(JupiterConfiguration.PARALLEL_EXECUTION_ENABLED_PROPERTY_NAME, true); List<DiscoveryIssue> issues = new ArrayList<>(); new DefaultJupiterConfiguration(configurationParameters(parameters), dummyOutputDirectoryCreator(), DiscoveryIssueReporter.collecting(issues)).getDefaultTestInstanceLifecycle(); assertThat(issues).containsExactly(DiscoveryIssue.create(Severity.INFO, """ Parallel test execution is enabled but the default ForkJoinPool-based executor service will be used. \ Please give the new implementation based on a regular thread pool a try by setting the \ 'junit.jupiter.execution.parallel.config.executor-service' configuration parameter to \ 'WORKER_THREAD_POOL' and report any issues to the JUnit team. Alternatively, set the configuration \ parameter to 'FORK_JOIN_POOL' to hide this message and keep using the original implementation.""")); } private void assertDefaultConfigParam(@Nullable String configValue, Lifecycle expected) { var lifecycle = getDefaultTestInstanceLifecycleConfigParam(configValue); assertThat(lifecycle).isEqualTo(expected); } private static Lifecycle getDefaultTestInstanceLifecycleConfigParam(@Nullable String configValue) { var configParams = configurationParameters(configValue == null ? Map.of() : Map.of(KEY, configValue)); return new DefaultJupiterConfiguration(configParams, dummyOutputDirectoryCreator(), mock()).getDefaultTestInstanceLifecycle(); } private static ConfigurationParameters configurationParameters(Map<@NonNull String, ?> parameters) { return ConfigurationParametersFactoryForTests.create(parameters); } @NullMarked private static
DefaultJupiterConfigurationTests
java
apache__kafka
server/src/main/java/org/apache/kafka/server/share/CachedSharePartition.java
{ "start": 1657, "end": 5841 }
class ____ implements ImplicitLinkedHashCollection.Element { private final String topic; private final Uuid topicId; private final int partition; private final Optional<Integer> leaderEpoch; private boolean requiresUpdateInResponse; private int cachedNext = ImplicitLinkedHashCollection.INVALID_INDEX; private int cachedPrev = ImplicitLinkedHashCollection.INVALID_INDEX; private CachedSharePartition(String topic, Uuid topicId, int partition, Optional<Integer> leaderEpoch, boolean requiresUpdateInResponse) { this.topic = topic; this.topicId = topicId; this.partition = partition; this.leaderEpoch = leaderEpoch; this.requiresUpdateInResponse = requiresUpdateInResponse; } public CachedSharePartition(String topic, Uuid topicId, int partition, boolean requiresUpdateInResponse) { this(topic, topicId, partition, Optional.empty(), requiresUpdateInResponse); } public CachedSharePartition(TopicIdPartition topicIdPartition) { this(topicIdPartition.topic(), topicIdPartition.topicId(), topicIdPartition.partition(), false); } public CachedSharePartition(TopicIdPartition topicIdPartition, boolean requiresUpdateInResponse) { this(topicIdPartition.topic(), topicIdPartition.topicId(), topicIdPartition.partition(), Optional.empty(), requiresUpdateInResponse); } public Uuid topicId() { return topicId; } public String topic() { return topic; } public int partition() { return partition; } /** * Determine whether the specified cached partition should be included in the ShareFetchResponse we send back to * the fetcher and update it if requested. * This function should be called while holding the appropriate session lock. * * @param respData partition data * @param updateResponseData if set to true, update this CachedSharePartition with new request and response data. * @return True if this partition should be included in the response; false if it can be omitted. */ public boolean maybeUpdateResponseData(ShareFetchResponseData.PartitionData respData, boolean updateResponseData) { boolean mustRespond = false; // Check the response data // Partitions with new data are always included in the response. if (ShareFetchResponse.recordsSize(respData) > 0) mustRespond = true; if (requiresUpdateInResponse) { mustRespond = true; if (updateResponseData) requiresUpdateInResponse = false; } if (respData.errorCode() != Errors.NONE.code()) { // Partitions with errors are always included in the response. // We also set the cached requiresUpdateInResponse to false. // This ensures that when the error goes away, we re-send the partition. if (updateResponseData) requiresUpdateInResponse = true; mustRespond = true; } return mustRespond; } public String toString() { return "CachedSharePartition(topic=" + topic + ", topicId=" + topicId + ", partition=" + partition + ", leaderEpoch=" + leaderEpoch + ")"; } @Override public int hashCode() { return Objects.hash(partition, topicId); } @Override public boolean equals(final Object obj) { if (this == obj) return true; else if (obj == null || getClass() != obj.getClass()) return false; else { CachedSharePartition that = (CachedSharePartition) obj; return partition == that.partition && Objects.equals(topicId, that.topicId); } } @Override public int prev() { return cachedPrev; } @Override public void setPrev(int prev) { cachedPrev = prev; } @Override public int next() { return cachedNext; } @Override public void setNext(int next) { cachedNext = next; } }
CachedSharePartition
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/internal/SqmJdbcExecutionContextAdapter.java
{ "start": 620, "end": 2657 }
class ____ extends BaseExecutionContext { /** * Creates an adapter which drops any locking or paging details from the query options */ public static SqmJdbcExecutionContextAdapter omittingLockingAndPaging(DomainQueryExecutionContext sqmExecutionContext) { return new SqmJdbcExecutionContextAdapter( sqmExecutionContext ); } /** * Creates an adapter which honors any locking or paging details specified in the query options */ public static SqmJdbcExecutionContextAdapter usingLockingAndPaging(DomainQueryExecutionContext sqmExecutionContext) { return new SqmJdbcExecutionContextAdapter( sqmExecutionContext, sqmExecutionContext.getQueryOptions() ); } private final DomainQueryExecutionContext sqmExecutionContext; private final QueryOptions queryOptions; private SqmJdbcExecutionContextAdapter(DomainQueryExecutionContext sqmExecutionContext) { this( sqmExecutionContext, omitSqlQueryOptions( sqmExecutionContext.getQueryOptions() ) ); } private SqmJdbcExecutionContextAdapter(DomainQueryExecutionContext sqmExecutionContext, QueryOptions queryOptions) { super( sqmExecutionContext.getSession() ); this.sqmExecutionContext = sqmExecutionContext; this.queryOptions = queryOptions; } public SqmJdbcExecutionContextAdapter( DomainQueryExecutionContext sqmExecutionContext, JdbcSelect jdbcSelect) { this( sqmExecutionContext, omitSqlQueryOptions( sqmExecutionContext.getQueryOptions(), jdbcSelect ) ); } @Override public QueryOptions getQueryOptions() { return queryOptions; } @Override public QueryParameterBindings getQueryParameterBindings() { return sqmExecutionContext.getQueryParameterBindings(); } @Override public Callback getCallback() { return sqmExecutionContext.getCallback(); } @Override public boolean hasCallbackActions() { return sqmExecutionContext.hasCallbackActions(); } @Override public boolean hasQueryExecutionToBeAddedToStatistics() { return true; } @Override public boolean upgradeLocks() { return true; } }
SqmJdbcExecutionContextAdapter
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/aot/generate/FileSystemGeneratedFiles.java
{ "start": 3389, "end": 4225 }
class ____ extends FileHandler { private final Path path; FileSystemFileHandler(Path path) { super(Files.exists(path), () -> new FileSystemResource(path)); this.path = path; } @Override protected void copy(InputStreamSource content, boolean override) { if (override) { copy(content, StandardCopyOption.REPLACE_EXISTING); } else { copy(content); } } private void copy(InputStreamSource content, CopyOption... copyOptions) { try { try (InputStream inputStream = content.getInputStream()) { Files.createDirectories(this.path.getParent()); Files.copy(inputStream, this.path, copyOptions); } } catch (IOException ex) { throw new IllegalStateException(ex); } } @Override public String toString() { return this.path.toString(); } } }
FileSystemFileHandler
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/function/RouterFunctionsTests.java
{ "start": 1093, "end": 5266 }
class ____ { private final ServerRequest request = new DefaultServerRequest( PathPatternsTestUtils.initRequest("GET", "", true), Collections.emptyList()); @Test void routeMatch() { HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build(); RequestPredicate requestPredicate = mock(); given(requestPredicate.test(request)).willReturn(true); RouterFunction<ServerResponse> result = RouterFunctions.route(requestPredicate, handlerFunction); assertThat(result).isNotNull(); Optional<HandlerFunction<ServerResponse>> resultHandlerFunction = result.route(request); assertThat(resultHandlerFunction).isPresent(); assertThat(resultHandlerFunction).contains(handlerFunction); } @Test void routeNoMatch() { HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build(); RequestPredicate requestPredicate = mock(); given(requestPredicate.test(request)).willReturn(false); RouterFunction<ServerResponse> result = RouterFunctions.route(requestPredicate, handlerFunction); assertThat(result).isNotNull(); Optional<HandlerFunction<ServerResponse>> resultHandlerFunction = result.route(request); assertThat(resultHandlerFunction).isNotPresent(); } @Test void nestMatch() { HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build(); RouterFunction<ServerResponse> routerFunction = request -> Optional.of(handlerFunction); RequestPredicate requestPredicate = mock(); given(requestPredicate.nest(request)).willReturn(Optional.of(request)); RouterFunction<ServerResponse> result = RouterFunctions.nest(requestPredicate, routerFunction); assertThat(result).isNotNull(); Optional<HandlerFunction<ServerResponse>> resultHandlerFunction = result.route(request); assertThat(resultHandlerFunction).isPresent(); assertThat(resultHandlerFunction).contains(handlerFunction); } @Test void nestNoMatch() { HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build(); RouterFunction<ServerResponse> routerFunction = request -> Optional.of(handlerFunction); RequestPredicate requestPredicate = mock(); given(requestPredicate.nest(request)).willReturn(Optional.empty()); RouterFunction<ServerResponse> result = RouterFunctions.nest(requestPredicate, routerFunction); assertThat(result).isNotNull(); Optional<HandlerFunction<ServerResponse>> resultHandlerFunction = result.route(request); assertThat(resultHandlerFunction).isNotPresent(); } @Test void nestPathVariable() { HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build(); RequestPredicate requestPredicate = request -> request.pathVariable("foo").equals("bar"); RouterFunction<ServerResponse> nestedFunction = RouterFunctions.route(requestPredicate, handlerFunction); RouterFunction<ServerResponse> result = RouterFunctions.nest(RequestPredicates.path("/{foo}"), nestedFunction); assertThat(result).isNotNull(); MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/bar"); ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList()); Optional<HandlerFunction<ServerResponse>> resultHandlerFunction = result.route(request); assertThat(resultHandlerFunction).isPresent(); assertThat(resultHandlerFunction).contains(handlerFunction); } @Test void composedPathVariable() { HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build(); RequestPredicate requestPredicate = RequestPredicates.path("/{foo}").and( request -> request.pathVariable("foo").equals("bar")); RouterFunction<ServerResponse> routerFunction = RouterFunctions.route(requestPredicate, handlerFunction); MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/bar"); ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList()); Optional<HandlerFunction<ServerResponse>> resultHandlerFunction = routerFunction.route(request); assertThat(resultHandlerFunction).isPresent(); assertThat(resultHandlerFunction).contains(handlerFunction); } }
RouterFunctionsTests
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/MultipleInputs.java
{ "start": 2061, "end": 2916 }
class ____ use for this path */ @SuppressWarnings("unchecked") public static void addInputPath(Job job, Path path, Class<? extends InputFormat> inputFormatClass) { String inputFormatMapping = path.toString() + ";" + inputFormatClass.getName(); Configuration conf = job.getConfiguration(); String inputFormats = conf.get(DIR_FORMATS); conf.set(DIR_FORMATS, inputFormats == null ? inputFormatMapping : inputFormats + "," + inputFormatMapping); job.setInputFormatClass(DelegatingInputFormat.class); } /** * Add a {@link Path} with a custom {@link InputFormat} and * {@link Mapper} to the list of inputs for the map-reduce job. * * @param job The {@link Job} * @param path {@link Path} to be added to the list of inputs for the job * @param inputFormatClass {@link InputFormat}
to
java
apache__camel
core/camel-core-model/src/generated/java/org/apache/camel/model/cloud/CachingServiceCallServiceDiscoveryConfigurationConfigurer.java
{ "start": 739, "end": 4248 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("Id", java.lang.String.class); map.put("Properties", java.util.List.class); map.put("ServiceDiscoveryConfiguration", org.apache.camel.model.cloud.ServiceCallServiceDiscoveryConfiguration.class); map.put("Timeout", java.lang.String.class); map.put("Units", java.lang.String.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.model.cloud.CachingServiceCallServiceDiscoveryConfiguration target = (org.apache.camel.model.cloud.CachingServiceCallServiceDiscoveryConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "id": target.setId(property(camelContext, java.lang.String.class, value)); return true; case "properties": target.setProperties(property(camelContext, java.util.List.class, value)); return true; case "servicediscoveryconfiguration": case "serviceDiscoveryConfiguration": target.setServiceDiscoveryConfiguration(property(camelContext, org.apache.camel.model.cloud.ServiceCallServiceDiscoveryConfiguration.class, value)); return true; case "timeout": target.setTimeout(property(camelContext, java.lang.String.class, value)); return true; case "units": target.setUnits(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "id": return java.lang.String.class; case "properties": return java.util.List.class; case "servicediscoveryconfiguration": case "serviceDiscoveryConfiguration": return org.apache.camel.model.cloud.ServiceCallServiceDiscoveryConfiguration.class; case "timeout": return java.lang.String.class; case "units": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.model.cloud.CachingServiceCallServiceDiscoveryConfiguration target = (org.apache.camel.model.cloud.CachingServiceCallServiceDiscoveryConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "id": return target.getId(); case "properties": return target.getProperties(); case "servicediscoveryconfiguration": case "serviceDiscoveryConfiguration": return target.getServiceDiscoveryConfiguration(); case "timeout": return target.getTimeout(); case "units": return target.getUnits(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "properties": return org.apache.camel.model.PropertyDefinition.class; default: return null; } } }
CachingServiceCallServiceDiscoveryConfigurationConfigurer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/embeddable/JoinInheritanceSelectJoinTest.java
{ "start": 3233, "end": 3671 }
class ____ { @Id @GeneratedValue private Long id; private String name; @Embedded private Address address; public Human() { } public Human(String name, Address address) { this.name = name; this.address = address; } public Long getId() { return id; } public String getName() { return name; } public Address getAddress() { return address; } } @Entity(name = "Parent") public static
Human
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/StandardComparisonStrategy_areEqual_Test.java
{ "start": 1178, "end": 7976 }
class ____ { private final StandardComparisonStrategy underTest = StandardComparisonStrategy.instance(); @Test void should_return_true_if_both_actual_and_other_are_null() { // WHEN boolean result = underTest.areEqual(null, null); // THEN then(result).isTrue(); } @Test void should_return_false_if_actual_is_null_and_other_is_not() { // GIVEN Object other = new Object(); // WHEN boolean result = underTest.areEqual(null, other); // THEN then(result).isFalse(); } @Test void should_return_true_if_Object_arrays_are_equal() { // GIVEN Object[] actual = { "Luke", "Yoda", "Leia" }; Object[] other = { "Luke", "Yoda", "Leia" }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isTrue(); } @Test void should_return_false_if_Object_arrays_are_not_equal() { // GIVEN Object[] actual = { "Luke", "Leia", "Yoda" }; Object[] other = { "Luke", "Yoda", "Leia" }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isFalse(); } @Test void should_return_true_if_byte_arrays_are_equal() { // GIVEN byte[] actual = { 1, 2, 3 }; byte[] other = { 1, 2, 3 }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isTrue(); } @Test void should_return_false_if_byte_arrays_are_not_equal() { // GIVEN byte[] actual = { 1, 2, 3 }; byte[] other = { 4, 5, 6 }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isFalse(); } @Test void should_return_true_if_short_arrays_are_equal() { // GIVEN short[] actual = { 1, 2, 3 }; short[] other = { 1, 2, 3 }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isTrue(); } @Test void should_return_false_if_short_arrays_are_not_equal() { // GIVEN short[] actual = { 1, 2, 3 }; short[] other = { 4, 5, 6 }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isFalse(); } @Test void should_return_true_if_int_arrays_are_equal() { // GIVEN int[] actual = { 1, 2, 3 }; int[] other = { 1, 2, 3 }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isTrue(); } @Test void should_return_false_if_int_arrays_are_not_equal() { // GIVEN int[] actual = { 1, 2, 3 }; int[] other = { 4, 5, 6 }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isFalse(); } @Test void should_return_true_if_long_arrays_are_equal() { // GIVEN long[] actual = { 1L, 2L, 3L }; long[] other = { 1L, 2L, 3L }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isTrue(); } @Test void should_return_false_if_long_arrays_are_not_equal() { // GIVEN long[] actual = { 1L, 2L, 3L }; long[] other = { 4L, 5L, 6L }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isFalse(); } @Test void should_return_true_if_char_arrays_are_equal() { // GIVEN char[] actual = { '1', '2', '3' }; char[] other = { '1', '2', '3' }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isTrue(); } @Test void should_return_false_if_char_arrays_are_not_equal() { // GIVEN char[] actual = { '1', '2', '3' }; char[] other = { '4', '5', '6' }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isFalse(); } @Test void should_return_true_if_float_arrays_are_equal() { // GIVEN float[] actual = { 1.0f, 2.0f, 3.0f }; float[] other = { 1.0f, 2.0f, 3.0f }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isTrue(); } @Test void should_return_false_if_float_arrays_are_not_equal() { // GIVEN float[] actual = { 1.0f, 2.0f, 3.0f }; float[] other = { 4.0f, 5.0f, 6.0f }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isFalse(); } @Test void should_return_true_if_double_arrays_are_equal() { // GIVEN double[] actual = { 1.0, 2.0, 3.0 }; double[] other = { 1.0, 2.0, 3.0 }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isTrue(); } @Test void should_return_false_if_double_arrays_are_not_equal() { // GIVEN double[] actual = { 1.0, 2.0, 3.0 }; double[] other = { 4.0, 5.0, 6.0 }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isFalse(); } @Test void should_return_true_if_boolean_arrays_are_equal() { // GIVEN boolean[] actual = { true, false }; boolean[] other = { true, false }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isTrue(); } @Test void should_return_false_if_boolean_arrays_are_not_equal() { // GIVEN boolean[] actual = { true, false }; boolean[] other = { false, true }; // WHEN boolean result = underTest.areEqual(actual, other); // THEN then(result).isFalse(); } @ParameterizedTest @MethodSource("arrays") void should_return_false_if_array_is_non_null_and_other_is_null(Object actual) { // WHEN boolean result = underTest.areEqual(actual, null); // THEN then(result).isFalse(); } private static Stream<Object> arrays() { return Stream.of(argument(new Object[] { "Luke", "Yoda", "Leia" }), new byte[] { 1, 2, 3 }, new short[] { 1, 2, 3 }, new int[] { 1, 2, 3 }, new long[] { 1L, 2L, 3L }, new char[] { '1', '2', '3' }, new float[] { 1.0f, 2.0f, 3.0f }, new double[] { 1.0, 2.0, 3.0 }, new boolean[] { true, false }); } // Arrays of objects require additional wrapping to avoid expanding into individual elements. // See https://github.com/junit-team/junit5/issues/1665 and https://github.com/junit-team/junit5/issues/2708 private static Arguments argument(Object[] array) { return () -> new Object[] { array }; } @Test void should_fail_if_equals_implementation_fails() { // GIVEN Object actual = new EqualsThrowsException(); // WHEN Throwable thrown = catchThrowable(() -> underTest.areEqual(actual, new Object())); // THEN then(thrown).isInstanceOf(RuntimeException.class) .hasMessage("Boom!"); } private static
StandardComparisonStrategy_areEqual_Test
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/mapper/ParameterTests.java
{ "start": 560, "end": 1213 }
class ____ extends ESTestCase { public void test_ignore_above_param_default() { // when FieldMapper.Parameter<Integer> ignoreAbove = FieldMapper.Parameter.ignoreAboveParam((FieldMapper fm) -> 123, 456); // then assertEquals(456, ignoreAbove.getValue().intValue()); } public void test_ignore_above_param_invalid_value() { // when FieldMapper.Parameter<Integer> ignoreAbove = FieldMapper.Parameter.ignoreAboveParam((FieldMapper fm) -> -1, 456); ignoreAbove.setValue(-1); // then assertThrows(IllegalArgumentException.class, ignoreAbove::validate); } }
ParameterTests
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/SecondInputOfTwoInputStreamOperatorOutput.java
{ "start": 1640, "end": 4063 }
class ____ extends OutputBase { private final TwoInputStreamOperator<RowData, RowData, RowData> operator; public SecondInputOfTwoInputStreamOperatorOutput( TwoInputStreamOperator<RowData, RowData, RowData> operator) { super(operator); this.operator = operator; } @Override public void emitWatermark(Watermark mark) { try { operator.processWatermark2(mark); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } @Override public void emitWatermarkStatus(WatermarkStatus watermarkStatus) { try { operator.processWatermarkStatus2(watermarkStatus); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } @Override public void emitLatencyMarker(LatencyMarker latencyMarker) { try { operator.processLatencyMarker2(latencyMarker); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } @Override public void emitRecordAttributes(RecordAttributes recordAttributes) { try { operator.processRecordAttributes2(recordAttributes); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } @Override public void emitWatermark(WatermarkEvent watermark) { try { operator.processWatermark2(watermark); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } @Override public void collect(StreamRecord<RowData> record) { pushToOperator(record); } @Override public <X> void collect(OutputTag<X> outputTag, StreamRecord<X> record) { pushToOperator(record); } protected <X> void pushToOperator(StreamRecord<X> record) { try { // we know that the given outputTag matches our OutputTag so the record // must be of the type that our operator expects. @SuppressWarnings("unchecked") StreamRecord<RowData> castRecord = (StreamRecord<RowData>) record; operator.processElement2(castRecord); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } }
SecondInputOfTwoInputStreamOperatorOutput
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/admin/indices/segments/IndicesSegmentsRequestTests.java
{ "start": 990, "end": 4626 }
class ____ extends ESSingleNodeTestCase { @Override protected Collection<Class<? extends Plugin>> getPlugins() { return pluginList(InternalSettingsPlugin.class); } @Before public void setupIndex() { Settings settings = Settings.builder() // don't allow any merges so that the num docs is the expected segments .put(MergePolicyConfig.INDEX_MERGE_ENABLED, false) .build(); createIndex("test", settings); int numDocs = scaledRandomIntBetween(100, 1000); for (int j = 0; j < numDocs; ++j) { String id = Integer.toString(j); prepareIndex("test").setId(id).setSource("text", "sometext").get(); } client().admin().indices().prepareFlush("test").get(); client().admin().indices().prepareRefresh().get(); } /** * with the default IndicesOptions inherited from BroadcastOperationRequest this will raise an exception */ public void testRequestOnClosedIndex() { client().admin().indices().prepareClose("test").get(); try { client().admin().indices().prepareSegments("test").get(); fail("Expected IndexClosedException"); } catch (IndexClosedException e) { assertThat(e.getMessage(), is("closed")); } } /** * setting the "ignoreUnavailable" option prevents IndexClosedException */ public void testRequestOnClosedIndexIgnoreUnavailable() { client().admin().indices().prepareClose("test").get(); IndicesOptions defaultOptions = new IndicesSegmentsRequest().indicesOptions(); IndicesOptions testOptions = IndicesOptions.fromOptions(true, true, true, false, defaultOptions); IndicesSegmentResponse rsp = client().admin().indices().prepareSegments("test").setIndicesOptions(testOptions).get(); assertEquals(0, rsp.getIndices().size()); } /** * by default IndicesOptions setting IndicesSegmentsRequest should not throw exception when no index present */ public void testAllowNoIndex() { client().admin().indices().prepareDelete("test").get(); IndicesSegmentResponse rsp = client().admin().indices().prepareSegments().get(); assertEquals(0, rsp.getIndices().size()); } public void testRequestOnClosedIndexWithVectorFormats() { client().admin().indices().prepareClose("test").get(); try { client().admin().indices().prepareSegments("test").includeVectorFormatInfo(true).get(); fail("Expected IndexClosedException"); } catch (IndexClosedException e) { assertThat(e.getMessage(), is("closed")); } } public void testAllowNoIndexWithVectorFormats() { client().admin().indices().prepareDelete("test").get(); IndicesSegmentResponse rsp = client().admin().indices().prepareSegments().includeVectorFormatInfo(true).get(); assertEquals(0, rsp.getIndices().size()); } public void testRequestOnClosedIndexIgnoreUnavailableWithVectorFormats() { client().admin().indices().prepareClose("test").get(); IndicesOptions defaultOptions = new IndicesSegmentsRequest().indicesOptions(); IndicesOptions testOptions = IndicesOptions.fromOptions(true, true, true, false, defaultOptions); IndicesSegmentResponse rsp = client().admin() .indices() .prepareSegments("test") .includeVectorFormatInfo(true) .setIndicesOptions(testOptions) .get(); assertEquals(0, rsp.getIndices().size()); } }
IndicesSegmentsRequestTests
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/retriever/StandardRetrieverBuilderParsingTests.java
{ "start": 1962, "end": 9238 }
class ____ extends AbstractXContentTestCase<StandardRetrieverBuilder> { /** * Creates a random {@link StandardRetrieverBuilder}. The created instance * is not guaranteed to pass {@link SearchRequest} validation. This is purely * for x-content testing. */ public static StandardRetrieverBuilder createRandomStandardRetrieverBuilder( BiFunction<XContent, BytesReference, XContentParser> createParser ) { try { StandardRetrieverBuilder standardRetrieverBuilder = new StandardRetrieverBuilder(); if (randomBoolean()) { for (int i = 0; i < randomIntBetween(1, 3); ++i) { standardRetrieverBuilder.getPreFilterQueryBuilders().add(RandomQueryBuilder.createQuery(random())); } } if (randomBoolean()) { standardRetrieverBuilder.queryBuilder = RandomQueryBuilder.createQuery(random()); } if (randomBoolean()) { standardRetrieverBuilder.searchAfterBuilder = SearchAfterBuilderTests.randomJsonSearchFromBuilder(createParser); } if (randomBoolean()) { standardRetrieverBuilder.terminateAfter = randomNonNegativeInt(); } if (randomBoolean()) { standardRetrieverBuilder.sortBuilders = SortBuilderTests.randomSortBuilderList(false); } if (randomBoolean()) { standardRetrieverBuilder.collapseBuilder = CollapseBuilderTests.randomCollapseBuilder(randomBoolean()); } return standardRetrieverBuilder; } catch (IOException ioe) { throw new UncheckedIOException(ioe); } } @Override protected StandardRetrieverBuilder createTestInstance() { return createRandomStandardRetrieverBuilder((xContent, data) -> { try { return createParser(xContent, data); } catch (IOException ioe) { throw new UncheckedIOException(ioe); } }); } @Override protected StandardRetrieverBuilder doParseInstance(XContentParser parser) throws IOException { return (StandardRetrieverBuilder) RetrieverBuilder.parseTopLevelRetrieverBuilder( parser, new RetrieverParserContext(new SearchUsage(), Predicates.never()) ); } @Override protected boolean supportsUnknownFields() { return false; } @Override protected String[] getShuffleFieldsExceptions() { // disable xcontent shuffling on the highlight builder return new String[] { "fields" }; } @Override protected NamedXContentRegistry xContentRegistry() { return new NamedXContentRegistry(new SearchModule(Settings.EMPTY, List.of()).getNamedXContents()); } public void testRewrite() throws IOException { for (int i = 0; i < 10; i++) { StandardRetrieverBuilder standardRetriever = createTestInstance(); SearchSourceBuilder source = new SearchSourceBuilder().retriever(standardRetriever); QueryRewriteContext queryRewriteContext = mock(QueryRewriteContext.class); source = Rewriteable.rewrite(source, queryRewriteContext); assertNull(source.retriever()); assertTrue(source.knnSearch().isEmpty()); if (standardRetriever.queryBuilder != null) { assertNotNull(source.query()); if (standardRetriever.preFilterQueryBuilders.size() > 0) { if (source.query() instanceof MatchAllQueryBuilder == false && source.query() instanceof MatchNoneQueryBuilder == false) { assertThat(source.query(), instanceOf(BoolQueryBuilder.class)); BoolQueryBuilder bq = (BoolQueryBuilder) source.query(); assertFalse(bq.must().isEmpty()); assertThat(bq.must().size(), equalTo(1)); assertThat(bq.must().get(0), equalTo(standardRetriever.queryBuilder)); for (int j = 0; j < bq.filter().size(); j++) { assertEqualQueryOrMatchAllNone(bq.filter().get(j), standardRetriever.preFilterQueryBuilders.get(j)); } } } else { assertEqualQueryOrMatchAllNone(source.query(), standardRetriever.queryBuilder); } } else if (standardRetriever.preFilterQueryBuilders.size() > 0) { if (source.query() instanceof MatchAllQueryBuilder == false && source.query() instanceof MatchNoneQueryBuilder == false) { assertNotNull(source.query()); assertThat(source.query(), instanceOf(BoolQueryBuilder.class)); BoolQueryBuilder bq = (BoolQueryBuilder) source.query(); assertTrue(bq.must().isEmpty()); for (int j = 0; j < bq.filter().size(); j++) { assertEqualQueryOrMatchAllNone(bq.filter().get(j), standardRetriever.preFilterQueryBuilders.get(j)); } } } else { assertNull(source.query()); } if (standardRetriever.sortBuilders != null) { assertThat(source.sorts().size(), equalTo(standardRetriever.sortBuilders.size())); } } } public void testIsCompound() { StandardRetrieverBuilder standardRetriever = createTestInstance(); assertFalse(standardRetriever.isCompound()); } public void testTopDocsQuery() throws IOException { StandardRetrieverBuilder standardRetriever = createTestInstance(); final int preFilters = standardRetriever.preFilterQueryBuilders.size(); if (standardRetriever.queryBuilder == null) { if (preFilters > 0) { expectThrows(IllegalArgumentException.class, standardRetriever::topDocsQuery); } } else { QueryBuilder topDocsQuery = standardRetriever.topDocsQuery(); assertNotNull(topDocsQuery); if (preFilters > 0) { assertThat(topDocsQuery, instanceOf(BoolQueryBuilder.class)); assertThat(((BoolQueryBuilder) topDocsQuery).filter().size(), equalTo(1 + preFilters)); assertThat(((BoolQueryBuilder) topDocsQuery).filter().get(0), instanceOf(standardRetriever.queryBuilder.getClass())); for (int i = 0; i < preFilters; i++) { assertThat( ((BoolQueryBuilder) topDocsQuery).filter().get(i + 1), instanceOf(standardRetriever.preFilterQueryBuilders.get(i).getClass()) ); } } else { assertThat(topDocsQuery, instanceOf(standardRetriever.queryBuilder.getClass())); } } } private static void assertEqualQueryOrMatchAllNone(QueryBuilder actual, QueryBuilder expected) { assertThat(actual, anyOf(instanceOf(MatchAllQueryBuilder.class), instanceOf(MatchNoneQueryBuilder.class), equalTo(expected))); } }
StandardRetrieverBuilderParsingTests
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/TypeInferenceExtractorTest.java
{ "start": 88732, "end": 88942 }
class ____ extends ScalarFunction { @FunctionHint(output = @DataTypeHint("INT")) public Integer eval(Number n) { return null; } } private static
GlobalInputFunctionHints
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java
{ "start": 225814, "end": 227088 }
interface ____ { /** Returns a text rendering of the Option parameter or positional parameter; returns an empty string * {@code ""} if the option is a boolean and does not take a parameter. * @param field the annotated field with a parameter label * @param ansi determines whether ANSI escape codes should be emitted or not * @param styles the styles to apply to the parameter label * @return a text rendering of the Option parameter or positional parameter */ Text renderParameterLabel(Field field, Ansi ansi, List<IStyle> styles); /** Returns the separator between option name and param label. * @return the separator between option name and param label */ String separator(); } /** * DefaultParamLabelRenderer separates option parameters from their {@linkplain Option options} with a * {@linkplain DefaultParamLabelRenderer#separator separator} string, surrounds optional values * with {@code '['} and {@code ']'} characters and uses ellipses ("...") to indicate that any number of * values is allowed for options or parameters with variable arity. */ static
IParamLabelRenderer
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java
{ "start": 68779, "end": 69295 }
class ____ { @Bean @Scope(scopeName = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) public Repository<String> stringRepo() { return new Repository<>() { @Override public String toString() { return "Repository<String>"; } }; } @Bean @PrototypeScoped public Repository<Integer> integerRepo() { return new Repository<>() { @Override public String toString() { return "Repository<Integer>"; } }; } } public static
ScopedProxyRepositoryConfiguration
java
elastic__elasticsearch
test/fixtures/aws-fixture-utils/src/main/java/fixture/aws/DynamicAwsCredentials.java
{ "start": 1088, "end": 3716 }
class ____ { /** * Extra validation that requests are signed using the correct region. Lazy so it can be randomly generated after initialization, since * randomness is not available in static context. */ private final Supplier<String> expectedRegionSupplier; /** * Extra validation that requests are directed to the correct service. */ private final String expectedServiceName; /** * The set of access keys for each session token registered with {@link #addValidCredentials}. It's this way round because the session * token is a separate header so it's easier to extract. */ private final Map<String, Set<String>> validCredentialsMap = ConcurrentCollections.newConcurrentMap(); /** * @param expectedRegion The region to use for validating the authorization header, or {@code *} to skip this validation. * @param expectedServiceName The service name that should appear in the authorization header. */ public DynamicAwsCredentials(String expectedRegion, String expectedServiceName) { this(() -> expectedRegion, expectedServiceName); } /** * @param expectedRegionSupplier Supplies the region to use for validating the authorization header, or {@code *} to skip this * validation. * @param expectedServiceName The service name that should appear in the authorization header. */ public DynamicAwsCredentials(Supplier<String> expectedRegionSupplier, String expectedServiceName) { this.expectedRegionSupplier = expectedRegionSupplier; this.expectedServiceName = expectedServiceName; } public boolean isAuthorized(String authorizationHeader, String sessionTokenHeader) { return authorizationHeader != null && sessionTokenHeader != null && validCredentialsMap.getOrDefault(sessionTokenHeader, Set.of()) .stream() .anyMatch( validAccessKey -> AwsCredentialsUtils.isValidAwsV4SignedAuthorizationHeader( validAccessKey, expectedRegionSupplier.get(), expectedServiceName, authorizationHeader ) ); } public void addValidCredentials(String accessKey, String sessionToken) { validCredentialsMap.computeIfAbsent( Objects.requireNonNull(sessionToken, "sessionToken"), t -> ConcurrentCollections.newConcurrentSet() ).add(Objects.requireNonNull(accessKey, "accessKey")); } }
DynamicAwsCredentials
java
apache__flink
flink-clients/src/main/java/org/apache/flink/client/cli/CliArgsException.java
{ "start": 929, "end": 1206 }
class ____ extends Exception { private static final long serialVersionUID = 1L; public CliArgsException(String message) { super(message); } public CliArgsException(String message, Throwable cause) { super(message, cause); } }
CliArgsException
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/MultipartOutputUsingBlockingEndpointsTest.java
{ "start": 720, "end": 9240 }
class ____ extends AbstractMultipartTest { private static final String EXPECTED_CONTENT_DISPOSITION_PART = "Content-Disposition: form-data; name=\"%s\""; private static final String EXPECTED_CONTENT_DISPOSITION_FILE_PART = "Content-Disposition: form-data; name=\"%s\"; filename=\"%s\""; private static final String EXPECTED_CONTENT_TYPE_PART = "Content-Type: %s"; @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) .addClasses(MultipartOutputResource.class, MultipartOutputResponse.class, MultipartOutputFileResponse.class, MultipartOutputMultipleFileResponse.class, MultipartOutputMultipleFileDownloadResponse.class, MultipartOutputSingleFileDownloadResponse.class, Status.class, FormDataBase.class, OtherPackageFormDataBase.class, PathFileDownload.class)); @Test public void testSimple() { String response = RestAssured.get("/multipart/output/simple") .then() .contentType(ContentType.MULTIPART) .statusCode(200) .extract().asString(); assertContainsValue(response, "name", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_NAME); assertContainsValue(response, "custom-surname", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_SURNAME); assertContainsValue(response, "custom-status", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_STATUS); assertContainsValue(response, "active", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_ACTIVE); assertContainsValue(response, "values", MediaType.TEXT_PLAIN, "[one, two]"); assertContainsValue(response, "num", MediaType.TEXT_PLAIN, "0"); } @Test public void testRestResponse() { String response = RestAssured.get("/multipart/output/rest-response") .then() .contentType(ContentType.MULTIPART) .statusCode(200) .header("foo", "bar") .extract().asString(); assertContainsValue(response, "name", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_NAME); assertContainsValue(response, "custom-surname", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_SURNAME); assertContainsValue(response, "custom-status", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_STATUS); assertContainsValue(response, "active", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_ACTIVE); assertContainsValue(response, "values", MediaType.TEXT_PLAIN, "[one, two]"); assertContainsValue(response, "num", MediaType.TEXT_PLAIN, "0"); } @Test public void testWithFormData() { ExtractableResponse<?> extractable = RestAssured.get("/multipart/output/with-form-data") .then() .contentType(ContentType.MULTIPART) .statusCode(200) .extract(); String body = extractable.asString(); assertContainsValue(body, "name", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_NAME); assertContainsValue(body, "part-with-filename", MediaType.TEXT_PLAIN, "filename=\"file.txt\""); assertContainsValue(body, "part-with-filename", MediaType.TEXT_PLAIN, "filename=\"file2.txt\"", "extra-header: extra-value"); assertContainsValue(body, "custom-surname", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_SURNAME); assertContainsValue(body, "custom-status", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_STATUS, "extra-header: extra-value"); assertContainsValue(body, "active", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_ACTIVE, "extra-header: extra-value"); assertContainsValue(body, "values", MediaType.TEXT_PLAIN, "[one, two]"); assertThat(extractable.header("Content-Type")).contains("boundary="); } @Test public void testString() { RestAssured.get("/multipart/output/string") .then() .statusCode(200) .body(equalTo(MultipartOutputResource.RESPONSE_NAME)); } @Test public void testWithFile() { String response = RestAssured .given() .get("/multipart/output/with-file") .then() .contentType(ContentType.MULTIPART) .statusCode(200) .extract().asString(); assertContainsValue(response, "name", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_NAME); assertContainsFile(response, "file", MediaType.APPLICATION_OCTET_STREAM, "lorem.txt"); } @Test public void testWithSingleFileDownload() { String response = RestAssured .given() .get("/multipart/output/with-single-file-download") .then() .contentType(ContentType.MULTIPART) .statusCode(200) .extract().asString(); assertContainsFile(response, "one", MediaType.APPLICATION_OCTET_STREAM, "test.xml"); } @Test public void testWithMultipleFiles() { String response = RestAssured .given() .get("/multipart/output/with-multiple-file") .then() .contentType(ContentType.MULTIPART) .statusCode(200) .extract().asString(); assertContainsValue(response, "name", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_NAME); assertContainsFile(response, "files", MediaType.APPLICATION_OCTET_STREAM, "lorem.txt"); assertContainsFile(response, "files", MediaType.APPLICATION_OCTET_STREAM, "test.xml"); } @Test public void testWithMultipleFileDownload() { String response = RestAssured .given() .get("/multipart/output/with-multiple-file-download") .then() .contentType(ContentType.MULTIPART) .statusCode(200) .extract().asString(); assertContainsValue(response, "name", MediaType.TEXT_PLAIN, MultipartOutputResource.RESPONSE_NAME); assertContainsFile(response, "files", MediaType.APPLICATION_OCTET_STREAM, "lorem.txt"); assertContainsFile(response, "files", MediaType.APPLICATION_OCTET_STREAM, "test.xml"); } @EnabledIfSystemProperty(named = "test-resteasy-reactive-large-files", matches = "true") @Test public void testWithLargeFiles() { RestAssured.given() .get("/multipart/output/with-large-file") .then() .contentType(ContentType.MULTIPART) .statusCode(200); } @Test public void testWithNullFields() { RestAssured .given() .get("/multipart/output/with-null-fields") .then() .contentType(ContentType.MULTIPART) .log().all() .statusCode(200); // should return 200 with no parts } private void assertContainsFile(String response, String name, String contentType, String fileName) { String[] lines = response.split("--"); assertThat(lines).anyMatch(line -> line.contains(String.format(EXPECTED_CONTENT_DISPOSITION_FILE_PART, name, fileName)) && line.contains(String.format(EXPECTED_CONTENT_TYPE_PART, contentType))); } private void assertContainsValue(String response, String name, String contentType, Object value) { String[] lines = response.split("--"); assertThat(lines).anyMatch(line -> line.contains(String.format(EXPECTED_CONTENT_DISPOSITION_PART, name)) && line.contains(String.format(EXPECTED_CONTENT_TYPE_PART, contentType)) && line.contains(value.toString())); } private void assertContainsValue(String response, String name, String contentType, Object value, String header) { String[] lines = response.split("--"); assertThat(lines).anyMatch(line -> line.contains(String.format(EXPECTED_CONTENT_DISPOSITION_PART, name)) && line.contains(String.format(EXPECTED_CONTENT_TYPE_PART, contentType)) && line.contains(value.toString()) && line.contains(header)); } }
MultipartOutputUsingBlockingEndpointsTest
java
apache__camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindyPojoSimpleCsvMarshallTest.java
{ "start": 3240, "end": 3860 }
class ____ extends RouteBuilder { @Override public void configure() { BindyCsvDataFormat camelDataFormat = new BindyCsvDataFormat(org.apache.camel.dataformat.bindy.model.simple.oneclass.Order.class); camelDataFormat.setLocale("en"); // default should errors go to mock:error errorHandler(deadLetterChannel(URI_MOCK_ERROR).redeliveryDelay(0)); onException(Exception.class).maximumRedeliveries(0).handled(true); from(URI_DIRECT_START).marshal(camelDataFormat).to(URI_MOCK_RESULT); } } }
ContextConfig
java
grpc__grpc-java
testing/src/main/java/io/grpc/testing/TestMethodDescriptors.java
{ "start": 1806, "end": 2081 }
class ____ implements MethodDescriptor.Marshaller<Void> { @Override public InputStream stream(Void value) { return new ByteArrayInputStream(new byte[]{}); } @Override public Void parse(InputStream stream) { return null; } } }
NoopMarshaller
java
quarkusio__quarkus
extensions/mailer/deployment/src/test/java/io/quarkus/mailer/NamedMailersInjectionTest.java
{ "start": 6559, "end": 6800 }
class ____ { @Inject @MailerName("client2") MailClient client; void verify() { Assertions.assertNotNull(client); } } @ApplicationScoped static
BeanUsingBareMailClientNamedClient2
java
quarkusio__quarkus
extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/logs/OpenTelemetryLogRecorder.java
{ "start": 378, "end": 1217 }
class ____ { private final RuntimeValue<OTelRuntimeConfig> runtimeConfig; public OpenTelemetryLogRecorder(final RuntimeValue<OTelRuntimeConfig> runtimeConfig) { this.runtimeConfig = runtimeConfig; } public RuntimeValue<Optional<Handler>> initializeHandler(final BeanContainer beanContainer) { if (runtimeConfig.getValue().sdkDisabled() || !runtimeConfig.getValue().logs().handlerEnabled()) { return new RuntimeValue<>(Optional.empty()); } final OpenTelemetry openTelemetry = beanContainer.beanInstance(OpenTelemetry.class); final OpenTelemetryLogHandler logHandler = new OpenTelemetryLogHandler(openTelemetry); logHandler.setLevel(runtimeConfig.getValue().logs().level()); return new RuntimeValue<>(Optional.of(logHandler)); } }
OpenTelemetryLogRecorder
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/batch/OtherEntity.java
{ "start": 209, "end": 457 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq2") public Long id; public OtherEntity() { } @Override public String toString() { return "OtherEntity#" + id; } }
OtherEntity
java
quarkusio__quarkus
extensions/reactive-mssql-client/runtime/src/main/java/io/quarkus/reactive/mssql/client/runtime/DataSourcesReactiveMSSQLConfig.java
{ "start": 658, "end": 999 }
interface ____ { /** * Datasources. */ @ConfigDocSection @ConfigDocMapKey("datasource-name") @WithParentName @WithDefaults @WithUnnamedKey(DataSourceUtil.DEFAULT_DATASOURCE_NAME) Map<String, DataSourceReactiveMSSQLOuterNamedConfig> dataSources(); @ConfigGroup public
DataSourcesReactiveMSSQLConfig
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/Assert.java
{ "start": 2490, "end": 6564 }
class ____ { /** * Assert a boolean expression, throwing an {@code IllegalStateException} * if the expression evaluates to {@code false}. * <p>Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException} * on an assertion failure. * <pre class="code">Assert.state(id == null, "The id property must not already be initialized");</pre> * @param expression a boolean expression * @param message the exception message to use if the assertion fails * @throws IllegalStateException if {@code expression} is {@code false} */ @Contract("false, _ -> fail") public static void state(boolean expression, String message) { if (!expression) { throw new IllegalStateException(message); } } /** * Assert a boolean expression, throwing an {@code IllegalStateException} * if the expression evaluates to {@code false}. * <p>Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException} * on an assertion failure. * <pre class="code"> * Assert.state(entity.getId() == null, * () -&gt; "ID for entity " + entity.getName() + " must not already be initialized"); * </pre> * @param expression a boolean expression * @param messageSupplier a supplier for the exception message to use if the * assertion fails * @throws IllegalStateException if {@code expression} is {@code false} * @since 5.0 */ @Contract("false, _ -> fail") public static void state(boolean expression, Supplier<String> messageSupplier) { if (!expression) { throw new IllegalStateException(nullSafeGet(messageSupplier)); } } /** * Assert a boolean expression, throwing an {@code IllegalArgumentException} * if the expression evaluates to {@code false}. * <pre class="code">Assert.isTrue(i &gt; 0, "The value must be greater than zero");</pre> * @param expression a boolean expression * @param message the exception message to use if the assertion fails * @throws IllegalArgumentException if {@code expression} is {@code false} */ @Contract("false, _ -> fail") public static void isTrue(boolean expression, String message) { if (!expression) { throw new IllegalArgumentException(message); } } /** * Assert a boolean expression, throwing an {@code IllegalArgumentException} * if the expression evaluates to {@code false}. * <pre class="code"> * Assert.isTrue(i &gt; 0, () -&gt; "The value '" + i + "' must be greater than zero"); * </pre> * @param expression a boolean expression * @param messageSupplier a supplier for the exception message to use if the * assertion fails * @throws IllegalArgumentException if {@code expression} is {@code false} * @since 5.0 */ @Contract("false, _ -> fail") public static void isTrue(boolean expression, Supplier<String> messageSupplier) { if (!expression) { throw new IllegalArgumentException(nullSafeGet(messageSupplier)); } } /** * Assert that an object is {@code null}. * <pre class="code">Assert.isNull(value, "The value must be null");</pre> * @param object the object to check * @param message the exception message to use if the assertion fails * @throws IllegalArgumentException if the object is not {@code null} */ @Contract("!null, _ -> fail") public static void isNull(@Nullable Object object, String message) { if (object != null) { throw new IllegalArgumentException(message); } } /** * Assert that an object is {@code null}. * <pre class="code"> * Assert.isNull(value, () -&gt; "The value '" + value + "' must be null"); * </pre> * @param object the object to check * @param messageSupplier a supplier for the exception message to use if the * assertion fails * @throws IllegalArgumentException if the object is not {@code null} * @since 5.0 */ @Contract("!null, _ -> fail") public static void isNull(@Nullable Object object, Supplier<String> messageSupplier) { if (object != null) { throw new IllegalArgumentException(nullSafeGet(messageSupplier)); } } /** * Assert that an object is not {@code null}. * <pre class="code">Assert.notNull(clazz, "The
Assert
java
google__dagger
hilt-android/main/java/dagger/hilt/android/internal/lifecycle/HiltViewModelFactory.java
{ "start": 2255, "end": 2805 }
class ____ to user defined @AssistedFactory-annotated implementations. @HiltViewModelAssistedMap Map<Class<?>, Object> getHiltViewModelAssistedMap(); } /** Creation extra key for the callbacks that create @AssistedInject-annotated ViewModels. */ public static final CreationExtras.Key<Function1<Object, ViewModel>> CREATION_CALLBACK_KEY = new CreationExtras.Key<Function1<Object, ViewModel>>() {}; /** Hilt module for providing the empty multi-binding map of ViewModels. */ @Module @InstallIn(ViewModelComponent.class)
names
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/sort/BucketedSort.java
{ "start": 25435, "end": 27244 }
class ____ extends BucketedSort { private IntArray values; @SuppressWarnings("this-escape") public ForInts(BigArrays bigArrays, SortOrder sortOrder, DocValueFormat format, int bucketSize, ExtraData extra) { super(bigArrays, sortOrder, format, bucketSize, extra); boolean success = false; try { values = bigArrays.newIntArray(1, false); success = true; } finally { if (success == false) { close(); } } initGatherOffsets(); } @Override public final boolean needsScores() { return false; } @Override protected final BigArray values() { return values; } @Override protected final void growValues(long minSize) { values = bigArrays.grow(values, minSize); } @Override protected final int getNextGatherOffset(long rootIndex) { return values.get(rootIndex); } @Override protected final void setNextGatherOffset(long rootIndex, int offset) { values.set(rootIndex, offset); } @Override protected final SortValue getValue(long index) { return SortValue.from(values.get(index)); } @Override protected final boolean betterThan(long lhs, long rhs) { return getOrder().reverseMul() * Integer.compare(values.get(lhs), values.get(rhs)) < 0; } @Override protected final void swap(long lhs, long rhs) { int tmp = values.get(lhs); values.set(lhs, values.get(rhs)); values.set(rhs, tmp); } protected abstract
ForInts
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/observer/injectionpoint/ObserverInjectingDependentSyntheticBeanWithMetadataTest.java
{ "start": 921, "end": 1259 }
class ____ { void onStart(@Observes StartupEvent event, MyConfig config) { // A @Dependent synthetic bean is registered for MyConfig, and it attempts to obtain InjectionPoint in its create() method assertEquals(42, config.value1()); assertEquals("baz", config.value2()); } } }
MyBean
java
quarkusio__quarkus
extensions/micrometer/deployment/src/main/java/io/quarkus/micrometer/deployment/binder/ReactiveMessagingProcessor.java
{ "start": 331, "end": 787 }
class ____ { static final String MESSAGE_OBSERVATION_COLLECTOR = "io.smallrye.reactive.messaging.observation.MessageObservationCollector"; static final String METRICS_BEAN_CLASS = "io.quarkus.micrometer.runtime.binder.reactivemessaging.MicrometerObservationCollector"; static final Class<?> MESSAGE_OBSERVATION_COLLECTOR_CLASS = MicrometerRecorder .getClassForName(MESSAGE_OBSERVATION_COLLECTOR); static
ReactiveMessagingProcessor
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/ClusterImplLoadBalancerProvider.java
{ "start": 2717, "end": 4998 }
class ____ { // Name of the cluster. final String cluster; // Resource name used in discovering endpoints via EDS. Only valid for EDS clusters. @Nullable final String edsServiceName; // Load report server info. Null if load reporting is disabled. @Nullable final ServerInfo lrsServerInfo; // Cluster-level max concurrent request threshold. Null if not specified. @Nullable final Long maxConcurrentRequests; // TLS context for connections to endpoints. @Nullable final UpstreamTlsContext tlsContext; // Drop configurations. final List<DropOverload> dropCategories; // Provides the direct child policy and its config. final Object childConfig; final Map<String, Struct> filterMetadata; @Nullable final BackendMetricPropagation backendMetricPropagation; ClusterImplConfig(String cluster, @Nullable String edsServiceName, @Nullable ServerInfo lrsServerInfo, @Nullable Long maxConcurrentRequests, List<DropOverload> dropCategories, Object childConfig, @Nullable UpstreamTlsContext tlsContext, Map<String, Struct> filterMetadata, @Nullable BackendMetricPropagation backendMetricPropagation) { this.cluster = checkNotNull(cluster, "cluster"); this.edsServiceName = edsServiceName; this.lrsServerInfo = lrsServerInfo; this.maxConcurrentRequests = maxConcurrentRequests; this.tlsContext = tlsContext; this.filterMetadata = ImmutableMap.copyOf(filterMetadata); this.dropCategories = Collections.unmodifiableList( new ArrayList<>(checkNotNull(dropCategories, "dropCategories"))); this.childConfig = checkNotNull(childConfig, "childConfig"); this.backendMetricPropagation = backendMetricPropagation; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("cluster", cluster) .add("edsServiceName", edsServiceName) .add("lrsServerInfo", lrsServerInfo) .add("maxConcurrentRequests", maxConcurrentRequests) // Exclude tlsContext as its string representation is cumbersome. .add("dropCategories", dropCategories) .add("childConfig", childConfig) .toString(); } } }
ClusterImplConfig
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/progress/MockingProgressImplTest.java
{ "start": 936, "end": 3790 }
class ____ extends TestBase { private MockingProgress mockingProgress; @Before public void setup() { mockingProgress = new MockingProgressImpl(); } @Test public void shouldStartVerificationAndPullVerificationMode() throws Exception { assertNull(mockingProgress.pullVerificationMode()); VerificationMode mode = VerificationModeFactory.times(19); mockingProgress.verificationStarted(mode); assertSame(mode, mockingProgress.pullVerificationMode()); assertNull(mockingProgress.pullVerificationMode()); } @Test public void shouldCheckIfVerificationWasFinished() throws Exception { mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce()); try { mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce()); fail(); } catch (MockitoException e) { } } @Test public void shouldNotifyListenerSafely() throws Exception { // when mockingProgress.addListener(null); // then no exception is thrown: mockingProgress.mockingStarted(null, null); } @Test public void should_not_allow_redundant_listeners() { MockitoListener listener1 = mock(MockitoListener.class); final MockitoListener listener2 = mock(MockitoListener.class); final Set<MockitoListener> listeners = new LinkedHashSet<MockitoListener>(); // when MockingProgressImpl.addListener(listener1, listeners); // then Assertions.assertThatThrownBy( new ThrowableAssert.ThrowingCallable() { public void call() { MockingProgressImpl.addListener(listener2, listeners); } }) .isInstanceOf(RedundantListenerException.class); } @Test public void should_clean_up_listeners_automatically() { MockitoListener someListener = mock(MockitoListener.class); MyListener cleanListener = mock(MyListener.class); MyListener dirtyListener = when(mock(MyListener.class).isListenerDirty()).thenReturn(true).getMock(); Set<MockitoListener> listeners = new LinkedHashSet<MockitoListener>(); // when MockingProgressImpl.addListener(someListener, listeners); MockingProgressImpl.addListener(dirtyListener, listeners); // then Assertions.assertThat(listeners).containsExactlyInAnyOrder(someListener, dirtyListener); // when MockingProgressImpl.addListener(cleanListener, listeners); // then dirty listener was removed automatically Assertions.assertThat(listeners).containsExactlyInAnyOrder(someListener, cleanListener); }
MockingProgressImplTest
java
google__dagger
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
{ "start": 90009, "end": 92717 }
interface ____ {", " @Provides static @Named(\"1\") String provide1() { return null; }", " @Provides static @Named(\"2\") String provide2() { return null; }", " @Provides static @Named(\"3\") String provide3() { return null; }", " @Provides static @Named(\"4\") String provide4() { return null; }", " @Provides static @Named(\"5\") String provide5() { return null; }", " @Provides static @Named(\"6\") String provide6() { return null; }", " @Provides static @Named(\"7\") String provide7() { return null; }", " @Provides static @Named(\"8\") String provide8() { return null; }", " @Provides static @Named(\"9\") String provide9() { return null; }", " @Provides static @Named(\"10\") String provide10() { return null; }", " @Provides static @Named(\"11\") String provide11() { return null; }", " @Provides static @Named(\"12\") String provide12() { return null; }", " @Provides static @Named(\"13\") String provide13() { return null; }", " @Provides static @Named(\"14\") String provide14() { return null; }", " @Provides static @Named(\"15\") String provide15() { return null; }", " @Provides static @Named(\"16\") String provide16() { return null; }", " @Provides static @Named(\"17\") String provide17() { return null; }", " @Provides static @Named(\"18\") String provide18() { return null; }", " @Provides static @Named(\"19\") String provide19() { return null; }", " @Provides static @Named(\"20\") String provide20() { return null; }", " @Provides static @Named(\"21\") String provide21() { return null; }", " @Provides static @Named(\"22\") String provide22() { return null; }", " @Provides static @Named(\"23\") String provide23() { return null; }", " @Provides static @Named(\"24\") String provide24() { return null; }", " @Provides static @Named(\"25\") String provide25() { return null; }", " @Provides static @Named(\"26\") String provide26() { return null; }", " @Provides static @Named(\"27\") String provide27() { return null; }", " @Provides static @Named(\"28\") String provide28() { return null; }", " @Provides static @Named(\"29\") String provide29() { return null; }", " @Provides static @Named(\"30\") String provide30() { return null; }", "}"); Source foo = CompilerTests.javaSource( "test.Foo", "package test;", "", "
TestModule
java
apache__spark
common/network-common/src/main/java/org/apache/spark/network/crypto/TransportCipherUtil.java
{ "start": 1116, "end": 1517 }
class ____ { /** * This method is used for testing to verify key derivation. */ @VisibleForTesting static String getKeyId(SecretKeySpec key) throws GeneralSecurityException { byte[] keyIdBytes = Hkdf.computeHkdf("HmacSha256", key.getEncoded(), null, "keyID".getBytes(StandardCharsets.UTF_8), 32); return Hex.encode(keyIdBytes); } }
TransportCipherUtil
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcInsert.java
{ "start": 2135, "end": 2320 }
class ____ the processing arrangement for {@link SimpleJdbcInsert}. * * @author Thomas Risberg * @author Juergen Hoeller * @author Sam Brannen * @since 2.5 */ public abstract
provides
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/configuration/Engine.java
{ "start": 653, "end": 971 }
class ____ { private final String manufacturer; public Engine(String manufacturer) { this.manufacturer = manufacturer; } public String getManufacturer() { return manufacturer; } public static Builder builder() { return new Builder(); } public static final
Engine
java
hibernate__hibernate-orm
hibernate-spatial/src/test/java/org/hibernate/spatial/dialect/oracle/hhh15669/TestStWithinBug.java
{ "start": 1695, "end": 2705 }
class ____ extends SpatialSessionFactoryAware { Polygon<G2D> filter = polygon( WGS84, ring( g( 0, 0 ), g( 10, 0 ), g( 10, 10 ), g( 0, 10 ), g( 0, 0 ) ) ); @BeforeEach public void before() { scope.inTransaction( session -> { session.persist( new Foo( 1, point( WGS84, g( 5, 5 ) ) ) ); session.persist( new Foo( 2, point( WGS84, g( 12, 12 ) ) ) ); session.persist( new Foo( 3, point( WGS84, g( -1, -1 ) ) ) ); } ); } @Test public void testHql() { scope.inTransaction( session -> { List<Foo> list = session .createQuery( "from Foo where st_within(point, :filter) = true", Foo.class ) .setParameter( "filter", filter ) .getResultList(); assertThat( list, hasSize( 1 ) ); assertThat( list.get( 0 ).id, equalTo( 1L ) ); } ); } @AfterEach public void cleanup() { scope.inTransaction( session -> session.createMutationQuery( "delete from Foo" ) .executeUpdate() ); } } @Entity(name = "Foo") @Table(name = "Foo")
TestStWithinBug
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DebeziumPostgresEndpointBuilderFactory.java
{ "start": 134806, "end": 135173 }
class ____ extends AbstractEndpointBuilder implements DebeziumPostgresEndpointBuilder, AdvancedDebeziumPostgresEndpointBuilder { public DebeziumPostgresEndpointBuilderImpl(String path) { super(componentName, path); } } return new DebeziumPostgresEndpointBuilderImpl(path); } }
DebeziumPostgresEndpointBuilderImpl
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/VectoredReadUtils.java
{ "start": 1600, "end": 1772 }
class ____ implements helper methods used * in vectored IO implementation. */ @InterfaceAudience.LimitedPrivate("Filesystems") @InterfaceStability.Unstable public final
which
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/MinIntAggregatorFunction.java
{ "start": 995, "end": 6235 }
class ____ implements AggregatorFunction { private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of( new IntermediateStateDesc("min", ElementType.INT), new IntermediateStateDesc("seen", ElementType.BOOLEAN) ); private final DriverContext driverContext; private final IntState state; private final List<Integer> channels; public MinIntAggregatorFunction(DriverContext driverContext, List<Integer> channels, IntState state) { this.driverContext = driverContext; this.channels = channels; this.state = state; } public static MinIntAggregatorFunction create(DriverContext driverContext, List<Integer> channels) { return new MinIntAggregatorFunction(driverContext, channels, new IntState(MinIntAggregator.init())); } public static List<IntermediateStateDesc> intermediateStateDesc() { return INTERMEDIATE_STATE_DESC; } @Override public int intermediateBlockCount() { return INTERMEDIATE_STATE_DESC.size(); } @Override public void addRawInput(Page page, BooleanVector mask) { if (mask.allFalse()) { // Entire page masked away } else if (mask.allTrue()) { addRawInputNotMasked(page); } else { addRawInputMasked(page, mask); } } private void addRawInputMasked(Page page, BooleanVector mask) { IntBlock vBlock = page.getBlock(channels.get(0)); IntVector vVector = vBlock.asVector(); if (vVector == null) { addRawBlock(vBlock, mask); return; } addRawVector(vVector, mask); } private void addRawInputNotMasked(Page page) { IntBlock vBlock = page.getBlock(channels.get(0)); IntVector vVector = vBlock.asVector(); if (vVector == null) { addRawBlock(vBlock); return; } addRawVector(vVector); } private void addRawVector(IntVector vVector) { state.seen(true); for (int valuesPosition = 0; valuesPosition < vVector.getPositionCount(); valuesPosition++) { int vValue = vVector.getInt(valuesPosition); state.intValue(MinIntAggregator.combine(state.intValue(), vValue)); } } private void addRawVector(IntVector vVector, BooleanVector mask) { state.seen(true); for (int valuesPosition = 0; valuesPosition < vVector.getPositionCount(); valuesPosition++) { if (mask.getBoolean(valuesPosition) == false) { continue; } int vValue = vVector.getInt(valuesPosition); state.intValue(MinIntAggregator.combine(state.intValue(), vValue)); } } private void addRawBlock(IntBlock vBlock) { for (int p = 0; p < vBlock.getPositionCount(); p++) { int vValueCount = vBlock.getValueCount(p); if (vValueCount == 0) { continue; } state.seen(true); int vStart = vBlock.getFirstValueIndex(p); int vEnd = vStart + vValueCount; for (int vOffset = vStart; vOffset < vEnd; vOffset++) { int vValue = vBlock.getInt(vOffset); state.intValue(MinIntAggregator.combine(state.intValue(), vValue)); } } } private void addRawBlock(IntBlock vBlock, BooleanVector mask) { for (int p = 0; p < vBlock.getPositionCount(); p++) { if (mask.getBoolean(p) == false) { continue; } int vValueCount = vBlock.getValueCount(p); if (vValueCount == 0) { continue; } state.seen(true); int vStart = vBlock.getFirstValueIndex(p); int vEnd = vStart + vValueCount; for (int vOffset = vStart; vOffset < vEnd; vOffset++) { int vValue = vBlock.getInt(vOffset); state.intValue(MinIntAggregator.combine(state.intValue(), vValue)); } } } @Override public void addIntermediateInput(Page page) { assert channels.size() == intermediateBlockCount(); assert page.getBlockCount() >= channels.get(0) + intermediateStateDesc().size(); Block minUncast = page.getBlock(channels.get(0)); if (minUncast.areAllValuesNull()) { return; } IntVector min = ((IntBlock) minUncast).asVector(); assert min.getPositionCount() == 1; Block seenUncast = page.getBlock(channels.get(1)); if (seenUncast.areAllValuesNull()) { return; } BooleanVector seen = ((BooleanBlock) seenUncast).asVector(); assert seen.getPositionCount() == 1; if (seen.getBoolean(0)) { state.intValue(MinIntAggregator.combine(state.intValue(), min.getInt(0))); state.seen(true); } } @Override public void evaluateIntermediate(Block[] blocks, int offset, DriverContext driverContext) { state.toIntermediate(blocks, offset, driverContext); } @Override public void evaluateFinal(Block[] blocks, int offset, DriverContext driverContext) { if (state.seen() == false) { blocks[offset] = driverContext.blockFactory().newConstantNullBlock(1); return; } blocks[offset] = driverContext.blockFactory().newConstantIntBlockWith(state.intValue(), 1); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("["); sb.append("channels=").append(channels); sb.append("]"); return sb.toString(); } @Override public void close() { state.close(); } }
MinIntAggregatorFunction
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/project/DefaultMavenProjectHelper.java
{ "start": 1399, "end": 4448 }
class ____ extends AbstractLogEnabled implements MavenProjectHelper { private final ArtifactHandlerManager artifactHandlerManager; @Inject public DefaultMavenProjectHelper(ArtifactHandlerManager artifactHandlerManager) { this.artifactHandlerManager = artifactHandlerManager; } @Override public void attachArtifact( MavenProject project, String artifactType, String artifactClassifier, File artifactFile) { ArtifactHandler handler = null; if (artifactType != null) { handler = artifactHandlerManager.getArtifactHandler(artifactType); } if (handler == null) { handler = artifactHandlerManager.getArtifactHandler("jar"); } Artifact artifact = new AttachedArtifact(project.getArtifact(), artifactType, artifactClassifier, handler); artifact.setFile(artifactFile); artifact.setResolved(true); attachArtifact(project, artifact); } @Override public void attachArtifact(MavenProject project, String artifactType, File artifactFile) { ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(artifactType); Artifact artifact = new AttachedArtifact(project.getArtifact(), artifactType, handler); artifact.setFile(artifactFile); artifact.setResolved(true); attachArtifact(project, artifact); } @Override public void attachArtifact(MavenProject project, File artifactFile, String artifactClassifier) { Artifact projectArtifact = project.getArtifact(); Artifact artifact = new AttachedArtifact( projectArtifact, projectArtifact.getType(), artifactClassifier, projectArtifact.getArtifactHandler()); artifact.setFile(artifactFile); artifact.setResolved(true); attachArtifact(project, artifact); } /** * Add an attached artifact or replace the file for an existing artifact. * * @see MavenProject#addAttachedArtifact(org.apache.maven.artifact.Artifact) * @param project project reference. * @param artifact artifact to add or replace. */ public void attachArtifact(MavenProject project, Artifact artifact) { project.addAttachedArtifact(artifact); } @Override public void addResource( MavenProject project, String resourceDirectory, List<String> includes, List<String> excludes) { Resource resource = new Resource(); resource.setDirectory(resourceDirectory); resource.setIncludes(includes); resource.setExcludes(excludes); project.addResource(resource); } @Override public void addTestResource( MavenProject project, String resourceDirectory, List<String> includes, List<String> excludes) { Resource resource = new Resource(); resource.setDirectory(resourceDirectory); resource.setIncludes(includes); resource.setExcludes(excludes); project.addTestResource(resource); } }
DefaultMavenProjectHelper
java
mapstruct__mapstruct
processor/src/test/resources/fixtures/org/mapstruct/ap/test/nestedbeans/UserDtoUpdateMapperSmartImpl.java
{ "start": 3766, "end": 4935 }
enum ____: " + roofType ); } return externalRoofType; } protected void roofToRoofDto(Roof roof, RoofDto mappingTarget) { if ( roof == null ) { return; } mappingTarget.setColor( String.valueOf( roof.getColor() ) ); if ( roof.getType() != null ) { mappingTarget.setType( roofTypeToExternalRoofType( roof.getType() ) ); } else { mappingTarget.setType( null ); } } protected void houseToHouseDto(House house, HouseDto mappingTarget) { if ( house == null ) { return; } if ( house.getName() != null ) { mappingTarget.setName( house.getName() ); } else { mappingTarget.setName( null ); } mappingTarget.setYear( house.getYear() ); if ( house.getRoof() != null ) { if ( mappingTarget.getRoof() == null ) { mappingTarget.setRoof( new RoofDto() ); } roofToRoofDto( house.getRoof(), mappingTarget.getRoof() ); } else { mappingTarget.setRoof( null ); } } }
constant
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/CyclicBufferTest.java
{ "start": 1192, "end": 3309 }
class ____ { @Test void testSize0() { final CyclicBuffer<Integer> buffer = new CyclicBuffer<>(Integer.class, 0); assertTrue(buffer.isEmpty()); buffer.add(1); assertTrue(buffer.isEmpty()); Integer[] items = buffer.removeAll(); assertEquals(0, items.length, "Incorrect number of items"); assertTrue(buffer.isEmpty()); buffer.add(1); buffer.add(2); buffer.add(3); buffer.add(4); items = buffer.removeAll(); assertEquals(0, items.length, "Incorrect number of items"); assertTrue(buffer.isEmpty()); } @Test void testSize1() { final CyclicBuffer<Integer> buffer = new CyclicBuffer<>(Integer.class, 1); assertTrue(buffer.isEmpty()); buffer.add(1); assertFalse(buffer.isEmpty()); Integer[] items = buffer.removeAll(); assertEquals(1, items.length, "Incorrect number of items"); assertTrue(buffer.isEmpty()); buffer.add(1); buffer.add(2); buffer.add(3); buffer.add(4); items = buffer.removeAll(); assertEquals(1, items.length, "Incorrect number of items"); assertArrayEquals(new Integer[] {4}, items); assertTrue(buffer.isEmpty()); } @Test void testSize3() { final CyclicBuffer<Integer> buffer = new CyclicBuffer<>(Integer.class, 3); assertTrue(buffer.isEmpty()); buffer.add(1); assertFalse(buffer.isEmpty()); Integer[] items = buffer.removeAll(); assertEquals(1, items.length, "Incorrect number of items"); assertTrue(buffer.isEmpty()); buffer.add(1); buffer.add(2); buffer.add(3); buffer.add(4); items = buffer.removeAll(); assertEquals(3, items.length, "Incorrect number of items"); assertArrayEquals(new Integer[] {2, 3, 4}, items); assertTrue(buffer.isEmpty()); } @Test void testSizeNegative() { assertThrows(IllegalArgumentException.class, () -> new CyclicBuffer<>(Integer.class, -1)); } }
CyclicBufferTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/RouterQuotaManager.java
{ "start": 1498, "end": 6857 }
class ____ { /** Quota usage <MountTable Path, Aggregated QuotaUsage> cache. */ private TreeMap<String, RouterQuotaUsage> cache; /** Lock to access the quota cache. */ private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final Lock readLock = readWriteLock.readLock(); private final Lock writeLock = readWriteLock.writeLock(); public RouterQuotaManager() { this.cache = new TreeMap<>(); } /** * Get all the mount quota paths. * @return All the mount quota paths. */ public Set<String> getAll() { readLock.lock(); try { return this.cache.keySet(); } finally { readLock.unlock(); } } /** * Is the path a mount entry. * * @param path the path. * @return {@code true} if path is a mount entry; {@code false} otherwise. */ boolean isMountEntry(String path) { readLock.lock(); try { return this.cache.containsKey(path); } finally { readLock.unlock(); } } /** * Get the nearest ancestor's quota usage, and meanwhile its quota was set. * @param path The path being written. * @return RouterQuotaUsage Quota usage. */ public RouterQuotaUsage getQuotaUsage(String path) { readLock.lock(); try { RouterQuotaUsage quotaUsage = this.cache.get(path); if (quotaUsage != null && isQuotaSet(quotaUsage)) { return quotaUsage; } // If not found, look for its parent path usage value. int pos = path.lastIndexOf(Path.SEPARATOR); if (pos != -1) { String parentPath = path.substring(0, pos); return getQuotaUsage(parentPath); } } finally { readLock.unlock(); } return null; } /** * Get children paths (can include itself) under specified federation path. * @param parentPath Federated path. * @return Set of children paths. */ public Set<String> getPaths(String parentPath) { readLock.lock(); try { String from = parentPath; String to = parentPath + Character.MAX_VALUE; SortedMap<String, RouterQuotaUsage> subMap = this.cache.subMap(from, to); Set<String> validPaths = new HashSet<>(); if (subMap != null) { for (String path : subMap.keySet()) { if (isParentEntry(path, parentPath)) { validPaths.add(path); } } } return validPaths; } finally { readLock.unlock(); } } /** * Get parent paths (including itself) and quotas of the specified federation * path. Only parents containing quota are returned. * @param childPath Federated path. * @return TreeMap of parent paths and quotas. */ TreeMap<String, RouterQuotaUsage> getParentsContainingQuota( String childPath) { TreeMap<String, RouterQuotaUsage> res = new TreeMap<>(); readLock.lock(); try { Entry<String, RouterQuotaUsage> entry = this.cache.floorEntry(childPath); while (entry != null) { String mountPath = entry.getKey(); RouterQuotaUsage quota = entry.getValue(); if (isQuotaSet(quota) && isParentEntry(childPath, mountPath)) { res.put(mountPath, quota); } entry = this.cache.lowerEntry(mountPath); } return res; } finally { readLock.unlock(); } } /** * Put new entity into cache. * @param path Mount table path. * @param quotaUsage Corresponding cache value. */ public void put(String path, RouterQuotaUsage quotaUsage) { writeLock.lock(); try { this.cache.put(path, quotaUsage); } finally { writeLock.unlock(); } } /** * Update quota in cache. The usage will be preserved. * @param path Mount table path. * @param quota Corresponding quota value. */ public void updateQuota(String path, RouterQuotaUsage quota) { writeLock.lock(); try { RouterQuotaUsage.Builder builder = new RouterQuotaUsage.Builder() .quota(quota.getQuota()).spaceQuota(quota.getSpaceQuota()); RouterQuotaUsage current = this.cache.get(path); if (current != null) { builder.fileAndDirectoryCount(current.getFileAndDirectoryCount()) .spaceConsumed(current.getSpaceConsumed()); } this.cache.put(path, builder.build()); } finally { writeLock.unlock(); } } /** * Remove the entity from cache. * @param path Mount table path. */ public void remove(String path) { writeLock.lock(); try { this.cache.remove(path); } finally { writeLock.unlock(); } } /** * Clean up the cache. */ public void clear() { writeLock.lock(); try { this.cache.clear(); } finally { writeLock.unlock(); } } /** * Check if the quota was set. * @param quota the quota usage. * @return True if the quota is set. */ public static boolean isQuotaSet(QuotaUsage quota) { if (quota != null) { long nsQuota = quota.getQuota(); long ssQuota = quota.getSpaceQuota(); // once nsQuota or ssQuota was set, this mount table is quota set if (nsQuota != HdfsConstants.QUOTA_RESET || ssQuota != HdfsConstants.QUOTA_RESET || Quota.orByStorageType( t -> quota.getTypeQuota(t) != HdfsConstants.QUOTA_RESET)) { return true; } } return false; } }
RouterQuotaManager
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MQ2EndpointBuilderFactory.java
{ "start": 1416, "end": 1536 }
interface ____ { /** * Builder for endpoint for the AWS MQ component. */ public
MQ2EndpointBuilderFactory
java
spring-projects__spring-boot
module/spring-boot-cache/src/main/java/org/springframework/boot/cache/autoconfigure/CacheAutoConfiguration.java
{ "start": 4211, "end": 4541 }
class ____ extends EntityManagerFactoryDependsOnPostProcessor { CacheManagerEntityManagerFactoryDependsOnPostProcessor() { super("cacheManager"); } } /** * Bean used to validate that a CacheManager exists and provide a more meaningful * exception. */ static
CacheManagerEntityManagerFactoryDependsOnPostProcessor
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/serializer/SerializationFactory.java
{ "start": 1564, "end": 2877 }
class ____ extends Configured { static final Logger LOG = LoggerFactory.getLogger(SerializationFactory.class.getName()); private List<Serialization<?>> serializations = new ArrayList<Serialization<?>>(); /** * <p> * Serializations are found by reading the <code>io.serializations</code> * property from <code>conf</code>, which is a comma-delimited list of * classnames. * </p> * * @param conf configuration. */ public SerializationFactory(Configuration conf) { super(conf); for (String serializerName : conf.getTrimmedStrings( CommonConfigurationKeys.IO_SERIALIZATIONS_KEY, new String[]{WritableSerialization.class.getName(), AvroSpecificSerialization.class.getName(), AvroReflectSerialization.class.getName()})) { add(conf, serializerName); } } @SuppressWarnings("unchecked") private void add(Configuration conf, String serializationName) { try { Class<? extends Serialization> serializionClass = (Class<? extends Serialization>) conf.getClassByName(serializationName); serializations.add((Serialization) ReflectionUtils.newInstance(serializionClass, getConf())); } catch (ClassNotFoundException e) { LOG.warn("Serialization
SerializationFactory
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/collector/ccr/StatsCollector.java
{ "start": 1399, "end": 4351 }
class ____ extends Collector { public static final Setting<TimeValue> CCR_STATS_TIMEOUT = collectionTimeoutSetting("ccr.stats.timeout"); private final Settings settings; private final ThreadContext threadContext; private final Client client; public StatsCollector( final Settings settings, final ClusterService clusterService, final XPackLicenseState licenseState, final Client client ) { this(settings, clusterService, licenseState, client, client.threadPool().getThreadContext()); } StatsCollector( final Settings settings, final ClusterService clusterService, final XPackLicenseState licenseState, final Client client, final ThreadContext threadContext ) { super(TYPE, clusterService, CCR_STATS_TIMEOUT, licenseState); this.settings = settings; this.client = client; this.threadContext = threadContext; } @Override protected boolean shouldCollect(final boolean isElectedMaster) { // this can only run when monitoring is allowed and CCR is enabled and allowed, but also only on the elected master node return isElectedMaster && super.shouldCollect(isElectedMaster) && XPackSettings.CCR_ENABLED_SETTING.get(settings) && CcrConstants.CCR_FEATURE.checkWithoutTracking(licenseState); } @Override protected Collection<MonitoringDoc> doCollect(final MonitoringDoc.Node node, final long interval, final ClusterState clusterState) throws Exception { try (ThreadContext.StoredContext ignore = threadContext.stashWithOrigin(MONITORING_ORIGIN)) { final long timestamp = timestamp(); final String clusterUuid = clusterUuid(clusterState); final CcrStatsAction.Request request = new CcrStatsAction.Request(getCollectionTimeout()); final CcrStatsAction.Response response = client.execute(CcrStatsAction.INSTANCE, request).actionGet(getCollectionTimeout()); final AutoFollowStatsMonitoringDoc autoFollowStatsDoc = new AutoFollowStatsMonitoringDoc( clusterUuid, timestamp, interval, node, response.getAutoFollowStats() ); Set<String> collectionIndices = new HashSet<>(Arrays.asList(getCollectionIndices())); List<MonitoringDoc> docs = response.getFollowStats() .getStatsResponses() .stream() .filter(statsResponse -> collectionIndices.isEmpty() || collectionIndices.contains(statsResponse.status().followerIndex())) .map(stats -> new FollowStatsMonitoringDoc(clusterUuid, timestamp, interval, node, stats.status())) .collect(Collectors.toCollection(ArrayList::new)); docs.add(autoFollowStatsDoc); return docs; } } }
StatsCollector
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MockNotUsedInProductionTest.java
{ "start": 5225, "end": 5688 }
class ____ { @Mock private Test test; public Test test() { return this.test; } } """) .doTest(); } @Test public void privateField() { helper .addSourceLines( "Test.java", """ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.mockito.Mock;
Test
java
elastic__elasticsearch
modules/lang-painless/src/test/java/org/elasticsearch/painless/EqualsTests.java
{ "start": 630, "end": 14943 }
class ____ extends ScriptTestCase { public void testTypesEquals() { assertEquals(true, exec("return false === false;")); assertEquals(false, exec("boolean x = false; boolean y = true; return x === y;")); assertEquals(true, exec("boolean x = false; boolean y = false; return x === y;")); assertEquals(false, exec("return (byte)3 === (byte)4;")); assertEquals(true, exec("byte x = 3; byte y = 3; return x === y;")); assertEquals(false, exec("return (char)3 === (char)4;")); assertEquals(true, exec("char x = 3; char y = 3; return x === y;")); assertEquals(false, exec("return (short)3 === (short)4;")); assertEquals(true, exec("short x = 3; short y = 3; return x === y;")); assertEquals(false, exec("return (int)3 === (int)4;")); assertEquals(true, exec("int x = 3; int y = 3; return x === y;")); assertEquals(false, exec("return (long)3 === (long)4;")); assertEquals(true, exec("long x = 3; long y = 3; return x === y;")); assertEquals(false, exec("return (float)3 === (float)4;")); assertEquals(true, exec("float x = 3; float y = 3; return x === y;")); assertEquals(false, exec("return (double)3 === (double)4;")); assertEquals(true, exec("double x = 3; double y = 3; return x === y;")); assertEquals(true, exec("return false == false;")); assertEquals(false, exec("boolean x = false; boolean y = true; return x == y;")); assertEquals(true, exec("boolean x = false; boolean y = false; return x == y;")); assertEquals(false, exec("return (byte)3 == (byte)4;")); assertEquals(true, exec("byte x = 3; byte y = 3; return x == y;")); assertEquals(false, exec("return (char)3 == (char)4;")); assertEquals(true, exec("char x = 3; char y = 3; return x == y;")); assertEquals(false, exec("return (short)3 == (short)4;")); assertEquals(true, exec("short x = 3; short y = 3; return x == y;")); assertEquals(false, exec("return (int)3 == (int)4;")); assertEquals(true, exec("int x = 3; int y = 3; return x == y;")); assertEquals(false, exec("return (long)3 == (long)4;")); assertEquals(true, exec("long x = 3; long y = 3; return x == y;")); assertEquals(false, exec("return (float)3 == (float)4;")); assertEquals(true, exec("float x = 3; float y = 3; return x == y;")); assertEquals(false, exec("return (double)3 == (double)4;")); assertEquals(true, exec("double x = 3; double y = 3; return x == y;")); } public void testTypesNotEquals() { assertEquals(false, exec("return true !== true;")); assertEquals(true, exec("boolean x = true; boolean y = false; return x !== y;")); assertEquals(false, exec("boolean x = false; boolean y = false; return x !== y;")); assertEquals(true, exec("return (byte)3 !== (byte)4;")); assertEquals(false, exec("byte x = 3; byte y = 3; return x !== y;")); assertEquals(true, exec("return (char)3 !== (char)4;")); assertEquals(false, exec("char x = 3; char y = 3; return x !== y;")); assertEquals(true, exec("return (short)3 !== (short)4;")); assertEquals(false, exec("short x = 3; short y = 3; return x !== y;")); assertEquals(true, exec("return (int)3 !== (int)4;")); assertEquals(false, exec("int x = 3; int y = 3; return x !== y;")); assertEquals(true, exec("return (long)3 !== (long)4;")); assertEquals(false, exec("long x = 3; long y = 3; return x !== y;")); assertEquals(true, exec("return (float)3 !== (float)4;")); assertEquals(false, exec("float x = 3; float y = 3; return x !== y;")); assertEquals(true, exec("return (double)3 !== (double)4;")); assertEquals(false, exec("double x = 3; double y = 3; return x !== y;")); assertEquals(false, exec("return true != true;")); assertEquals(true, exec("boolean x = true; boolean y = false; return x != y;")); assertEquals(false, exec("boolean x = false; boolean y = false; return x != y;")); assertEquals(true, exec("return (byte)3 != (byte)4;")); assertEquals(false, exec("byte x = 3; byte y = 3; return x != y;")); assertEquals(true, exec("return (char)3 != (char)4;")); assertEquals(false, exec("char x = 3; char y = 3; return x != y;")); assertEquals(true, exec("return (short)3 != (short)4;")); assertEquals(false, exec("short x = 3; short y = 3; return x != y;")); assertEquals(true, exec("return (int)3 != (int)4;")); assertEquals(false, exec("int x = 3; int y = 3; return x != y;")); assertEquals(true, exec("return (long)3 != (long)4;")); assertEquals(false, exec("long x = 3; long y = 3; return x != y;")); assertEquals(true, exec("return (float)3 != (float)4;")); assertEquals(false, exec("float x = 3; float y = 3; return x != y;")); assertEquals(true, exec("return (double)3 != (double)4;")); assertEquals(false, exec("double x = 3; double y = 3; return x != y;")); } public void testEquals() { assertEquals(true, exec("return 3 == 3;")); assertEquals(false, exec("int x = 4; int y = 5; x == y")); assertEquals(true, exec("int[] x = new int[1]; Object y = x; return x == y;")); assertEquals(true, exec("int[] x = new int[1]; Object y = x; return x === y;")); assertEquals(false, exec("int[] x = new int[1]; Object y = new int[1]; return x == y;")); assertEquals(false, exec("int[] x = new int[1]; Object y = new int[1]; return x === y;")); assertEquals(false, exec("Map x = new HashMap(); List y = new ArrayList(); return x == y;")); assertEquals(false, exec("Map x = new HashMap(); List y = new ArrayList(); return x === y;")); } public void testNotEquals() { assertEquals(false, exec("return 3 != 3;")); assertEquals(true, exec("int x = 4; int y = 5; x != y")); assertEquals(false, exec("int[] x = new int[1]; Object y = x; return x != y;")); assertEquals(false, exec("int[] x = new int[1]; Object y = x; return x !== y;")); assertEquals(true, exec("int[] x = new int[1]; Object y = new int[1]; return x != y;")); assertEquals(true, exec("int[] x = new int[1]; Object y = new int[1]; return x !== y;")); assertEquals(true, exec("Map x = new HashMap(); List y = new ArrayList(); return x != y;")); assertEquals(true, exec("Map x = new HashMap(); List y = new ArrayList(); return x !== y;")); } public void testBranchEquals() { assertEquals(0, exec("def a = (char)'a'; def b = (char)'b'; if (a == b) return 1; else return 0;")); assertEquals(1, exec("def a = (char)'a'; def b = (char)'a'; if (a == b) return 1; else return 0;")); assertEquals(1, exec("def a = 1; def b = 1; if (a === b) return 1; else return 0;")); assertEquals(1, exec("def a = (char)'a'; def b = (char)'a'; if (a === b) return 1; else return 0;")); assertEquals(1, exec("def a = (char)'a'; Object b = a; if (a === b) return 1; else return 0;")); assertEquals(1, exec("def a = 1; Number b = a; Number c = a; if (c === b) return 1; else return 0;")); assertEquals(0, exec("def a = 1; Object b = new HashMap(); if (a === (Object)b) return 1; else return 0;")); } public void testEqualsDefAndPrimitive() { /* This test needs an Integer that isn't cached by Integer.valueOf so we draw one randomly. We can't use any fixed integer because * we can never be sure that the JVM hasn't configured itself to cache that Integer. It is sneaky like that. */ int uncachedAutoboxedInt = randomValueOtherThanMany(i -> Integer.valueOf(i) == Integer.valueOf(i), ESTestCase::randomInt); assertEquals(true, exec("def x = params.i; int y = params.i; return x == y;", singletonMap("i", uncachedAutoboxedInt), true)); assertEquals(false, exec("def x = params.i; int y = params.i; return x === y;", singletonMap("i", uncachedAutoboxedInt), true)); assertEquals(true, exec("def x = params.i; int y = params.i; return y == x;", singletonMap("i", uncachedAutoboxedInt), true)); assertEquals(false, exec("def x = params.i; int y = params.i; return y === x;", singletonMap("i", uncachedAutoboxedInt), true)); /* Now check that we use valueOf with the boxing used for comparing primitives to def. For this we need an * integer that is cached by Integer.valueOf. The JLS says 0 should always be cached. */ int cachedAutoboxedInt = 0; assertSame(Integer.valueOf(cachedAutoboxedInt), Integer.valueOf(cachedAutoboxedInt)); assertEquals(true, exec("def x = params.i; int y = params.i; return x == y;", singletonMap("i", cachedAutoboxedInt), true)); assertEquals(true, exec("def x = params.i; int y = params.i; return x === y;", singletonMap("i", cachedAutoboxedInt), true)); assertEquals(true, exec("def x = params.i; int y = params.i; return y == x;", singletonMap("i", cachedAutoboxedInt), true)); assertEquals(true, exec("def x = params.i; int y = params.i; return y === x;", singletonMap("i", cachedAutoboxedInt), true)); } public void testBranchNotEquals() { assertEquals(1, exec("def a = (char)'a'; def b = (char)'b'; if (a != b) return 1; else return 0;")); assertEquals(0, exec("def a = (char)'a'; def b = (char)'a'; if (a != b) return 1; else return 0;")); assertEquals(0, exec("def a = 1; def b = 1; if (a !== b) return 1; else return 0;")); assertEquals(0, exec("def a = (char)'a'; def b = (char)'a'; if (a !== b) return 1; else return 0;")); assertEquals(0, exec("def a = (char)'a'; Object b = a; if (a !== b) return 1; else return 0;")); assertEquals(0, exec("def a = 1; Number b = a; Number c = a; if (c !== b) return 1; else return 0;")); assertEquals(1, exec("def a = 1; Object b = new HashMap(); if (a !== (Object)b) return 1; else return 0;")); } public void testNotEqualsDefAndPrimitive() { /* This test needs an Integer that isn't cached by Integer.valueOf so we draw one randomly. We can't use any fixed integer because * we can never be sure that the JVM hasn't configured itself to cache that Integer. It is sneaky like that. */ int uncachedAutoboxedInt = randomValueOtherThanMany(i -> Integer.valueOf(i) == Integer.valueOf(i), ESTestCase::randomInt); assertEquals(false, exec("def x = params.i; int y = params.i; return x != y;", singletonMap("i", uncachedAutoboxedInt), true)); assertEquals(true, exec("def x = params.i; int y = params.i; return x !== y;", singletonMap("i", uncachedAutoboxedInt), true)); assertEquals(false, exec("def x = params.i; int y = params.i; return y != x;", singletonMap("i", uncachedAutoboxedInt), true)); assertEquals(true, exec("def x = params.i; int y = params.i; return y !== x;", singletonMap("i", uncachedAutoboxedInt), true)); /* Now check that we use valueOf with the boxing used for comparing primitives to def. For this we need an * integer that is cached by Integer.valueOf. The JLS says 0 should always be cached. */ int cachedAutoboxedInt = 0; assertSame(Integer.valueOf(cachedAutoboxedInt), Integer.valueOf(cachedAutoboxedInt)); assertEquals(false, exec("def x = params.i; int y = params.i; return x != y;", singletonMap("i", cachedAutoboxedInt), true)); assertEquals(false, exec("def x = params.i; int y = params.i; return x !== y;", singletonMap("i", cachedAutoboxedInt), true)); assertEquals(false, exec("def x = params.i; int y = params.i; return y != x;", singletonMap("i", cachedAutoboxedInt), true)); assertEquals(false, exec("def x = params.i; int y = params.i; return y !== x;", singletonMap("i", cachedAutoboxedInt), true)); } public void testRightHandNull() { assertEquals(false, exec("HashMap a = new HashMap(); return a == null;")); assertEquals(false, exec("HashMap a = new HashMap(); return a === null;")); assertEquals(true, exec("HashMap a = new HashMap(); return a != null;")); assertEquals(true, exec("HashMap a = new HashMap(); return a !== null;")); } public void testLeftHandNull() { assertEquals(false, exec("HashMap a = new HashMap(); return null == a;")); assertEquals(false, exec("HashMap a = new HashMap(); return null === a;")); assertEquals(true, exec("HashMap a = new HashMap(); return null != a;")); assertEquals(true, exec("HashMap a = new HashMap(); return null !== a;")); } public void testStringEquals() { assertEquals(false, exec("def x = null; return \"a\" == x")); assertEquals(true, exec("def x = \"a\"; return \"a\" == x")); assertEquals(true, exec("def x = null; return \"a\" != x")); assertEquals(false, exec("def x = \"a\"; return \"a\" != x")); assertEquals(false, exec("def x = null; return x == \"a\"")); assertEquals(true, exec("def x = \"a\"; return x == \"a\"")); assertEquals(true, exec("def x = null; return x != \"a\"")); assertEquals(false, exec("def x = \"a\"; return x != \"a\"")); } public void testStringEqualsMethodCall() { assertBytecodeExists("def x = \"a\"; return \"a\" == x", "INVOKEVIRTUAL java/lang/Object.equals (Ljava/lang/Object;)Z"); assertBytecodeExists("def x = \"a\"; return \"a\" != x", "INVOKEVIRTUAL java/lang/Object.equals (Ljava/lang/Object;)Z"); assertBytecodeExists("def x = \"a\"; return x == \"a\"", "INVOKEVIRTUAL java/lang/Object.equals (Ljava/lang/Object;)Z"); } public void testEqualsNullCheck() { // get the same callsite working once, then with a null // need to specify call site depth as 0 to force MIC to execute assertEquals(false, exec(""" def list = [2, 2, 3, 3, 4, null]; boolean b; for (int i=0; i<list.length; i+=2) { b = list[i] == list[i+1]; b = list[i+1] == 10; b = 10 == list[i+1]; } return b; """, Map.of(), Map.of(CompilerSettings.INITIAL_CALL_SITE_DEPTH, "0"), false)); } }
EqualsTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/script/NumberSortScript.java
{ "start": 624, "end": 1371 }
class ____ extends AbstractSortScript { public static final String[] PARAMETERS = {}; public static final ScriptContext<Factory> CONTEXT = new ScriptContext<>("number_sort", Factory.class); public NumberSortScript(Map<String, Object> params, SearchLookup searchLookup, DocReader docReader) { // searchLookup is used taken in for compatibility with expressions. See ExpressionScriptEngine.newScoreScript and // ExpressionScriptEngine.getDocValueSource for where it's used. super(params, docReader); } protected NumberSortScript() { super(); } public abstract double execute(); /** * A factory to construct {@link NumberSortScript} instances. */ public
NumberSortScript
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/reflect/ReflectData.java
{ "start": 2621, "end": 3250 }
class ____ extends SpecificData { private static final String STRING_OUTER_PARENT_REFERENCE = "this$0"; // holds a wrapper so null entries will have a cached value private final ConcurrentMap<Schema, CustomEncodingWrapper> encoderCache = new ConcurrentHashMap<>(); /** * Always false since custom coders are not available for {@link ReflectData}. */ @Override public boolean useCustomCoders() { return false; } /** * {@link ReflectData} implementation that permits null field values. The schema * generated for each field is a union of its declared type and null. */ public static
ReflectData
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4328PrimitiveMojoParameterConfigurationTest.java
{ "start": 1523, "end": 2398 }
class ____ to reflection) and the actual parameter type should not matter. * * @throws Exception in case of failure */ @Test public void testit() throws Exception { File testDir = extractResources("/mng-4328"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.addCliArgument("--offline"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); Properties props; props = verifier.loadProperties("target/config1.properties"); assertEquals("true", props.getProperty("primitiveBooleanParam")); props = verifier.loadProperties("target/config2.properties"); assertEquals("true", props.getProperty("primitiveBooleanParam")); } }
due
java
micronaut-projects__micronaut-core
http-server-netty/src/test/groovy/io/micronaut/http/server/netty/binding/HttpRequestTest.java
{ "start": 1271, "end": 3404 }
class ____ extends TestCase { public void testForEach() { final DefaultFullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "/test"); nettyRequest.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); HttpRequest<?> request = new NettyHttpRequest( nettyRequest, NettyByteBodyFactory.empty(), new DetachedMockFactory().Mock(ChannelHandlerContext.class), ConversionService.SHARED, new HttpServerConfiguration() ); final HttpHeaders headers = request.getHeaders(); headers.forEach((name, values) -> { assertEquals(HttpHeaders.CONTENT_TYPE, name); assertEquals(1, values.size()); assertEquals(MediaType.APPLICATION_JSON, values.iterator().next()); }); } public void testForEach2() { final DefaultFullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "/test"); nettyRequest.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); nettyRequest.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML); HttpRequest<?> request = new NettyHttpRequest( nettyRequest, NettyByteBodyFactory.empty(), new DetachedMockFactory().Mock(ChannelHandlerContext.class), ConversionService.SHARED, new HttpServerConfiguration() ); final HttpHeaders headers = request.getHeaders(); headers.forEach((name, values) -> { assertEquals(HttpHeaders.CONTENT_TYPE, name); assertEquals(2, values.size()); assertTrue(values.contains(MediaType.APPLICATION_JSON)); assertTrue(values.contains(MediaType.APPLICATION_XML)); }); AtomicInteger integer = new AtomicInteger(0); headers.forEachValue((s, s2) -> integer.incrementAndGet()); assertEquals(2, integer.get()); } }
HttpRequestTest
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilter.java
{ "start": 1551, "end": 4219 }
class ____ implements WebFilter { private ServerWebExchangeMatcher matcher = ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/logout"); @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return this.matcher.matches(exchange) .filter(ServerWebExchangeMatcher.MatchResult::isMatch) .switchIfEmpty(chain.filter(exchange).then(Mono.empty())) .flatMap((matchResult) -> render(exchange)); } private Mono<Void> render(ServerWebExchange exchange) { ServerHttpResponse result = exchange.getResponse(); result.setStatusCode(HttpStatus.OK); result.getHeaders().setContentType(MediaType.TEXT_HTML); return result.writeWith(createBuffer(exchange)); } private Mono<DataBuffer> createBuffer(ServerWebExchange exchange) { Mono<CsrfToken> token = exchange.getAttributeOrDefault(CsrfToken.class.getName(), Mono.empty()); String contextPath = exchange.getRequest().getPath().contextPath().value(); return token.map(LogoutPageGeneratingWebFilter::csrfToken).defaultIfEmpty("").map((csrfTokenHtmlInput) -> { byte[] bytes = createPage(csrfTokenHtmlInput, contextPath); DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory(); return bufferFactory.wrap(bytes); }); } private static byte[] createPage(String csrfTokenHtmlInput, String contextPath) { return HtmlTemplates.fromTemplate(LOGOUT_PAGE_TEMPLATE) .withValue("contextPath", contextPath) .withRawHtml("csrf", csrfTokenHtmlInput.indent(8)) .render() .getBytes(Charset.defaultCharset()); } private static String csrfToken(CsrfToken token) { return HtmlTemplates.fromTemplate(CSRF_INPUT_TEMPLATE) .withValue("name", token.getParameterName()) .withValue("value", token.getToken()) .render(); } private static final String LOGOUT_PAGE_TEMPLATE = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Confirm Log Out?</title> <link href="{{contextPath}}/default-ui.css" rel="stylesheet" /> </head> <body> <div class="content"> <form class="logout-form" method="post" action="{{contextPath}}/logout"> <h2>Are you sure you want to log out?</h2> {{csrf}} <button class="primary" type="submit">Log Out</button> </form> </div> </body> </html>"""; private static final String CSRF_INPUT_TEMPLATE = """ <input name="{{name}}" type="hidden" value="{{value}}" /> """; }
LogoutPageGeneratingWebFilter
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/string/EndsWithErrorTests.java
{ "start": 799, "end": 1397 }
class ____ extends ErrorsForCasesWithoutExamplesTestCase { @Override protected List<TestCaseSupplier> cases() { return paramsToSuppliers(EndsWithTests.parameters()); } @Override protected Expression build(Source source, List<Expression> args) { return new EndsWith(source, args.get(0), args.get(1)); } @Override protected Matcher<String> expectedTypeErrorMatcher(List<Set<DataType>> validPerPosition, List<DataType> signature) { return equalTo(typeErrorMessage(true, validPerPosition, signature, (v, p) -> "string")); } }
EndsWithErrorTests
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/predicate/operator/comparison/GreaterThanOrEqualDoublesEvaluator.java
{ "start": 1213, "end": 5115 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(GreaterThanOrEqualDoublesEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator lhs; private final EvalOperator.ExpressionEvaluator rhs; private final DriverContext driverContext; private Warnings warnings; public GreaterThanOrEqualDoublesEvaluator(Source source, EvalOperator.ExpressionEvaluator lhs, EvalOperator.ExpressionEvaluator rhs, DriverContext driverContext) { this.source = source; this.lhs = lhs; this.rhs = rhs; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (DoubleBlock lhsBlock = (DoubleBlock) lhs.eval(page)) { try (DoubleBlock rhsBlock = (DoubleBlock) rhs.eval(page)) { DoubleVector lhsVector = lhsBlock.asVector(); if (lhsVector == null) { return eval(page.getPositionCount(), lhsBlock, rhsBlock); } DoubleVector rhsVector = rhsBlock.asVector(); if (rhsVector == null) { return eval(page.getPositionCount(), lhsBlock, rhsBlock); } return eval(page.getPositionCount(), lhsVector, rhsVector).asBlock(); } } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += lhs.baseRamBytesUsed(); baseRamBytesUsed += rhs.baseRamBytesUsed(); return baseRamBytesUsed; } public BooleanBlock eval(int positionCount, DoubleBlock lhsBlock, DoubleBlock rhsBlock) { try(BooleanBlock.Builder result = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { switch (lhsBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } switch (rhsBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } double lhs = lhsBlock.getDouble(lhsBlock.getFirstValueIndex(p)); double rhs = rhsBlock.getDouble(rhsBlock.getFirstValueIndex(p)); result.appendBoolean(GreaterThanOrEqual.processDoubles(lhs, rhs)); } return result.build(); } } public BooleanVector eval(int positionCount, DoubleVector lhsVector, DoubleVector rhsVector) { try(BooleanVector.FixedBuilder result = driverContext.blockFactory().newBooleanVectorFixedBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { double lhs = lhsVector.getDouble(p); double rhs = rhsVector.getDouble(p); result.appendBoolean(p, GreaterThanOrEqual.processDoubles(lhs, rhs)); } return result.build(); } } @Override public String toString() { return "GreaterThanOrEqualDoublesEvaluator[" + "lhs=" + lhs + ", rhs=" + rhs + "]"; } @Override public void close() { Releasables.closeExpectNoException(lhs, rhs); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
GreaterThanOrEqualDoublesEvaluator
java
google__dagger
javatests/dagger/internal/codegen/bindinggraphvalidation/SetMultibindingValidationTest.java
{ "start": 4320, "end": 5079 }
interface ____ {", " Set<Foo> setOfFoo();", "}"); CompilerTests.daggerCompiler(FOO, FOO_IMPL, module, component) .withProcessingOptions(compilerMode.processorOptions()) .compile( subject -> { subject.hasErrorCount(1); subject.hasErrorContaining("FooImpl is bound multiple times"); }); } @Test public void testSetBindingsToMissingBinding() { Source module = CompilerTests.javaSource( "test.TestModule", "package test;", "", "import dagger.Binds;", "import dagger.Module;", "import dagger.multibindings.IntoSet;", "", "@Module", "
TestComponent
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/Test.java
{ "start": 2625, "end": 3165 }
interface ____ {@link TestMethodOrder @TestMethodOrder} * and specify the desired {@link MethodOrderer} implementation. * * @since 5.0 * @see RepeatedTest * @see org.junit.jupiter.params.ParameterizedTest * @see TestTemplate * @see TestFactory * @see TestInfo * @see DisplayName * @see Tag * @see BeforeAll * @see AfterAll * @see BeforeEach * @see AfterEach */ @Target({ ElementType.ANNOTATION_TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @API(status = STABLE, since = "5.0") @Testable public @
with
java
spring-projects__spring-boot
module/spring-boot-micrometer-tracing/src/main/java/org/springframework/boot/micrometer/tracing/autoconfigure/TracingAndMeterObservationHandlerGroup.java
{ "start": 1684, "end": 3428 }
class ____ implements ObservationHandlerGroup { private final Tracer tracer; TracingAndMeterObservationHandlerGroup(Tracer tracer) { this.tracer = tracer; } @Override public boolean isMember(ObservationHandler<?> handler) { return MeterObservationHandler.class.isInstance(handler) || TracingObservationHandler.class.isInstance(handler); } @Override public int compareTo(ObservationHandlerGroup other) { if (other instanceof TracingAndMeterObservationHandlerGroup) { return 0; } return MeterObservationHandler.class.isAssignableFrom(other.handlerType()) ? -1 : 1; } @Override public void registerMembers(ObservationConfig config, List<ObservationHandler<?>> members) { List<ObservationHandler<?>> tracingHandlers = new ArrayList<>(members.size()); List<ObservationHandler<?>> metricsHandlers = new ArrayList<>(members.size()); for (ObservationHandler<?> member : members) { if (member instanceof MeterObservationHandler<?> meterObservationHandler && !(member instanceof TracingAwareMeterObservationHandler<?>)) { metricsHandlers.add(new TracingAwareMeterObservationHandler<>(meterObservationHandler, this.tracer)); } else { tracingHandlers.add(member); } } registerHandlers(config, tracingHandlers); registerHandlers(config, metricsHandlers); } private void registerHandlers(ObservationConfig config, List<ObservationHandler<?>> handlers) { if (handlers.size() == 1) { config.observationHandler(handlers.get(0)); } else if (!handlers.isEmpty()) { config.observationHandler(new FirstMatchingCompositeObservationHandler(handlers)); } } @Override public Class<?> handlerType() { return TracingObservationHandler.class; } }
TracingAndMeterObservationHandlerGroup
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/ParameterResolverTests.java
{ "start": 15300, "end": 15526 }
class ____ { @Test void intPrimitive(int i) { assertEquals(42, i); } } @SuppressWarnings("JUnitMalformedDeclaration") @ExtendWith(PrimitiveArrayParameterResolver.class) static
PrimitiveIntegerMethodInjectionTestCase
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/StandaloneTestPlugin.java
{ "start": 1277, "end": 2697 }
class ____ implements Plugin<Project> { @Override public void apply(final Project project) { project.getRootProject().getPluginManager().apply(GlobalBuildInfoPlugin.class); project.getPluginManager().apply(ElasticsearchJavaBasePlugin.class); project.getPluginManager().apply(ElasticsearchTestBasePlugin.class); // only setup tests to build SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class); final SourceSet testSourceSet = sourceSets.create("test"); project.getDependencies().add(testSourceSet.getImplementationConfigurationName(), project.project(":test:framework")); project.getTasks().withType(Test.class).configureEach(test -> { test.setTestClassesDirs(testSourceSet.getOutput().getClassesDirs()); test.setClasspath(testSourceSet.getRuntimeClasspath()); }); TaskProvider<Test> testTask = project.getTasks().register("test", Test.class); testTask.configure(test -> { test.setGroup(JavaBasePlugin.VERIFICATION_GROUP); test.setDescription("Runs unit tests that are separate"); test.mustRunAfter(project.getTasks().getByName("precommit")); }); project.getTasks().named("check").configure(task -> task.dependsOn(testTask)); InternalPrecommitTasks.create(project, false); } }
StandaloneTestPlugin
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/search/arguments/SearchArgs.java
{ "start": 2535, "end": 23932 }
class ____<K, V> { private final SearchArgs<K, V> instance = new SearchArgs<>(); private SummarizeArgs.Builder<K, V> summarizeArgs; private HighlightArgs.Builder<K, V> highlightArgs; /** * Build a new instance of the {@link SearchArgs}. * * @return a new instance of the {@link SearchArgs} */ public SearchArgs<K, V> build() { if (!instance.summarize.isPresent() && summarizeArgs != null) { instance.summarize = Optional.of(summarizeArgs.build()); } if (!instance.highlight.isPresent() && highlightArgs != null) { instance.highlight = Optional.of(highlightArgs.build()); } return instance; } /** * Returns the document ids and not the content. This is useful if RediSearch is only an index on an external document * collection. Disabled by default. * * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> noContent() { instance.noContent = true; return this; } /** * Do not try to use stemming for query expansion but searches the query terms verbatim. Disabled by default. * * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> verbatim() { instance.verbatim = true; return this; } /** * Return the relative internal score of each document. This can be used to merge results from multiple instances. * Disabled by default. * * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> withScores() { instance.withScores = true; return this; } /** * Return the value of the sorting key, right after the id and score and/or payload, if requested. This is usually not * needed, and exists for distributed search coordination purposes. This option is relevant only if used in conjunction * with {@link SearchArgs.Builder#sortBy(SortByArgs)}. Disabled by default. * * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> withSortKeys() { instance.withSortKeys = true; return this; } /** * Limit the result to a given set of keys specified in the list. Non-existent keys are ignored, unless all the keys are * non-existent. * * @param key the key to search in * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> inKey(K key) { instance.inKeys.add(key); return this; } /** * Filter the result to those appearing only in specific attributes of the document. * * @param field the field to search in * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> inField(K field) { instance.inFields.add(field); return this; } /** * Limit the attributes returned from the document. The field is either an attribute name (for hashes and JSON) or a * JSON Path expression (for JSON). <code>as</code> is the name of the field used in the result as an alias. * * @param field the field to return * @param as the alias to use for this field in the result * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> returnField(K field, K as) { instance.returnFields.put(field, Optional.ofNullable(as)); return this; } /** * Limit the attributes returned from the document. The field is either an attribute name (for hashes and JSON) or a * JSON Path expression (for JSON). * * @param field the field to return * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> returnField(K field) { instance.returnFields.put(field, Optional.empty()); return this; } /** * Return only the sections of the attribute that contain the matched text. * * @param summarizeFilter the summarization filter * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see <a href= * "https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/highlight/">Highlighting</a> */ public SearchArgs.Builder<K, V> summarizeArgs(SummarizeArgs<K, V> summarizeFilter) { instance.summarize = Optional.ofNullable(summarizeFilter); return this; } /** * Convenience method to build {@link SummarizeArgs} * <p> * Add a field to summarize. Each field is summarized. If no FIELDS directive is passed, then all returned fields are * summarized. * * @param field the field to add * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see <a href= * "https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/highlight/">Highlighting</a> */ public SearchArgs.Builder<K, V> summarizeField(K field) { if (summarizeArgs == null) { summarizeArgs = new SummarizeArgs.Builder<>(); } summarizeArgs.field(field); return this; } /** * Convenience method to build {@link SummarizeArgs} * <p> * Set the number of context words each fragment should contain. Context words surround the found term. A higher value * will return a larger block of text. If not specified, the default value is 20. * * @param len the field to add * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see <a href= * "https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/highlight/">Highlighting</a> */ public SearchArgs.Builder<K, V> summarizeLen(long len) { if (summarizeArgs == null) { summarizeArgs = new SummarizeArgs.Builder<>(); } summarizeArgs.len(len); return this; } /** * Convenience method to build {@link SummarizeArgs} * <p> * The string used to divide individual summary snippets. The default is <code>...</code> which is common among search * engines, but you may override this with any other string if you desire to programmatically divide the snippets later * on. You may also use a newline sequence, as newlines are stripped from the result body during processing. * * @param separator the separator between fragments * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see <a href= * "https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/highlight/">Highlighting</a> */ public SearchArgs.Builder<K, V> summarizeSeparator(V separator) { if (summarizeArgs == null) { summarizeArgs = new SummarizeArgs.Builder<>(); } summarizeArgs.separator(separator); return this; } /** * Convenience method to build {@link SummarizeArgs} * <p> * Set the number of fragments to be returned. If not specified, the default is 3. * * @param fragments the number of fragments to return * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see <a href= * "https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/highlight/">Highlighting</a> */ public SearchArgs.Builder<K, V> summarizeFragments(long fragments) { if (summarizeArgs == null) { summarizeArgs = new SummarizeArgs.Builder<>(); } summarizeArgs.fragments(fragments); return this; } /** * Format occurrences of matched text. * * @param highlightFilter the highlighting filter * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see <a href= * "https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/highlight/">Highlighting</a> */ public SearchArgs.Builder<K, V> highlightArgs(HighlightArgs<K, V> highlightFilter) { instance.highlight = Optional.ofNullable(highlightFilter); return this; } /** * Convenience method to build {@link HighlightArgs} * <p> * Add a field to highlight. If no FIELDS directive is passed, then all returned fields are highlighted. * * @param field the field to summarize * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see <a href= * "https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/highlight/">Highlighting</a> */ public SearchArgs.Builder<K, V> highlightField(K field) { if (highlightArgs == null) { highlightArgs = new HighlightArgs.Builder<>(); } highlightArgs.field(field); return this; } /** * Convenience method to build {@link HighlightArgs} * <p> * Tags to surround the matched terms with. If no TAGS are specified, a built-in tag pair is prepended and appended to * each matched term. * * @param startTag the string is prepended to each matched term * @param endTag the string is appended to each matched term * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see <a href= * "https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/highlight/">Highlighting</a> */ public SearchArgs.Builder<K, V> highlightTags(V startTag, V endTag) { if (highlightArgs == null) { highlightArgs = new HighlightArgs.Builder<>(); } highlightArgs.tags(startTag, endTag); return this; } /** * Allow for a number of intermediate terms allowed to appear between the terms of the query. Suppose you're searching * for a phrase <code>hello world</code>, if some other terms appear in-between <code>hello</code> and * <code>world</code>, a SLOP greater than 0 allows for these text attributes to match. By default, there is no SLOP * constraint. * * @param slop the slop value how many intermediate terms are allowed * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> slop(long slop) { instance.slop = slop; return this; } /** * Require the terms in the document to have the same order as the terms in the query, regardless of the offsets between * them. Typically used in conjunction with {@link SearchArgs.Builder#slop(long)}. Disabled by default. * * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> inOrder() { instance.inOrder = true; return this; } /** * Specify the language of the query. This is used to stem the query terms. The default is * {@link DocumentLanguage#ENGLISH}. * <p/> * If this setting was specified as part of index creation, it doesn't need to be specified here. * * @param language the language of the query * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> language(DocumentLanguage language) { instance.language = Optional.ofNullable(language); return this; } /** * Use a custom query expander instead of the stemmer * * @param expander the query expander to use * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see <a href= * "https://redis.io/docs/latest/develop/interact/search-and-query/administration/extensions/">Extensions</a> */ public SearchArgs.Builder<K, V> expander(V expander) { instance.expander = Optional.ofNullable(expander); return this; } /** * Use a built-in or a user-provided scoring function * * @param scorer the {@link ScoringFunction} to use * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see <a href= * "https://redis.io/docs/latest/develop/interact/search-and-query/administration/extensions/">Extensions</a> * @see <a href="https://redis.io/docs/latest/develop/interact/search-and-query/advanced-concepts/scoring/">Scoring</a> */ public SearchArgs.Builder<K, V> scorer(ScoringFunction scorer) { instance.scorer = Optional.ofNullable(scorer); return this; } /** * Order the results by the value of this attribute. This applies to both text and numeric attributes. Attributes needed * for SORTBY should be declared as SORTABLE in the index, to be available with very low latency. * <p/> * Note that this adds memory overhead. * * @param sortBy the {@link SortByArgs} to use * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> sortBy(SortByArgs<K> sortBy) { instance.sortBy = Optional.ofNullable(sortBy); return this; } /** * Limit the results to the offset and number of results given. Note that the offset is zero-indexed. The default is 0 * 10, which returns 10 items starting from the first result. You can use LIMIT 0 0 to count the number of documents in * the result set without actually returning them. * <p/> * LIMIT behavior: If you use the LIMIT option without sorting, the results returned are non-deterministic, which means * that subsequent queries may return duplicated or missing values. Add SORTBY with a unique field, or use FT.AGGREGATE * with the WITHCURSOR option to ensure deterministic result set paging. * * @param offset the offset to use * @param number the limit to use * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> limit(long offset, long number) { instance.limit = Optional.of(new Limit(offset, number)); return this; } /** * Override the maximum time to wait for the query to complete. * * @param timeout the timeout to use (with millisecond resolution) * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> timeout(Duration timeout) { instance.timeout = Optional.ofNullable(timeout); return this; } /** * Add one or more value parameters. Each parameter has a name and a value. * <p/> * Requires {@link QueryDialects#DIALECT2} or higher. * * @param name the name of the parameter * @param value the value of the parameter * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining */ public SearchArgs.Builder<K, V> param(K name, V value) { instance.params.put(name, value); return this; } /** * Set the query dialect. The default is {@link QueryDialects#DIALECT2}. * * @param dialect the dialect to use * @return the instance of the current {@link SearchArgs.Builder} for the purpose of method chaining * @see QueryDialects */ public SearchArgs.Builder<K, V> dialect(QueryDialects dialect) { instance.dialect = dialect; return this; } } /** * Gets whether the NOCONTENT option is enabled. * * @return true if NOCONTENT is enabled, false otherwise */ public boolean isNoContent() { return noContent; } /** * Gets whether the WITHSCORES option is enabled. * * @return true if WITHSCORES is enabled, false otherwise */ public boolean isWithScores() { return withScores; } /** * Gets whether the WITHSORTKEYS option is enabled. * * @return true if WITHSORTKEYS is enabled, false otherwise */ public boolean isWithSortKeys() { return withSortKeys; } /** * Build a {@link CommandArgs} object that contains all the arguments. * * @param args the {@link CommandArgs} object */ public void build(CommandArgs<K, V> args) { if (noContent) { args.add(CommandKeyword.NOCONTENT); } if (verbatim) { args.add(CommandKeyword.VERBATIM); } if (withScores) { args.add(CommandKeyword.WITHSCORES); } if (withSortKeys) { args.add(CommandKeyword.WITHSORTKEYS); } if (!inKeys.isEmpty()) { args.add(CommandKeyword.INKEYS); args.add(inKeys.size()); args.addKeys(inKeys); } if (!inFields.isEmpty()) { args.add(CommandKeyword.INFIELDS); args.add(inFields.size()); args.addKeys(inFields); } if (!returnFields.isEmpty()) { args.add(CommandKeyword.RETURN); // Count total number of field specifications (field + optional AS + alias) int count = returnFields.size(); // Add 2 for each "AS" keyword and alias value count += (int) (returnFields.values().stream().filter(Optional::isPresent).count() * 2); args.add(count); returnFields.forEach((field, as) -> { args.addKey(field); if (as.isPresent()) { args.add(CommandKeyword.AS); args.addKey(as.get()); } }); } summarize.ifPresent(summarizeArgs -> summarizeArgs.build(args)); highlight.ifPresent(highlightArgs -> highlightArgs.build(args)); if (slop != null) { args.add(CommandKeyword.SLOP); args.add(slop); } timeout.ifPresent(timeoutDuration -> { args.add(CommandKeyword.TIMEOUT); args.add(timeoutDuration.toMillis()); }); if (inOrder) { args.add(CommandKeyword.INORDER); } language.ifPresent(documentLanguage -> { args.add(CommandKeyword.LANGUAGE); args.add(documentLanguage.toString()); }); expander.ifPresent(v -> { args.add(CommandKeyword.EXPANDER); args.addValue(v); }); scorer.ifPresent(scoringFunction -> { args.add(CommandKeyword.SCORER); args.add(scoringFunction.toString()); }); sortBy.ifPresent(sortByArgs -> sortByArgs.build(args)); limit.ifPresent(limitArgs -> { args.add(CommandKeyword.LIMIT); args.add(limitArgs.offset); args.add(limitArgs.num); }); if (!params.isEmpty()) { args.add(CommandKeyword.PARAMS); args.add(params.size() * 2L); params.forEach((name, value) -> { args.addKey(name); args.addValue(value); }); } args.add(CommandKeyword.DIALECT); args.add(dialect.toString()); } static
Builder
java
apache__camel
components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzRouteRestartTest.java
{ "start": 1062, "end": 2188 }
class ____ extends BaseQuartzTest { @Test public void testQuartzCronRoute() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(2); MockEndpoint.assertIsSatisfied(context); // restart route context().getRouteController().stopRoute("trigger"); mock.reset(); mock.expectedMessageCount(0); // wait a bit Awaitility.await().atMost(2, TimeUnit.SECONDS) .untilAsserted(() -> MockEndpoint.assertIsSatisfied(context)); // start route, and we got messages again mock.reset(); mock.expectedMinimumMessageCount(1); context().getRouteController().startRoute("trigger"); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("quartz://groupName/timerName?cron=0/1+*+*+*+*+?").routeId("trigger") .to("mock:result"); } }; } }
QuartzRouteRestartTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/CachingOfDeserTest.java
{ "start": 666, "end": 828 }
class ____ { @JsonDeserialize(contentUsing = CustomDeserializer735.class) public Map<String, Integer> map; } public static
TestMapWithCustom
java
micronaut-projects__micronaut-core
http-client-jdk/src/main/java/io/micronaut/http/client/jdk/JdkRawHttpClient.java
{ "start": 1467, "end": 3993 }
class ____ extends AbstractJdkHttpClient implements RawHttpClient { public JdkRawHttpClient(AbstractJdkHttpClient prototype) { super(prototype); } @Override public @NonNull Publisher<? extends HttpResponse<?>> exchange(@NonNull HttpRequest<?> request, @Nullable CloseableByteBody requestBody, @Nullable Thread blockedThread) { return exchangeImpl(new RawHttpRequestWrapper(conversionService, request.toMutableRequest(), requestBody), null); } @Override public void close() throws IOException { // Nothing to do here, we do not need to close clients } @Override protected <O> Publisher<HttpResponse<O>> responsePublisher(@NonNull HttpRequest<?> request, @Nullable Argument<O> bodyType) { return Mono.defer(() -> mapToHttpRequest(request, bodyType)) // defered so any client filter changes are used .map(httpRequest -> { if (log.isDebugEnabled()) { log.debug("Client {} Sending HTTP Request: {}", clientId, httpRequest); } if (log.isTraceEnabled()) { HttpHeadersUtil.trace(log, () -> httpRequest.headers().map().keySet(), headerName -> httpRequest.headers().allValues(headerName)); } BodySizeLimits bodySizeLimits = new BodySizeLimits(Long.MAX_VALUE, configuration.getMaxContentLength()); return client.sendAsync(httpRequest, responseInfo -> new ByteBodySubscriber(bodySizeLimits)); }) .flatMap(Mono::fromCompletionStage) .onErrorMap(IOException.class, e -> new HttpClientException("Error sending request: " + e.getMessage(), e)) .onErrorMap(InterruptedException.class, e -> new HttpClientException("Error sending request: " + e.getMessage(), e)) .map(netResponse -> { if (log.isDebugEnabled()) { log.debug("Client {} Received HTTP Response: {} {}", clientId, netResponse.statusCode(), netResponse.uri()); } //noinspection unchecked return (HttpResponse<O>) ByteBodyHttpResponseWrapper.wrap(new BaseHttpResponseAdapter<CloseableByteBody, O>(netResponse, conversionService) { @Override public @NonNull Optional<O> getBody() { return Optional.empty(); } }, netResponse.body()); }); } }
JdkRawHttpClient
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/metadata/ItemUsageTests.java
{ "start": 709, "end": 1662 }
class ____ extends AbstractWireTestCase<ItemUsage> { public static ItemUsage randomUsage() { return new ItemUsage(randomStringList(), randomStringList(), randomStringList()); } @Nullable private static List<String> randomStringList() { if (randomBoolean()) { return null; } else { return randomList(0, 1, () -> randomAlphaOfLengthBetween(2, 10)); } } @Override protected ItemUsage createTestInstance() { return randomUsage(); } @Override protected ItemUsage copyInstance(ItemUsage instance, TransportVersion version) throws IOException { return new ItemUsage(instance.getIndices(), instance.getDataStreams(), instance.getComposableTemplates()); } @Override protected ItemUsage mutateInstance(ItemUsage instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } }
ItemUsageTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/boolean2darray/Boolean2DArrayAssert_hasNumberOfRows_Test.java
{ "start": 848, "end": 1200 }
class ____ extends Boolean2DArrayAssertBaseTest { @Override protected Boolean2DArrayAssert invoke_api_method() { return assertions.hasNumberOfRows(1); } @Override protected void verify_internal_effects() { verify(arrays).assertNumberOfRows(getInfo(assertions), getActual(assertions), 1); } }
Boolean2DArrayAssert_hasNumberOfRows_Test
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/cache/CacheReproTests.java
{ "start": 23477, "end": 23687 }
class ____ { @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager(); } @Bean public Spr15271Interface service() { return new Spr15271Service(); } } }
Spr15271ConfigB
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/TestContextAnnotationUtilsTests.java
{ "start": 24707, "end": 24823 }
interface ____ { } @ContextConfiguration @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @
MetaCycle3
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/CrossTypeRevisionChangesReaderImpl.java
{ "start": 1013, "end": 4935 }
class ____ implements CrossTypeRevisionChangesReader { private final AuditReaderImplementor auditReaderImplementor; private final EnversService enversService; public CrossTypeRevisionChangesReaderImpl( AuditReaderImplementor auditReaderImplementor, EnversService enversService) { this.auditReaderImplementor = auditReaderImplementor; this.enversService = enversService; } @Override @SuppressWarnings("unchecked") public List<Object> findEntities(Number revision) throws IllegalStateException, IllegalArgumentException { final Set<Pair<String, Class>> entityTypes = findEntityTypes( revision ); final List<Object> result = new ArrayList<>(); for ( Pair<String, Class> type : entityTypes ) { result.addAll( auditReaderImplementor.createQuery().forEntitiesModifiedAtRevision( type.getSecond(), type.getFirst(), revision ) .getResultList() ); } return result; } @Override @SuppressWarnings("unchecked") public List<Object> findEntities(Number revision, RevisionType revisionType) throws IllegalStateException, IllegalArgumentException { final Set<Pair<String, Class>> entityTypes = findEntityTypes( revision ); final List<Object> result = new ArrayList<>(); for ( Pair<String, Class> type : entityTypes ) { result.addAll( auditReaderImplementor.createQuery().forEntitiesModifiedAtRevision( type.getSecond(), type.getFirst(), revision ) .add( new RevisionTypeAuditExpression( null, revisionType, "=" ) ).getResultList() ); } return result; } @Override @SuppressWarnings("unchecked") public Map<RevisionType, List<Object>> findEntitiesGroupByRevisionType(Number revision) throws IllegalStateException, IllegalArgumentException { final Set<Pair<String, Class>> entityTypes = findEntityTypes( revision ); final Map<RevisionType, List<Object>> result = new HashMap<>(); for ( RevisionType revisionType : RevisionType.values() ) { result.put( revisionType, new ArrayList<>() ); for ( Pair<String, Class> type : entityTypes ) { final List<Object> list = auditReaderImplementor.createQuery() .forEntitiesModifiedAtRevision( type.getSecond(), type.getFirst(), revision ) .add( new RevisionTypeAuditExpression( null, revisionType, "=" ) ) .getResultList(); result.get( revisionType ).addAll( list ); } } return result; } @Override @SuppressWarnings("unchecked") public Set<Pair<String, Class>> findEntityTypes(Number revision) throws IllegalStateException, IllegalArgumentException { checkNotNull( revision, "Entity revision" ); checkPositive( revision, "Entity revision" ); checkSession(); final Session session = auditReaderImplementor.getSession(); final SessionImplementor sessionImplementor = auditReaderImplementor.getSessionImplementor(); final Set<Number> revisions = new HashSet<>( 1 ); revisions.add( revision ); final Query<?> query = enversService.getRevisionInfoQueryCreator().getRevisionsQuery( session, revisions ); final Object revisionInfo = query.uniqueResult(); if ( revisionInfo != null ) { // If revision exists. final Set<String> entityNames = enversService.getModifiedEntityNamesReader().getModifiedEntityNames( revisionInfo ); if ( entityNames != null ) { // Generate result that contains entity names and corresponding Java classes. final Set<Pair<String, Class>> result = new HashSet<>(); for ( String entityName : entityNames ) { result.add( Pair.make( entityName, EntityTools.getEntityClass( sessionImplementor, entityName ) ) ); } return result; } } return Collections.EMPTY_SET; } private void checkSession() { if ( !auditReaderImplementor.getSession().isOpen() ) { throw new IllegalStateException( "The associated entity manager is closed!" ); } } }
CrossTypeRevisionChangesReaderImpl
java
apache__kafka
server/src/main/java/org/apache/kafka/server/partition/PendingPartitionChange.java
{ "start": 1008, "end": 1352 }
interface ____ extends PartitionState { /** * Returns the last committed partition state before this pending change. */ CommittedPartitionState lastCommittedState(); /** * Returns the LeaderAndIsr object sent to the controller for this pending change. */ LeaderAndIsr sentLeaderAndIsr(); }
PendingPartitionChange
java
apache__logging-log4j2
log4j-iostreams/src/main/java/org/apache/logging/log4j/io/internal/InternalFilterWriter.java
{ "start": 1131, "end": 1227 }
class ____ exists primarily to allow location calculation to work. * * @since 2.12 */ public
that
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/HARuntimeInfo.java
{ "start": 2416, "end": 3911 }
class ____ extends RemotingSerializable { private String addr; private long slaveAckOffset; private long diff; private boolean inSync; private long transferredByteInSecond; private long transferFromWhere; public String getAddr() { return this.addr; } public void setAddr(String addr) { this.addr = addr; } public long getSlaveAckOffset() { return this.slaveAckOffset; } public void setSlaveAckOffset(long slaveAckOffset) { this.slaveAckOffset = slaveAckOffset; } public long getDiff() { return this.diff; } public void setDiff(long diff) { this.diff = diff; } public boolean isInSync() { return this.inSync; } public void setInSync(boolean inSync) { this.inSync = inSync; } public long getTransferredByteInSecond() { return this.transferredByteInSecond; } public void setTransferredByteInSecond(long transferredByteInSecond) { this.transferredByteInSecond = transferredByteInSecond; } public long getTransferFromWhere() { return transferFromWhere; } public void setTransferFromWhere(long transferFromWhere) { this.transferFromWhere = transferFromWhere; } } public static
HAConnectionRuntimeInfo
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/settings/SecureSetting.java
{ "start": 7172, "end": 7833 }
class ____ extends Setting<SecureString> { private final String name; private InsecureStringSetting(String name) { super(name, "", SecureString::new, Property.Deprecated, Property.Filtered, Property.NodeScope); this.name = name; } @Override public SecureString get(Settings settings) { if (ALLOW_INSECURE_SETTINGS == false && exists(settings)) { throw new IllegalArgumentException("Setting [" + name + "] is insecure, use the elasticsearch keystore instead"); } return super.get(settings); } } private static
InsecureStringSetting
java
elastic__elasticsearch
plugins/discovery-ec2/src/main/java/org/elasticsearch/discovery/ec2/AwsEc2ServiceImpl.java
{ "start": 1933, "end": 6598 }
class ____ implements AwsEc2Service { private static final Logger LOGGER = LogManager.getLogger(AwsEc2ServiceImpl.class); private final AtomicReference<LazyInitializable<AmazonEc2Reference, ElasticsearchException>> lazyClientReference = new AtomicReference<>(); private Ec2Client buildClient(Ec2ClientSettings clientSettings) { final var httpClientBuilder = getHttpClientBuilder(); httpClientBuilder.socketTimeout(Duration.of(clientSettings.readTimeoutMillis, ChronoUnit.MILLIS)); if (Strings.hasText(clientSettings.proxyHost)) { applyProxyConfiguration(clientSettings, httpClientBuilder); } final var ec2ClientBuilder = getEc2ClientBuilder(); ec2ClientBuilder.credentialsProvider(getAwsCredentialsProvider(clientSettings)); ec2ClientBuilder.httpClientBuilder(httpClientBuilder); // Increase the number of retries in case of 5xx API responses ec2ClientBuilder.overrideConfiguration(b -> b.retryStrategy(c -> c.maxAttempts(10))); if (Strings.hasText(clientSettings.endpoint)) { LOGGER.debug("using explicit ec2 endpoint [{}]", clientSettings.endpoint); final var endpoint = Endpoint.builder().url(URI.create(clientSettings.endpoint)).build(); ec2ClientBuilder.endpointProvider(endpointParams -> CompletableFuture.completedFuture(endpoint)); } return ec2ClientBuilder.build(); } private static void applyProxyConfiguration(Ec2ClientSettings clientSettings, ApacheHttpClient.Builder httpClientBuilder) { final var uriBuilder = new URIBuilder(); uriBuilder.setScheme(clientSettings.proxyScheme.getSchemeString()) .setHost(clientSettings.proxyHost) .setPort(clientSettings.proxyPort); final URI proxyUri; try { proxyUri = uriBuilder.build(); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } httpClientBuilder.proxyConfiguration( ProxyConfiguration.builder() .endpoint(proxyUri) .scheme(clientSettings.proxyScheme.getSchemeString()) .username(clientSettings.proxyUsername) .password(clientSettings.proxyPassword) .build() ); } // exposed for tests Ec2ClientBuilder getEc2ClientBuilder() { return Ec2Client.builder(); } // exposed for tests ApacheHttpClient.Builder getHttpClientBuilder() { return ApacheHttpClient.builder(); } private static AwsCredentialsProvider getAwsCredentialsProvider(Ec2ClientSettings clientSettings) { final AwsCredentialsProvider credentialsProvider; final AwsCredentials credentials = clientSettings.credentials; if (credentials == null) { LOGGER.debug("Using default provider chain"); credentialsProvider = DefaultCredentialsProvider.create(); } else { LOGGER.debug("Using basic key/secret credentials"); credentialsProvider = StaticCredentialsProvider.create(credentials); } return credentialsProvider; } @Override public AmazonEc2Reference client() { final LazyInitializable<AmazonEc2Reference, ElasticsearchException> clientReference = this.lazyClientReference.get(); if (clientReference == null) { throw new IllegalStateException("Missing ec2 client configs"); } return clientReference.getOrCompute(); } /** * Refreshes the settings for the {@link Ec2Client} client. The new client will be built using these new settings. The old client is * usable until released. On release it will be destroyed instead of being returned to the cache. */ @Override public void refreshAndClearCache(Ec2ClientSettings clientSettings) { final LazyInitializable<AmazonEc2Reference, ElasticsearchException> newClient = new LazyInitializable<>( () -> new AmazonEc2Reference(buildClient(clientSettings)), AbstractRefCounted::incRef, AbstractRefCounted::decRef ); final LazyInitializable<AmazonEc2Reference, ElasticsearchException> oldClient = this.lazyClientReference.getAndSet(newClient); if (oldClient != null) { oldClient.reset(); } } @Override public void close() { final LazyInitializable<AmazonEc2Reference, ElasticsearchException> clientReference = this.lazyClientReference.getAndSet(null); if (clientReference != null) { clientReference.reset(); } } }
AwsEc2ServiceImpl
java
apache__camel
core/camel-base/src/main/java/org/apache/camel/impl/event/CamelContextSuspendingEvent.java
{ "start": 951, "end": 1360 }
class ____ extends AbstractContextEvent implements CamelEvent.CamelContextSuspendingEvent { private static final @Serial long serialVersionUID = 6761726800283072241L; public CamelContextSuspendingEvent(CamelContext source) { super(source); } @Override public String toString() { return "Suspending CamelContext: " + getContext().getName(); } }
CamelContextSuspendingEvent
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/vectorized/ArrowColumnVector.java
{ "start": 15583, "end": 16392 }
class ____ extends ArrowVectorAccessor { private final ListVector accessor; private final ArrowColumnVector arrayData; ArrayAccessor(ListVector vector) { super(vector); this.accessor = vector; this.arrayData = new ArrowColumnVector(vector.getDataVector()); } @Override final ColumnarArray getArray(int rowId) { int start = accessor.getElementStartIndex(rowId); int end = accessor.getElementEndIndex(rowId); return new ColumnarArray(arrayData, start, end - start); } } /** * Any call to "get" method will throw UnsupportedOperationException. * * Access struct values in a ArrowColumnVector doesn't use this accessor. Instead, it uses * getStruct() method defined in the parent class. Any call to "get" method in this
ArrayAccessor
java
google__guice
core/test/com/google/inject/errors/MissingImplementationErrorTest.java
{ "start": 8721, "end": 9454 }
class ____ extends AbstractModule { @Provides List<String> provideString() { throw new RuntimeException("not reachable"); } @Provides Dao provideInteger(List<? extends String> dep) { throw new RuntimeException("not reachable"); } } @Test public void testInjectionHasUnnecessaryExtendsClause() { CreationException exception = assertThrows( CreationException.class, () -> Guice.createInjector(new InjectionHasUnnecessaryExtendsClauseModule())); assertGuiceErrorEqualsIgnoreLineNumber( exception.getMessage(), "missing_implementation_has_unnecessary_extends_clause_java.txt"); } private static final
InjectionHasUnnecessaryExtendsClauseModule
java
spring-projects__spring-boot
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/ImplicitLayerResolver.java
{ "start": 796, "end": 1327 }
class ____ extends StandardLayers { private static final String SPRING_BOOT_LOADER_PREFIX = "org/springframework/boot/loader/"; @Override public Layer getLayer(String name) { if (name.startsWith(SPRING_BOOT_LOADER_PREFIX)) { return SPRING_BOOT_LOADER; } return APPLICATION; } @Override public Layer getLayer(Library library) { if (library.isLocal()) { return APPLICATION; } if (library.getName().contains("SNAPSHOT.")) { return SNAPSHOT_DEPENDENCIES; } return DEPENDENCIES; } }
ImplicitLayerResolver
java
google__dagger
dagger-android-processor/main/java/dagger/android/processor/BaseProcessingStep.java
{ "start": 1530, "end": 3910 }
class ____ implements XProcessingStep { @Override public final ImmutableSet<String> annotations() { return annotationClassNames().stream().map(XClassName::getCanonicalName).collect(toImmutableSet()); } // Subclass must ensure all annotated targets are of valid type. @Override public ImmutableSet<XElement> process( XProcessingEnv env, Map<String, ? extends Set<? extends XElement>> elementsByAnnotation) { ImmutableSet.Builder<XElement> deferredElements = ImmutableSet.builder(); inverse(elementsByAnnotation) .forEach( (element, annotations) -> { try { process(element, annotations); } catch (TypeNotPresentException e) { deferredElements.add(element); } }); return deferredElements.build(); } /** * Processes one element. If this method throws {@link TypeNotPresentException}, the element will * be deferred until the next round of processing. * * @param annotations the subset of {@link XProcessingStep#annotations()} that annotate {@code * element} */ protected abstract void process(XElement element, ImmutableSet<XClassName> annotations); private ImmutableMap<XElement, ImmutableSet<XClassName>> inverse( Map<String, ? extends Set<? extends XElement>> elementsByAnnotation) { ImmutableMap<String, XClassName> annotationClassNames = annotationClassNames().stream() .collect(toImmutableMap(XClassName::getCanonicalName, className -> className)); checkState( annotationClassNames.keySet().containsAll(elementsByAnnotation.keySet()), "Unexpected annotations for %s: %s", this.getClass().getCanonicalName(), difference(elementsByAnnotation.keySet(), annotationClassNames.keySet())); ImmutableSetMultimap.Builder<XElement, XClassName> builder = ImmutableSetMultimap.builder(); elementsByAnnotation.forEach( (annotationName, elementSet) -> elementSet.forEach( element -> builder.put(element, annotationClassNames.get(annotationName)))); return ImmutableMap.copyOf(Maps.transformValues(builder.build().asMap(), ImmutableSet::copyOf)); } /** Returns the set of annotations processed by this processing step. */ protected abstract Set<XClassName> annotationClassNames(); }
BaseProcessingStep
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java
{ "start": 16497, "end": 16528 }
class ____<S> { public
Enclosed
java
quarkusio__quarkus
extensions/mailer/runtime/src/test/java/io/quarkus/mailer/runtime/MailerTLSRegistryTest.java
{ "start": 433, "end": 4803 }
class ____ extends FakeSmtpTestBase { @Test public void sendMailWithCorrectTrustStore() { MailersRuntimeConfig mailersConfig = new DefaultMailersRuntimeConfig(new DefaultMailerRuntimeConfig() { @Override public Optional<String> tlsConfigurationName() { return Optional.of("my-mailer"); } @Override public Optional<Boolean> tls() { return Optional.of(true); } }); ReactiveMailer mailer = getMailer(mailersConfig, "my-mailer", new BaseTlsConfiguration() { @Override public TrustOptions getTrustStoreOptions() { JksOptions jksOptions = new JksOptions(); jksOptions.setPath("target/certs/mailer-certs-truststore.p12"); jksOptions.setPassword("password"); return jksOptions; } @Override public String getName() { return "test"; } }); startServer(new File("target/certs/mailer-certs-keystore.p12").getAbsolutePath()); mailer.send(getMail()).await().indefinitely(); } @Test public void sendMailWithDefaultTrustAll() { MailersRuntimeConfig mailersConfig = new DefaultMailersRuntimeConfig(); ReactiveMailer mailer = getMailer(mailersConfig, null, new BaseTlsConfiguration() { @Override public boolean isTrustAll() { return true; } @Override public String getName() { return "test"; } }); startServer(SERVER_JKS); mailer.send(getMail()).await().indefinitely(); } @Test public void sendMailWithNamedTrustAll() { MailersRuntimeConfig mailersConfig = new DefaultMailersRuntimeConfig(new DefaultMailerRuntimeConfig() { @Override public Optional<String> tlsConfigurationName() { return Optional.of("my-mailer"); } }); ReactiveMailer mailer = getMailer(mailersConfig, "my-mailer", new BaseTlsConfiguration() { @Override public boolean isTrustAll() { return true; } @Override public String getName() { return "test"; } }); startServer(SERVER_JKS); mailer.send(getMail()).await().indefinitely(); } @Test public void sendMailWithoutTrustStore() { MailersRuntimeConfig mailersConfig = new DefaultMailersRuntimeConfig(new DefaultMailerRuntimeConfig() { @Override public Optional<String> tlsConfigurationName() { return Optional.of("my-mailer"); } @Override public Optional<Boolean> tls() { return Optional.of(true); } }); startServer(SERVER_JKS); ReactiveMailer mailer = getMailer(mailersConfig, "my-mailer", new BaseTlsConfiguration() { @Override public String getName() { return "test"; } }); Assertions.assertThatThrownBy(() -> mailer.send(getMail()).await().indefinitely()) .isInstanceOf(CompletionException.class) .hasCauseInstanceOf(SSLHandshakeException.class); } @Test public void testWithWrongTlsName() { MailersRuntimeConfig mailersConfig = new DefaultMailersRuntimeConfig(new DefaultMailerRuntimeConfig() { @Override public Optional<String> tlsConfigurationName() { return Optional.of("missing-mailer-configuration"); } }); Assertions.assertThatThrownBy(() -> getMailer(mailersConfig, "my-mailer", new BaseTlsConfiguration() { @Override public TrustOptions getTrustStoreOptions() { JksOptions jksOptions = new JksOptions(); jksOptions.setPath("target/certs/mailer-certs-truststore.p12"); jksOptions.setPassword("password"); return jksOptions; } @Override public String getName() { return "test"; } })).hasMessageContaining("missing-mailer-configuration"); } }
MailerTLSRegistryTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AbstractContainerLogAggregationPolicy.java
{ "start": 1039, "end": 1187 }
class ____ no-op implementation for parseParameters. Polices // that don't need parameters can derive from this class. @Private public abstract
provides