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__flink
flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/row/ParquetRowDataWriter.java
{ "start": 11573, "end": 12254 }
class ____ implements FieldWriter { @Override public void write(RowData row, int ordinal) { writeInt(row.getInt(ordinal)); } @Override public void write(ArrayData arrayData, int ordinal) { writeInt(arrayData.getInt(ordinal)); } private void writeInt(int value) { recordConsumer.addInteger(value); } } /** * We only support INT96 bytes now, julianDay(4) + nanosOfDay(8). See * https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#timestamp * TIMESTAMP_MILLIS and TIMESTAMP_MICROS are the deprecated ConvertedType. */ private
IntWriter
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/frommap/MapToBeanImplicitMapper.java
{ "start": 333, "end": 516 }
interface ____ { MapToBeanImplicitMapper INSTANCE = Mappers.getMapper( MapToBeanImplicitMapper.class ); Target toTarget(Map<String, String> source);
MapToBeanImplicitMapper
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/metadata/MetadataTests.java
{ "start": 58806, "end": 59620 }
class ____ implements Metadata.ClusterCustom { @Override public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params params) { return Collections.emptyIterator(); } @Override public Diff<Metadata.ClusterCustom> diff(Metadata.ClusterCustom previousState) { return null; } @Override public EnumSet<Metadata.XContentContext> context() { return null; } @Override public String getWriteableName() { return null; } @Override public TransportVersion getMinimalSupportedVersion() { return null; } @Override public void writeTo(StreamOutput out) throws IOException { } } }
TestClusterCustomMetadata
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/FluxConcatIterableTest.java
{ "start": 1096, "end": 3726 }
class ____ { @Test public void arrayNull() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> { Flux.concat((Iterable<? extends Publisher<?>>) null); }); } final Publisher<Integer> source = Flux.range(1, 3); @Test public void normal() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.concat(Arrays.asList(source, source, source)).subscribe(ts); ts.assertValues(1, 2, 3, 1, 2, 3, 1, 2, 3) .assertComplete() .assertNoError(); } @Test public void normalBackpressured() { AssertSubscriber<Integer> ts = AssertSubscriber.create(0); Flux.concat(Arrays.asList(source, source, source)).subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); ts.request(1); ts.assertValues(1) .assertNoError() .assertNotComplete(); ts.request(4); ts.assertValues(1, 2, 3, 1, 2) .assertNoError() .assertNotComplete(); ts.request(10); ts.assertValues(1, 2, 3, 1, 2, 3, 1, 2, 3) .assertComplete() .assertNoError(); } @Test public void oneSourceIsNull() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.concat(Arrays.asList(source, null, source)).subscribe(ts); ts.assertValues(1, 2, 3) .assertNotComplete() .assertError(NullPointerException.class); } @Test public void singleSourceIsNull() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.concat(Arrays.asList((Publisher<Integer>) null)).subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertError(NullPointerException.class); } @Test public void scanOperator(){ FluxConcatIterable<Integer> test = new FluxConcatIterable<>(Arrays.asList(source, source, source)); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); } @Test public void scanSubscriber(){ CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null); List<Publisher<Integer>> publishers = Arrays.asList(source, source, source); FluxConcatIterable.ConcatIterableSubscriber<Integer> test = new FluxConcatIterable.ConcatIterableSubscriber<>(actual, publishers.iterator()); Subscription parent = Operators.emptySubscription(); test.onSubscribe(parent); test.missedRequested = 2; test.requested = 3; assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(5L); } }
FluxConcatIterableTest
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/errors/BinaryDecodeErrorTest.java
{ "start": 825, "end": 1460 }
class ____ { @RegisterExtension public static final QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot(root -> { root.addClasses(Echo.class, WSClient.class); }); @Inject Vertx vertx; @TestHTTPResource("echo") URI testUri; @Test void testError() { WSClient client = WSClient.create(vertx).connect(testUri); client.send(Buffer.buffer("1")); client.waitForMessages(1); assertEquals("Problem decoding: 1", client.getLastMessage().toString()); } @WebSocket(path = "/echo") public static
BinaryDecodeErrorTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java
{ "start": 37016, "end": 37173 }
class ____ { @Scheduled(fixedRate = 3, initialDelay = 1, timeUnit = TimeUnit.MINUTES) void fixedRate() { } } static
FixedRateWithInitialDelayInMinutes
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/PercentilesConfig.java
{ "start": 1446, "end": 3695 }
class ____ implements ToXContent, Writeable { public static int indexOfKey(double[] keys, double key) { return ArrayUtils.binarySearch(keys, key, 0.001); } private final PercentilesMethod method; PercentilesConfig(PercentilesMethod method) { this.method = method; } public static PercentilesConfig fromStream(StreamInput in) throws IOException { PercentilesMethod method = PercentilesMethod.readFromStream(in); return method.configFromStream(in); } public PercentilesMethod getMethod() { return method; } public abstract Aggregator createPercentilesAggregator( String name, ValuesSourceConfig config, AggregationContext context, Aggregator parent, double[] values, boolean keyed, DocValueFormat formatter, Map<String, Object> metadata ) throws IOException; public abstract InternalNumericMetricsAggregation.MultiValue createEmptyPercentilesAggregator( String name, double[] values, boolean keyed, DocValueFormat formatter, Map<String, Object> metadata ); abstract Aggregator createPercentileRanksAggregator( String name, ValuesSourceConfig config, AggregationContext context, Aggregator parent, double[] values, boolean keyed, DocValueFormat formatter, Map<String, Object> metadata ) throws IOException; public abstract InternalNumericMetricsAggregation.MultiValue createEmptyPercentileRanksAggregator( String name, double[] values, boolean keyed, DocValueFormat formatter, Map<String, Object> metadata ); @Override public void writeTo(StreamOutput out) throws IOException { out.writeEnum(method); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; PercentilesConfig other = (PercentilesConfig) obj; return method.equals(other.getMethod()); } @Override public int hashCode() { return Objects.hash(method); } public static final
PercentilesConfig
java
google__dagger
javatests/dagger/internal/codegen/MultipleRequestTest.java
{ "start": 1121, "end": 1421 }
class ____ {", " @Inject Dep() {}", "}"), CompilerTests.javaSource( "test.ConstructorInjectsMultiple", "package test;", "", "import javax.inject.Inject;", "", "
Dep
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/fields/RecursiveComparisonAssert_isEqualTo_java_objects_Test.java
{ "start": 951, "end": 1763 }
class ____ extends WithComparingFieldsIntrospectionStrategyBaseTest { @Test void should_describe_cause_of_equals_use() { // GIVEN two equal values of a type from a java package that are compared by reference IntSummaryStatistics actual = new IntSummaryStatistics(); IntSummaryStatistics expected = new IntSummaryStatistics(); // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).usingRecursiveComparison(recursiveComparisonConfiguration) .isEqualTo(expected)); // THEN then(assertionError).hasMessageContaining("Actual and expected value are both java types (java.util.IntSummaryStatistics) and thus were compared to with equals"); } }
RecursiveComparisonAssert_isEqualTo_java_objects_Test
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/service/query/ConfigChainRequestExtractorService.java
{ "start": 949, "end": 1061 }
class ____ initializing and retrieving the configuration query request extractor. * * @author Nacos */ public
for
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/config/TableConfigOptions.java
{ "start": 1501, "end": 1628 }
class ____ {@link org.apache.flink.configuration.ConfigOption}s used by table planner. * * <p>NOTE: All option keys in this
holds
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSQLServerTest.java
{ "start": 8998, "end": 9119 }
class ____ extends InheritanceRootEntity { @ManyToOne @JoinColumn public Match match; } }
InheritanceSecondChildEntity
java
apache__maven
impl/maven-di/src/test/java/org/apache/maven/di/impl/TypeUtilsTest.java
{ "start": 7273, "end": 7324 }
interface ____<A, B extends Integer> {} }
TestInterface
java
quarkusio__quarkus
extensions/redis-cache/runtime/src/main/java/io/quarkus/cache/redis/runtime/RedisCache.java
{ "start": 4155, "end": 5850 }
class ____ the value * @param defaultValue the default value * @param <K> the type of key * @param <V> the type of value * @return a Uni emitting the value cached under {@code key}, or {@code defaultValue} if there is no cached value */ <K, V> Uni<V> getOrDefault(K key, Class<V> clazz, V defaultValue); /** * Returns {@link Uni} that completes with a value present in the cache under the given {@code key}. * If there is no value in the cache under the key, the {@code Uni} completes with the given {@code defaultValue}. * * @param key the key * @param type type of the value * @param defaultValue the default value * @param <K> the type of key * @param <V> the type of value * @return a Uni emitting the value cached under {@code key}, or {@code defaultValue} if there is no cached value */ <K, V> Uni<V> getOrDefault(K key, TypeLiteral<V> type, V defaultValue); /** * Returns {@link Uni} that completes with a value present in the cache under the given {@code key}. * If there is no value in the cache under the key, the {@code Uni} completes with {@code null}. * * @param key the key * @param <K> the type of key * @param <V> the type of value * @return a Uni emitting the value cached under {@code key}, or {@code null} if there is no cached value */ <K, V> Uni<V> getOrNull(K key); /** * Returns {@link Uni} that completes with a value present in the cache under the given {@code key}. * If there is no value in the cache under the key, the {@code Uni} completes with {@code null}. * * @param key the key * @param clazz the
of
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/autodetect/ProcessContext.java
{ "start": 6027, "end": 6662 }
class ____ implements ProcessState { @Override public boolean setRunning(ProcessContext processContext, AutodetectCommunicator autodetectCommunicator) { LOGGER.debug("Process set to [running] while it was already in that state"); return false; } @Override public boolean setDying(ProcessContext processContext) { processContext.setState(new ProcessDyingState()); return true; } @Override public ProcessStateName getName() { return ProcessStateName.RUNNING; } } private static
ProcessRunningState
java
grpc__grpc-java
api/src/test/java/io/grpc/ServiceProvidersTestUtil.java
{ "start": 2415, "end": 3124 }
class ____ was not in hardcodedClassNames") .that(results).isEmpty(); assertWithMessage( "The Iterable did not attempt to load some classes from hardcodedClassNames") .that(notLoaded).isEmpty(); } finally { Thread.currentThread().setContextClassLoader(ccl); } } private static Iterator<?> invokeIteratorCallable( String callableClassName, ClassLoader cl) throws Exception { Class<?> klass = Class.forName(callableClassName, true, cl); Constructor<?> ctor = klass.getDeclaredConstructor(); Object instance = ctor.newInstance(); Method callMethod = klass.getMethod("call"); return (Iterator<?>) callMethod.invoke(instance); } }
that
java
alibaba__druid
core/src/test/java/com/alibaba/druid/pvt/pool/AsyncCloseTest1.java
{ "start": 636, "end": 2377 }
class ____ extends TestCase { protected DruidDataSource dataSource; private ExecutorService connExecutor; private ExecutorService closeExecutor; final AtomicInteger errorCount = new AtomicInteger(); private Logger log4jLog; private Level log4jOldLevel; private NoLoggingImpl noLoggingImpl; protected void setUp() throws Exception { Field logField = DruidDataSource.class.getDeclaredField("LOG"); logField.setAccessible(true); Log dataSourceLog = (Log) logField.get(null); if (dataSourceLog instanceof Log4jImpl) { this.log4jLog = ((Log4jImpl) dataSourceLog).getLog(); this.log4jOldLevel = this.log4jLog.getLevel(); this.log4jLog.setLevel(Level.FATAL); } else if (dataSourceLog instanceof NoLoggingImpl) { noLoggingImpl = (NoLoggingImpl) dataSourceLog; noLoggingImpl.setErrorEnabled(false); } dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:"); // dataSource.setAsyncCloseConnectionEnable(true); dataSource.setTestOnBorrow(false); dataSource.setMaxActive(16); connExecutor = Executors.newFixedThreadPool(128); closeExecutor = Executors.newFixedThreadPool(128); } protected void tearDown() throws Exception { dataSource.close(); if (log4jLog != null) { log4jLog.setLevel(log4jOldLevel); } else if (noLoggingImpl != null) { noLoggingImpl.setErrorEnabled(true); } } public void test_0() throws Exception { for (int i = 0; i < 16; ++i) { loop(); System.out.println("loop " + i + " done."); } }
AsyncCloseTest1
java
spring-projects__spring-boot
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java
{ "start": 1258, "end": 2742 }
class ____ { @AfterEach void preventRunFailuresFromPollutingLoggerContext() { ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)).getLoggerContext() .getTurboFilterList() .clear(); } @Test void missingUrl() { assertThatIllegalStateException().isThrownBy(this::doTest).withMessageContaining("No remote URL specified"); } @Test void malformedUrl() { assertThatIllegalStateException().isThrownBy(() -> doTest("::://wibble")) .withMessageContaining("Malformed URL '::://wibble'"); } @Test void multipleUrls() { assertThatIllegalStateException().isThrownBy(() -> doTest("http://localhost:8080", "http://localhost:9090")) .withMessageContaining("Multiple URLs specified"); } @Test void validUrl() { ApplicationContext context = doTest("http://localhost:8080"); assertThat(context.getEnvironment().getProperty("remoteUrl")).isEqualTo("http://localhost:8080"); } @Test void cleanValidUrl() { ApplicationContext context = doTest("http://localhost:8080/"); assertThat(context.getEnvironment().getProperty("remoteUrl")).isEqualTo("http://localhost:8080"); } private ApplicationContext doTest(String... args) { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); application.addListeners(new RemoteUrlPropertyExtractor()); return application.run(args); } @Configuration(proxyBeanMethods = false) static
RemoteUrlPropertyExtractorTests
java
quarkusio__quarkus
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/OpenshiftWithRoutePropertiesTest.java
{ "start": 540, "end": 3340 }
class ____ { @RegisterExtension static final QuarkusProdModeTest config = new QuarkusProdModeTest() .withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class)) .setApplicationName("openshift") .setApplicationVersion("0.1-SNAPSHOT") .withConfigurationResource("openshift-with-route.properties"); @ProdBuildResults private ProdModeTestResults prodModeTestResults; @Test public void assertGeneratedResources() throws IOException { Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes"); assertThat(kubernetesDir) .isDirectoryContaining(p -> p.getFileName().endsWith("openshift.json")) .isDirectoryContaining(p -> p.getFileName().endsWith("openshift.yml")); List<HasMetadata> openshiftList = DeserializationUtil .deserializeAsList(kubernetesDir.resolve("openshift.yml")); assertThat(openshiftList).filteredOn(h -> "Service".equals(h.getKind())).singleElement().satisfies(h -> { assertThat(h).isInstanceOfSatisfying(Service.class, s -> { assertThat(s.getMetadata()).satisfies(m -> { assertThat(m.getNamespace()).isEqualTo("applications"); }); assertThat(s.getSpec()).satisfies(spec -> { assertThat(spec.getSelector()).contains(entry("app.kubernetes.io/name", "test-it")); assertThat(spec.getPorts()).hasSize(1).anySatisfy(p -> { assertThat(p.getPort()).isEqualTo(80); assertThat(p.getTargetPort().getIntVal()).isEqualTo(9090); }); }); }); }); assertThat(openshiftList).filteredOn(i -> "Route".equals(i.getKind())).singleElement().satisfies(i -> { assertThat(i).isInstanceOfSatisfying(Route.class, r -> { //Check that labels and annotations are also applied to Routes (#10260) assertThat(r.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("test-it"); assertThat(m.getLabels()).contains(entry("foo", "bar")); assertThat(m.getAnnotations()).contains(entry("bar", "baz")); assertThat(m.getAnnotations()).contains(entry("kubernetes.io/tls-acme", "true")); assertThat(m.getNamespace()).isEqualTo("applications"); }); assertThat(r.getSpec().getPort().getTargetPort().getStrVal()).isEqualTo("http"); assertThat(r.getSpec().getHost()).isEqualTo("foo.bar.io"); assertThat(r.getSpec().getTls()).isNull(); }); }); } }
OpenshiftWithRoutePropertiesTest
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportGetDeploymentStatsAction.java
{ "start": 2142, "end": 17042 }
class ____ extends TransportTasksAction< TrainedModelDeploymentTask, GetDeploymentStatsAction.Request, GetDeploymentStatsAction.Response, AssignmentStats> { @Inject public TransportGetDeploymentStatsAction( TransportService transportService, ActionFilters actionFilters, ClusterService clusterService ) { super( GetDeploymentStatsAction.NAME, clusterService, transportService, actionFilters, GetDeploymentStatsAction.Request::new, AssignmentStats::new, transportService.getThreadPool().executor(ThreadPool.Names.MANAGEMENT) ); } @Override protected GetDeploymentStatsAction.Response newResponse( GetDeploymentStatsAction.Request request, List<AssignmentStats> taskResponse, List<TaskOperationFailure> taskOperationFailures, List<FailedNodeException> failedNodeExceptions ) { // group the stats by deployment and merge individual node stats var mergedNodeStatsByDeployment = taskResponse.stream() .collect(Collectors.toMap(AssignmentStats::getDeploymentId, Function.identity(), (l, r) -> { l.getNodeStats().addAll(r.getNodeStats()); return l; }, TreeMap::new)); List<AssignmentStats> bunchedAndSorted = new ArrayList<>(mergedNodeStatsByDeployment.values()); return new GetDeploymentStatsAction.Response( taskOperationFailures, failedNodeExceptions, bunchedAndSorted, bunchedAndSorted.size() ); } @Override protected void doExecute( Task task, GetDeploymentStatsAction.Request request, ActionListener<GetDeploymentStatsAction.Response> listener ) { final ClusterState clusterState = clusterService.state(); final TrainedModelAssignmentMetadata assignment = TrainedModelAssignmentMetadata.fromState(clusterState); String[] tokenizedRequestIds = Strings.tokenizeToStringArray(request.getDeploymentId(), ","); ExpandedIdsMatcher.SimpleIdsMatcher idsMatcher = new ExpandedIdsMatcher.SimpleIdsMatcher(tokenizedRequestIds); List<String> matchedIds = new ArrayList<>(); Set<String> taskNodes = new HashSet<>(); Map<TrainedModelAssignment, Map<String, RoutingInfo>> assignmentNonStartedRoutes = new HashMap<>(); for (var assignmentEntry : assignment.allAssignments().entrySet()) { String deploymentId = assignmentEntry.getKey(); if (idsMatcher.idMatches(deploymentId)) { matchedIds.add(deploymentId); taskNodes.addAll(Arrays.asList(assignmentEntry.getValue().getStartedNodes())); Map<String, RoutingInfo> routings = assignmentEntry.getValue() .getNodeRoutingTable() .entrySet() .stream() .filter(routingEntry -> RoutingState.STARTED.equals(routingEntry.getValue().getState()) == false) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); assignmentNonStartedRoutes.put(assignmentEntry.getValue(), routings); } } if (matchedIds.isEmpty()) { listener.onResponse( new GetDeploymentStatsAction.Response(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), 0L) ); return; } request.setNodes(taskNodes.toArray(String[]::new)); request.setExpandedIds(matchedIds); ActionListener<GetDeploymentStatsAction.Response> addFailedListener = listener.safeMap(response -> { var updatedResponse = addFailedRoutes(response, assignmentNonStartedRoutes, clusterState.nodes()); // Set the allocation state and reason if we have it for (AssignmentStats stats : updatedResponse.getStats().results()) { TrainedModelAssignment trainedModelAssignment = assignment.getDeploymentAssignment(stats.getDeploymentId()); if (trainedModelAssignment != null) { stats.setState(trainedModelAssignment.getAssignmentState()).setReason(trainedModelAssignment.getReason().orElse(null)); if (trainedModelAssignment.getNodeRoutingTable().isEmpty() == false && trainedModelAssignment.getNodeRoutingTable() .values() .stream() .allMatch(ri -> ri.getState().equals(RoutingState.FAILED))) { stats.setState(AssignmentState.FAILED); if (stats.getReason() == null) { stats.setReason("All node routes are failed; see node route reason for details"); } } if (trainedModelAssignment.getAssignmentState().isAnyOf(AssignmentState.STARTED, AssignmentState.STARTING)) { stats.setAllocationStatus(trainedModelAssignment.calculateAllocationStatus().orElse(null)); } } } return updatedResponse; }); super.doExecute(task, request, addFailedListener); } /** * Update the collected task responses with the non-started * assignment information. The result is the task responses * merged with the non-started model assignments. * * Where there is a merge collision for the pair {@code <model_id, node_id>} * the non-started assignments are used. * * @param tasksResponse All the responses from the tasks * @param assignmentNonStartedRoutes Non-started routes * @param nodes current cluster nodes * @return The result of merging tasksResponse and the non-started routes */ static GetDeploymentStatsAction.Response addFailedRoutes( GetDeploymentStatsAction.Response tasksResponse, Map<TrainedModelAssignment, Map<String, RoutingInfo>> assignmentNonStartedRoutes, DiscoveryNodes nodes ) { final Map<String, TrainedModelAssignment> deploymentToAssignmentWithNonStartedRoutes = assignmentNonStartedRoutes.keySet() .stream() .collect(Collectors.toMap(TrainedModelAssignment::getDeploymentId, Function.identity())); final List<AssignmentStats> updatedAssignmentStats = new ArrayList<>(); for (AssignmentStats stat : tasksResponse.getStats().results()) { if (deploymentToAssignmentWithNonStartedRoutes.containsKey(stat.getDeploymentId())) { // there is merging to be done Map<String, RoutingInfo> nodeToRoutingStates = assignmentNonStartedRoutes.get( deploymentToAssignmentWithNonStartedRoutes.get(stat.getDeploymentId()) ); List<AssignmentStats.NodeStats> updatedNodeStats = new ArrayList<>(); Set<String> visitedNodes = new HashSet<>(); for (var nodeStat : stat.getNodeStats()) { if (nodeToRoutingStates.containsKey(nodeStat.getNode().getId())) { // conflict as there is both a task response for the deployment/node pair // and we have a non-started routing entry. // Prefer the entry from assignmentNonStartedRoutes as we cannot be sure // of the state of the task - it may be starting, started, stopping, or stopped. RoutingInfo routingInfo = nodeToRoutingStates.get(nodeStat.getNode().getId()); updatedNodeStats.add( AssignmentStats.NodeStats.forNotStartedState( nodeStat.getNode(), routingInfo.getState(), routingInfo.getReason() ) ); } else { updatedNodeStats.add(nodeStat); } visitedNodes.add(nodeStat.getNode().getId()); } // add nodes from the failures that were not in the task responses for (var nodeRoutingState : nodeToRoutingStates.entrySet()) { if ((visitedNodes.contains(nodeRoutingState.getKey()) == false) && nodes.nodeExists(nodeRoutingState.getKey())) { updatedNodeStats.add( AssignmentStats.NodeStats.forNotStartedState( nodes.get(nodeRoutingState.getKey()), nodeRoutingState.getValue().getState(), nodeRoutingState.getValue().getReason() ) ); } } updatedNodeStats.sort(Comparator.comparing(n -> n.getNode().getId())); updatedAssignmentStats.add( new AssignmentStats( stat.getDeploymentId(), stat.getModelId(), stat.getThreadsPerAllocation(), stat.getNumberOfAllocations(), stat.getAdaptiveAllocationsSettings(), stat.getQueueCapacity(), stat.getCacheSize(), stat.getStartTime(), updatedNodeStats, stat.getPriority() ) ); } else { updatedAssignmentStats.add(stat); } } // Merge any models in the non-started that were not in the task responses for (var nonStartedEntries : assignmentNonStartedRoutes.entrySet()) { final TrainedModelAssignment assignment = nonStartedEntries.getKey(); final String deploymentId = assignment.getDeploymentId(); if (tasksResponse.getStats().results().stream().anyMatch(e -> deploymentId.equals(e.getDeploymentId())) == false) { // no tasks for this model so build the assignment stats from the non-started states List<AssignmentStats.NodeStats> nodeStats = new ArrayList<>(); for (var routingEntry : nonStartedEntries.getValue().entrySet()) { if (nodes.nodeExists(routingEntry.getKey())) { nodeStats.add( AssignmentStats.NodeStats.forNotStartedState( nodes.get(routingEntry.getKey()), routingEntry.getValue().getState(), routingEntry.getValue().getReason() ) ); } } nodeStats.sort(Comparator.comparing(n -> n.getNode().getId())); updatedAssignmentStats.add( new AssignmentStats( deploymentId, assignment.getModelId(), assignment.getTaskParams().getThreadsPerAllocation(), assignment.getTaskParams().getNumberOfAllocations(), assignment.getAdaptiveAllocationsSettings(), assignment.getTaskParams().getQueueCapacity(), assignment.getTaskParams().getCacheSize().orElse(null), assignment.getStartTime(), nodeStats, assignment.getTaskParams().getPriority() ) ); } } updatedAssignmentStats.sort(Comparator.comparing(AssignmentStats::getDeploymentId)); return new GetDeploymentStatsAction.Response( tasksResponse.getTaskFailures(), tasksResponse.getNodeFailures(), updatedAssignmentStats, updatedAssignmentStats.size() ); } @Override protected void taskOperation( CancellableTask actionTask, GetDeploymentStatsAction.Request request, TrainedModelDeploymentTask task, ActionListener<AssignmentStats> listener ) { Optional<ModelStats> stats = task.modelStats(); List<AssignmentStats.NodeStats> nodeStats = new ArrayList<>(); if (stats.isPresent()) { var presentValue = stats.get(); nodeStats.add( AssignmentStats.NodeStats.forStartedState( clusterService.localNode(), presentValue.inferenceCount(), presentValue.averageInferenceTime(), presentValue.averageInferenceTimeNoCacheHits(), presentValue.pendingCount(), presentValue.errorCount(), presentValue.cacheHitCount(), presentValue.rejectedExecutionCount(), presentValue.timeoutCount(), presentValue.lastUsed(), presentValue.startTime(), presentValue.threadsPerAllocation(), presentValue.numberOfAllocations(), presentValue.peakThroughput(), presentValue.throughputLastPeriod(), presentValue.avgInferenceTimeLastPeriod(), presentValue.cacheHitCountLastPeriod() ) ); } else { // if there are no stats the process is missing. // Either because it is starting or stopped nodeStats.add(AssignmentStats.NodeStats.forNotStartedState(clusterService.localNode(), RoutingState.STOPPED, "")); } TrainedModelAssignment assignment = TrainedModelAssignmentMetadata.fromState(clusterService.state()) .getDeploymentAssignment(task.getDeploymentId()); listener.onResponse( new AssignmentStats( task.getDeploymentId(), task.getParams().getModelId(), task.getParams().getThreadsPerAllocation(), assignment == null ? task.getParams().getNumberOfAllocations() : assignment.getTaskParams().getNumberOfAllocations(), assignment == null ? null : assignment.getAdaptiveAllocationsSettings(), task.getParams().getQueueCapacity(), task.getParams().getCacheSize().orElse(null), TrainedModelAssignmentMetadata.fromState(clusterService.state()) .getDeploymentAssignment(task.getDeploymentId()) .getStartTime(), nodeStats, task.getParams().getPriority() ) ); } }
TransportGetDeploymentStatsAction
java
quarkusio__quarkus
integration-tests/gradle/src/main/resources/inject-quarkus-app-properties/src/main/java/org/acme/ExampleResource.java
{ "start": 257, "end": 550 }
class ____ { @ConfigProperty(name = "my-app-name") String appName; @ConfigProperty(name = "quarkus.application.version") String appVersion; @GET @Produces(MediaType.TEXT_PLAIN) public String hello() { return appName + " " + appVersion; } }
ExampleResource
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/ReadFromImpl.java
{ "start": 1334, "end": 1637 }
class ____ { private static final Predicate<RedisNodeDescription> IS_UPSTREAM = node -> node.getRole().isUpstream(); private static final Predicate<RedisNodeDescription> IS_REPLICA = node -> node.getRole().isReplica(); /** * Read from upstream only. */ static final
ReadFromImpl
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FailoverAppenderTest.java
{ "start": 1498, "end": 3443 }
class ____ { @Test @LoggerContextSource("log4j-failover.xml") void testFailover(final LoggerContext context, @Named("List") final ListAppender app) { final Logger logger = context.getLogger("LoggerTest"); logger.error("This is a test"); List<LogEvent> events = app.getEvents(); assertNotNull(events); assertEquals(1, events.size(), "Incorrect number of events. Should be 1 is " + events.size()); app.clear(); logger.error("This is a test"); events = app.getEvents(); assertNotNull(events); assertEquals(1, events.size(), "Incorrect number of events. Should be 1 is " + events.size()); } @Test @LoggerContextSource("log4j-failover.xml") void testRecovery( final LoggerContext context, @Named("List") final ListAppender app, @Named("Once") final FailOnceAppender foApp) throws Exception { final Logger onceLogger = context.getLogger("Once"); onceLogger.error("Fail once"); onceLogger.error("Fail again"); List<LogEvent> events = app.getEvents(); assertNotNull(events); assertEquals(2, events.size(), "Incorrect number of events. Should be 2 is " + events.size()); app.clear(); Thread.sleep(1100); onceLogger.error("Fail after recovery interval"); onceLogger.error("Second log message"); events = app.getEvents(); assertEquals(0, events.size(), "Did not recover"); events = foApp.drainEvents(); assertEquals(2, events.size(), "Incorrect number of events in primary appender"); } @Test @LoggerContextSource("log4j-failover-location.xml") void testRequiresLocation(final LoggerContext context) { final FailoverAppender appender = context.getConfiguration().getAppender("Failover"); assertTrue(appender.requiresLocation()); } }
FailoverAppenderTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/SortedDocsProducer.java
{ "start": 1260, "end": 4782 }
class ____ { protected final String field; SortedDocsProducer(String field) { this.field = field; } /** * Visits all non-deleted documents in <code>iterator</code> and fills the provided <code>queue</code> * with the top composite buckets extracted from the collection. * Documents that contain a top composite bucket are added in the provided <code>builder</code> if it is not null. * * Returns true if the queue is full and the current <code>leadSourceBucket</code> did not produce any competitive * composite buckets. */ protected static boolean processBucket( CompositeValuesCollectorQueue queue, LeafReaderContext context, DocIdSetIterator iterator, Comparable<?> leadSourceBucket, @Nullable DocIdSetBuilder builder ) throws IOException { final int[] topCompositeCollected = new int[1]; final boolean[] hasCollected = new boolean[1]; final DocCountProvider docCountProvider = new DocCountProvider(); docCountProvider.setLeafReaderContext(context); final LeafBucketCollector queueCollector = new LeafBucketCollector() { int lastDoc = -1; // we need to add the matching document in the builder // so we build a bulk adder from the approximate cost of the iterator // and rebuild the adder during the collection if needed int remainingBits = (int) Math.min(iterator.cost(), Integer.MAX_VALUE); DocIdSetBuilder.BulkAdder adder = builder == null ? null : builder.grow(remainingBits); @Override public void collect(int doc, long bucket) throws IOException { hasCollected[0] = true; int docCount = docCountProvider.getDocCount(doc); if (queue.addIfCompetitive(docCount)) { topCompositeCollected[0]++; if (adder != null && doc != lastDoc) { if (remainingBits == 0) { // the cost approximation was lower than the real size, we need to grow the adder // by some numbers (128) to ensure that we can add the extra documents adder = builder.grow(128); remainingBits = 128; } adder.add(doc); remainingBits--; lastDoc = doc; } } } }; final Bits liveDocs = context.reader().getLiveDocs(); final LeafBucketCollector collector = queue.getLeafCollector(leadSourceBucket, context, queueCollector); while (iterator.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) { if (liveDocs == null || liveDocs.get(iterator.docID())) { collector.collect(iterator.docID()); } } if (queue.isFull() && hasCollected[0] && topCompositeCollected[0] == 0) { return true; } return false; } /** * Populates the queue with the composite buckets present in the <code>context</code>. * Returns the {@link DocIdSet} of the documents that contain a top composite bucket in this leaf or * {@link DocIdSet#EMPTY} if <code>fillDocIdSet</code> is false. */ abstract DocIdSet processLeaf(CompositeValuesCollectorQueue queue, LeafReaderContext context, boolean fillDocIdSet) throws IOException; }
SortedDocsProducer
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointFailureManagerTest.java
{ "start": 1348, "end": 7050 }
class ____ { @Test void testIgnoresPastCheckpoints() { TestFailJobCallback callback = new TestFailJobCallback(); CheckpointFailureManager failureManager = new CheckpointFailureManager(2, callback); CheckpointProperties checkpointProperties = forCheckpoint(NEVER_RETAIN_AFTER_TERMINATION); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CHECKPOINT_EXPIRED), 1L); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CHECKPOINT_EXPIRED), 2L); failureManager.handleCheckpointSuccess(2L); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CHECKPOINT_EXPIRED), 1L); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CHECKPOINT_EXPIRED), 3L); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CHECKPOINT_EXPIRED), 4L); assertThat(callback.getInvokeCounter()).isZero(); } @Test void testContinuousFailure() { TestFailJobCallback callback = new TestFailJobCallback(); CheckpointFailureManager failureManager = new CheckpointFailureManager(2, callback); CheckpointProperties checkpointProperties = forCheckpoint(NEVER_RETAIN_AFTER_TERMINATION); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.CHECKPOINT_DECLINED), 1); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.CHECKPOINT_DECLINED), 2); // ignore this failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.JOB_FAILOVER_REGION), 3); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.CHECKPOINT_DECLINED), 4); assertThat(callback.getInvokeCounter()).isOne(); } @Test void testBreakContinuousFailure() { TestFailJobCallback callback = new TestFailJobCallback(); CheckpointFailureManager failureManager = new CheckpointFailureManager(2, callback); CheckpointProperties checkpointProperties = forCheckpoint(NEVER_RETAIN_AFTER_TERMINATION); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.IO_EXCEPTION), 1); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.CHECKPOINT_DECLINED), 2); // ignore this failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.JOB_FAILOVER_REGION), 3); // reset failureManager.handleCheckpointSuccess(4); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CHECKPOINT_EXPIRED), 5); assertThat(callback.getInvokeCounter()).isZero(); } @Test void testTotalCountValue() { TestFailJobCallback callback = new TestFailJobCallback(); CheckpointProperties checkpointProperties = forCheckpoint(NEVER_RETAIN_AFTER_TERMINATION); CheckpointFailureManager failureManager = new CheckpointFailureManager(0, callback); for (CheckpointFailureReason reason : CheckpointFailureReason.values()) { failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(reason), -2); } // IO_EXCEPTION, CHECKPOINT_DECLINED, FINALIZE_CHECKPOINT_FAILURE, CHECKPOINT_EXPIRED and // CHECKPOINT_ASYNC_EXCEPTION assertThat(callback.getInvokeCounter()).isEqualTo(5); } @Test void testIgnoreOneCheckpointRepeatedlyCountMultiTimes() { TestFailJobCallback callback = new TestFailJobCallback(); CheckpointFailureManager failureManager = new CheckpointFailureManager(2, callback); CheckpointProperties checkpointProperties = forCheckpoint(NEVER_RETAIN_AFTER_TERMINATION); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.CHECKPOINT_DECLINED), 1); failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.CHECKPOINT_DECLINED), 2); // ignore this failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.JOB_FAILOVER_REGION), 3); // ignore repeatedly report from one checkpoint failureManager.handleJobLevelCheckpointException( checkpointProperties, new CheckpointException(CheckpointFailureReason.CHECKPOINT_DECLINED), 2); assertThat(callback.getInvokeCounter()).isZero(); } /** A failure handler callback for testing. */ private static
CheckpointFailureManagerTest
java
netty__netty
transport/src/main/java/io/netty/channel/EventLoopGroup.java
{ "start": 879, "end": 1898 }
interface ____ extends EventExecutorGroup { /** * Return the next {@link EventLoop} to use */ @Override EventLoop next(); /** * Register a {@link Channel} with this {@link EventLoop}. The returned {@link ChannelFuture} * will get notified once the registration was complete. */ ChannelFuture register(Channel channel); /** * Register a {@link Channel} with this {@link EventLoop} using a {@link ChannelFuture}. The passed * {@link ChannelFuture} will get notified once the registration was complete and also will get returned. */ ChannelFuture register(ChannelPromise promise); /** * Register a {@link Channel} with this {@link EventLoop}. The passed {@link ChannelFuture} * will get notified once the registration was complete and also will get returned. * * @deprecated Use {@link #register(ChannelPromise)} instead. */ @Deprecated ChannelFuture register(Channel channel, ChannelPromise promise); }
EventLoopGroup
java
spring-projects__spring-security
oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jose/jws/MacAlgorithm.java
{ "start": 1335, "end": 2205 }
enum ____ implements JwsAlgorithm { /** * HMAC using SHA-256 (Required) */ HS256(JwsAlgorithms.HS256), /** * HMAC using SHA-384 (Optional) */ HS384(JwsAlgorithms.HS384), /** * HMAC using SHA-512 (Optional) */ HS512(JwsAlgorithms.HS512); private final String name; MacAlgorithm(String name) { this.name = name; } /** * Returns the algorithm name. * @return the algorithm name */ @Override public String getName() { return this.name; } /** * Attempt to resolve the provided algorithm name to a {@code MacAlgorithm}. * @param name the algorithm name * @return the resolved {@code MacAlgorithm}, or {@code null} if not found */ public static MacAlgorithm from(String name) { for (MacAlgorithm algorithm : values()) { if (algorithm.getName().equals(name)) { return algorithm; } } return null; } }
MacAlgorithm
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/LockOnBoxedPrimitiveTest.java
{ "start": 945, "end": 1277 }
class ____ { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(LockOnBoxedPrimitive.class, getClass()); @Test public void detectsSynchronizedBoxedLocks() throws Exception { compilationHelper .addSourceLines( "Test.java", "
LockOnBoxedPrimitiveTest
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/SetMessageRequestModeRequestBody.java
{ "start": 993, "end": 2113 }
class ____ extends RemotingSerializable { private String topic; private String consumerGroup; private MessageRequestMode mode = MessageRequestMode.PULL; /* consumer working in pop mode could share the MessageQueues assigned to the N (N = popShareQueueNum) consumers following it in the cid list */ private int popShareQueueNum = 0; public SetMessageRequestModeRequestBody() { } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getConsumerGroup() { return consumerGroup; } public void setConsumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; } public MessageRequestMode getMode() { return mode; } public void setMode(MessageRequestMode mode) { this.mode = mode; } public int getPopShareQueueNum() { return popShareQueueNum; } public void setPopShareQueueNum(int popShareQueueNum) { this.popShareQueueNum = popShareQueueNum; } }
SetMessageRequestModeRequestBody
java
google__auto
value/src/main/java/com/google/auto/value/processor/AnnotationOutput.java
{ "start": 8044, "end": 8227 }
class ____ is // undefined, javac unhelpfully converts it into a string "<error>" and visits that instead. We // want to catch this case and defer processing to allow the
constant
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/path/PathAssert_hasSameFileSystemAs_Test.java
{ "start": 948, "end": 1360 }
class ____ extends PathAssertBaseTest { private final Path expectedPath = mock(Path.class); @Override protected PathAssert invoke_api_method() { return assertions.hasSameFileSystemAs(expectedPath); } @Override protected void verify_internal_effects() { verify(paths).assertHasSameFileSystemAs(getInfo(assertions), getActual(assertions), expectedPath); } }
PathAssert_hasSameFileSystemAs_Test
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/googlevertexai/completion/ThinkingConfig.java
{ "start": 1314, "end": 3514 }
class ____ implements Writeable, ToXContentFragment { public static final String THINKING_CONFIG_FIELD = "thinking_config"; public static final String THINKING_BUDGET_FIELD = "thinking_budget"; private final Integer thinkingBudget; /** * Constructor for an empty {@code ThinkingConfig} */ public ThinkingConfig() { this.thinkingBudget = null; } public ThinkingConfig(Integer thinkingBudget) { this.thinkingBudget = thinkingBudget; } public ThinkingConfig(StreamInput in) throws IOException { thinkingBudget = in.readOptionalVInt(); } public static ThinkingConfig fromMap(Map<String, Object> map, ValidationException validationException) { Map<String, Object> thinkingConfigSettings = removeFromMapOrDefaultEmpty(map, THINKING_CONFIG_FIELD); Integer thinkingBudget = ServiceUtils.extractOptionalInteger( thinkingConfigSettings, THINKING_BUDGET_FIELD, ModelConfigurations.TASK_SETTINGS, validationException ); return new ThinkingConfig(thinkingBudget); } public boolean isEmpty() { return thinkingBudget == null; } public Integer getThinkingBudget() { return thinkingBudget; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalVInt(thinkingBudget); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (thinkingBudget != null) { builder.startObject(THINKING_CONFIG_FIELD); builder.field(THINKING_BUDGET_FIELD, thinkingBudget); builder.endObject(); } return builder; } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; ThinkingConfig that = (ThinkingConfig) o; return Objects.equals(thinkingBudget, that.thinkingBudget); } @Override public int hashCode() { return Objects.hashCode(thinkingBudget); } @Override public String toString() { return Strings.toString(this); } }
ThinkingConfig
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertIsNegative_Test.java
{ "start": 1224, "end": 2818 }
class ____ extends BigIntegersBaseTest { @Test void should_succeed_since_actual_is_negative() { numbers.assertIsNegative(someInfo(), new BigInteger("-1")); } @Test void should_succeed_since_actual_is_negative_according_to_custom_comparison_strategy() { numbersWithComparatorComparisonStrategy.assertIsNegative(someInfo(), new BigInteger("-1")); } @Test void should_fail_since_actual_is_zero() { // WHEN var error = expectAssertionError(() -> numbersWithAbsValueComparisonStrategy.assertIsNegative(someInfo(), BigInteger.ZERO)); // THEN then(error).hasMessage(shouldBeLess(BigInteger.ZERO, BigInteger.ZERO, absValueComparisonStrategy).create()); } @Test void should_fail_since_actual_is_not_negative() { // WHEN var assertionError = expectAssertionError(() -> numbers.assertIsNegative(someInfo(), BigInteger.ONE)); // THEN then(assertionError).hasMessage(shouldBeLess(BigInteger.ONE, BigInteger.ZERO).create()); } @Test void should_fail_since_actual_is_not_negative_according_to_custom_comparison_strategy() { // WHEN var error = expectAssertionError(() -> numbersWithAbsValueComparisonStrategy.assertIsNegative(someInfo(), BigInteger.valueOf(-1))); // THEN then(error).hasMessage(shouldBeLess(BigInteger.valueOf(-1), BigInteger.ZERO, absValueComparisonStrategy).create()); } }
BigIntegers_assertIsNegative_Test
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/creation/instance/ObjenesisInstantiator.java
{ "start": 319, "end": 495 }
class ____ implements Instantiator { // TODO: in order to provide decent exception message when objenesis is not found, // have a constructor in this
ObjenesisInstantiator
java
google__dagger
javatests/dagger/hilt/android/processor/internal/aggregateddeps/TestInstallInTest.java
{ "start": 1189, "end": 1681 }
class ____ { // TODO(danysantiago): Migrate to hiltCompiler() after b/288893275 is fixed. @Test public void testMissingValues() { JavaFileObject testInstallInModule = JavaFileObjects.forSourceLines( "test.TestInstallInModule", "package test;", "", "import dagger.Module;", "import dagger.hilt.testing.TestInstallIn;", "", "@Module", "@TestInstallIn", "
TestInstallInTest
java
micronaut-projects__micronaut-core
http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/filter/HttpServerFilterExceptionHandlerTest.java
{ "start": 1978, "end": 2592 }
class ____ { private static final String SPEC_NAME = "FilterErrorHandlerTest"; @Test public void exceptionHandlerTest() throws IOException { assertion(HttpRequest.GET("/foo"), AssertionUtils.assertThrowsStatus(HttpStatus.UNPROCESSABLE_ENTITY)); } private static void assertion(HttpRequest<?> request, BiConsumer<ServerUnderTest, HttpRequest<?>> assertion) throws IOException { TestScenario.builder() .specName(SPEC_NAME) .request(request) .assertion(assertion) .run(); } static
HttpServerFilterExceptionHandlerTest
java
quarkusio__quarkus
extensions/grpc/deployment/src/test/java/io/quarkus/grpc/auth/GrpcLazyAuthCustomRootPathTest.java
{ "start": 138, "end": 586 }
class ____ extends GrpcAuthTestBase { @RegisterExtension static final QuarkusUnitTest config = createQuarkusUnitTest(""" quarkus.grpc.server.use-separate-server=false quarkus.grpc.clients.securityClient.host=localhost quarkus.grpc.clients.securityClient.port=8081 quarkus.http.root-path=/api quarkus.http.auth.proactive=false """, true); }
GrpcLazyAuthCustomRootPathTest
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/Symbol.java
{ "start": 6342, "end": 7309 }
class ____ or method corresponding to this symbol. Only used for {@link * #CONSTANT_FIELDREF_TAG}, {@link #CONSTANT_METHODREF_TAG}, {@link * #CONSTANT_INTERFACE_METHODREF_TAG}, {@link #CONSTANT_NAME_AND_TYPE_TAG}, {@link * #CONSTANT_METHOD_HANDLE_TAG}, {@link #CONSTANT_DYNAMIC_TAG} and {@link * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols. */ final String name; /** * The string value of this symbol. This is: * * <ul> * <li>a field or method descriptor for {@link #CONSTANT_FIELDREF_TAG}, {@link * #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG}, {@link * #CONSTANT_NAME_AND_TYPE_TAG}, {@link #CONSTANT_METHOD_HANDLE_TAG}, {@link * #CONSTANT_METHOD_TYPE_TAG}, {@link #CONSTANT_DYNAMIC_TAG} and {@link * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols, * <li>an arbitrary string for {@link #CONSTANT_UTF8_TAG} and {@link #CONSTANT_STRING_TAG} * symbols, * <li>an internal
field
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_5.java
{ "start": 767, "end": 1019 }
class ____ extends AbstractDTO { private String field; public String getField() { return field; } public void setField(String field) { this.field = field; } } public static
Payload
java
apache__flink
flink-end-to-end-tests/flink-sql-client-test/src/main/java/org/apache/flink/table/toolbox/TestSourceFunction.java
{ "start": 1835, "end": 3840 }
class ____ implements SourceFunction<RowData> { public static final List<List<Object>> DATA = new ArrayList<>(); static { DATA.add(Arrays.asList(StringData.fromString("Bob"), 1L, TimestampData.fromEpochMillis(1))); DATA.add( Arrays.asList( StringData.fromString("Alice"), 2L, TimestampData.fromEpochMillis(2))); } private final WatermarkStrategy<RowData> watermarkStrategy; public TestSourceFunction(WatermarkStrategy<RowData> watermarkStrategy) { this.watermarkStrategy = watermarkStrategy; } private volatile boolean isRunning = true; @Override public void run(SourceContext<RowData> ctx) { WatermarkGenerator<RowData> generator = watermarkStrategy.createWatermarkGenerator( new WatermarkGeneratorSupplier.Context() { @Override public MetricGroup getMetricGroup() { return null; } @Override public RelativeClock getInputActivityClock() { return SystemClock.getInstance(); } }); WatermarkOutput output = new TestWatermarkOutput(ctx); int rowDataSize = DATA.get(0).size(); int index = 0; while (index < DATA.size() && isRunning) { List<Object> list = DATA.get(index); GenericRowData row = new GenericRowData(rowDataSize); for (int i = 0; i < rowDataSize; i++) { row.setField(i, list.get(i)); } ctx.collect(row); index++; generator.onEvent(row, Long.MIN_VALUE, output); generator.onPeriodicEmit(output); } ctx.close(); } @Override public void cancel() { isRunning = false; } private static
TestSourceFunction
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/web/configurers/ChannelSecurityConfigurer.java
{ "start": 6097, "end": 7773 }
class ____ extends AbstractConfigAttributeRequestMatcherRegistry<RequiresChannelUrl> { private ChannelRequestMatcherRegistry(ApplicationContext context) { setApplicationContext(context); } @Override protected RequiresChannelUrl chainRequestMatchersInternal(List<RequestMatcher> requestMatchers) { return new RequiresChannelUrl(requestMatchers); } /** * Adds an {@link ObjectPostProcessor} for this class. * @param objectPostProcessor * @return the {@link ChannelSecurityConfigurer} for further customizations */ public ChannelRequestMatcherRegistry withObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) { addObjectPostProcessor(objectPostProcessor); return this; } /** * Sets the {@link ChannelProcessor} instances to use in * {@link ChannelDecisionManagerImpl} * @param channelProcessors * @return the {@link ChannelSecurityConfigurer} for further customizations */ public ChannelRequestMatcherRegistry channelProcessors(List<ChannelProcessor> channelProcessors) { ChannelSecurityConfigurer.this.channelProcessors = channelProcessors; return this; } /** * Sets the {@link RedirectStrategy} instances to use in * {@link RetryWithHttpEntryPoint} and {@link RetryWithHttpsEntryPoint} * @param redirectStrategy * @return the {@link ChannelSecurityConfigurer} for further customizations */ public ChannelRequestMatcherRegistry redirectStrategy(RedirectStrategy redirectStrategy) { ChannelSecurityConfigurer.this.redirectStrategy = redirectStrategy; return this; } } /** * @deprecated no replacement planned */ @Deprecated public
ChannelRequestMatcherRegistry
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/array/FloatPrimitiveArraySerializer.java
{ "start": 3579, "end": 3794 }
class ____ extends SimpleTypeSerializerSnapshot<float[]> { public FloatPrimitiveArraySerializerSnapshot() { super(() -> INSTANCE); } } }
FloatPrimitiveArraySerializerSnapshot
java
apache__camel
components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/service/WordpressServiceTaxonomy.java
{ "start": 1020, "end": 1210 }
interface ____ extends WordpressService { Map<String, Taxonomy> list(Context context, String postType); Taxonomy retrieve(Context context, String taxonomy); }
WordpressServiceTaxonomy
java
netty__netty
codec-http3/src/main/java/io/netty/handler/codec/http3/Http3Exception.java
{ "start": 833, "end": 1919 }
class ____ extends Exception { private final Http3ErrorCode errorCode; /** * Create a new instance. * * @param errorCode the {@link Http3ErrorCode} that caused this exception. * @param message the message to include. */ public Http3Exception(Http3ErrorCode errorCode, @Nullable String message) { super(message); this.errorCode = ObjectUtil.checkNotNull(errorCode, "errorCode"); } /** * Create a new instance. * * @param errorCode the {@link Http3ErrorCode} that caused this exception. * @param message the message to include. * @param cause the {@link Throwable} to wrap. */ public Http3Exception(Http3ErrorCode errorCode, String message, @Nullable Throwable cause) { super(message, cause); this.errorCode = ObjectUtil.checkNotNull(errorCode, "errorCode"); } /** * Returns the related {@link Http3ErrorCode}. * * @return the {@link Http3ErrorCode}. */ public Http3ErrorCode errorCode() { return errorCode; } }
Http3Exception
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/util/TestPathHelper.java
{ "start": 3025, "end": 3097 }
class ____ URL to a URI", e ); } } private TestPathHelper() { } }
root
java
quarkusio__quarkus
extensions/oidc/runtime/src/main/java/io/quarkus/oidc/OidcTenantConfig.java
{ "start": 102779, "end": 103957 }
enum ____ { /** * A {@code WEB_APP} is a client that serves pages, usually a front-end application. For this type of client the * Authorization Code Flow is defined as the preferred method for authenticating users. */ WEB_APP, /** * A {@code SERVICE} is a client that has a set of protected HTTP resources, usually a backend application following the * RESTful Architectural Design. For this type of client, the Bearer Authorization method is defined as the preferred * method for authenticating and authorizing users. */ SERVICE, /** * A combined {@code SERVICE} and {@code WEB_APP} client. * For this type of client, the Bearer Authorization method is used if the Authorization header is set * and Authorization Code Flow - if not. */ HYBRID } /** * Well known OpenId Connect provider identifier * * @deprecated use the {@link #provider()} method instead */ @Deprecated(since = "3.18", forRemoval = true) public Optional<Provider> provider = Optional.empty(); public static
ApplicationType
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest69.java
{ "start": 976, "end": 15173 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "CREATE TABLE \"SC01\".\"TB01\" \n" + " (\t\"KPPZXH\" VARCHAR2(80) NOT NULL ENABLE, \n" + "\t\"NSRDZDAH\" VARCHAR2(80) NOT NULL ENABLE, \n" + "\t\"NSRSBH\" VARCHAR2(80) DEFAULT '', \n" + "\t\"NSRMC\" VARCHAR2(160) DEFAULT '', \n" + "\t\"KPFDZJDH\" VARCHAR2(400) DEFAULT '', \n" + "\t\"KPFYHJZH\" VARCHAR2(400) DEFAULT '', \n" + "\t\"FPZLDM\" VARCHAR2(20) NOT NULL ENABLE, \n" + "\t\"DZFPHM\" VARCHAR2(40), \n" + "\t\"KPRQ\" DATE NOT NULL ENABLE, \n" + "\t\"HYFL\" VARCHAR2(40) NOT NULL ENABLE, \n" + "\t\"SPFNSRMC\" VARCHAR2(400) DEFAULT '', \n" + "\t\"SPFYHJZH\" VARCHAR2(400) DEFAULT '', \n" + "\t\"HJ\" NUMBER(20,2) DEFAULT 0, \n" + "\t\"SL\" NUMBER(20,2) DEFAULT 0, \n" + "\t\"SE\" NUMBER(20,2) DEFAULT 0, \n" + "\t\"KPR\" VARCHAR2(40) DEFAULT '', \n" + "\t\"SKR\" VARCHAR2(40) DEFAULT '', \n" + "\t\"LRRQ\" DATE, \n" + "\t\"ZFBZ\" CHAR(1) DEFAULT 'N' NOT NULL ENABLE, \n" + "\t\"YJBZ\" CHAR(1) DEFAULT 'N' NOT NULL ENABLE, \n" + "\t\"GHFQYLX\" VARCHAR2(20), \n" + "\t\"SPFDZJDH\" VARCHAR2(400), \n" + "\t\"SPFNSRSBH\" VARCHAR2(60), \n" + "\t\"FPCJBZ\" CHAR(1), \n" + "\t\"FPBZ\" CHAR(1) DEFAULT '0', \n" + "\t\"JSJE\" NUMBER(20,2), \n" + "\t\"ZJLX\" VARCHAR2(20), \n" + "\t\"KJFSBH\" VARCHAR2(40), \n" + "\t\"SQBHM\" VARCHAR2(160), \n" + "\t\"WSPZHM\" VARCHAR2(80), \n" + "\t\"LZFPHM\" VARCHAR2(40), \n" + "\t\"HCJE\" NUMBER(20,2) DEFAULT 0, \n" + "\t\"XHFQYLX_DM\" VARCHAR2(20), \n" + "\t\"YNSE\" NUMBER(20,2), \n" + "\t\"BZ\" VARCHAR2(600), \n" + "\t\"ZFYY\" VARCHAR2(20), \n" + "\t\"HCYY\" VARCHAR2(20), \n" + "\t\"ZFRQ\" DATE, \n" + "\t\"FPZL\" VARCHAR2(20), \n" + "\t\"SWJG_DM\" VARCHAR2(40), \n" + "\t\"HTHM\" VARCHAR2(160), \n" + "\t\"XYZHS\" VARCHAR2(160), \n" + "\t\"JGRQ\" DATE, \n" + "\t\"SHBZ\" VARCHAR2(40), \n" + "\t\"BIZHONG\" VARCHAR2(40), \n" + "\t\"DKJE\" NUMBER(20,2), \n" + "\t\"DSWSPZHM\" VARCHAR2(80), \n" + "\t\"DKYF\" DATE, \n" + "\t\"JGTK\" VARCHAR2(200), \n" + "\t\"HXDH\" VARCHAR2(80), \n" + "\t\"HL\" NUMBER(20,6), \n" + "\t\"LAJE\" NUMBER(20,2), \n" + "\t\"HC_LCBZ\" CHAR(1), \n" + "\t\"SPR_BHYY\" VARCHAR2(400), \n" + "\t\"CONTENT\" BLOB, \n" + "\t\"ZF_LCBZ\" CHAR(1), \n" + "\t\"FPDM\" VARCHAR2(40), \n" + "\t\"FPHM\" VARCHAR2(40), \n" + "\t\"GHFSJH\" VARCHAR2(30), \n" + "\t\"GHFDZYX\" VARCHAR2(100), \n" + "\t\"GHFZH\" VARCHAR2(100), \n" + "\t\"KPLX\" VARCHAR2(2), \n" + "\t\"JSHJ\" NUMBER(18,2), \n" + "\t\"HJJE\" NUMBER(18,2), \n" + "\t\"HJSE\" NUMBER(18,2), \n" + "\t\"YFPDM\" VARCHAR2(24), \n" + "\t\"YFPHM\" VARCHAR2(16), \n" + "\t\"FHR\" VARCHAR2(16), \n" + "\t\"EWM\" VARCHAR2(4000), \n" + "\t\"FPMW\" VARCHAR2(224), \n" + "\t\"JYM\" VARCHAR2(40), \n" + "\t\"JQBH\" VARCHAR2(24), \n" + "\t\"ERPTID\" VARCHAR2(80), \n" + "\t\"DSPTDM\" VARCHAR2(40), \n" + "\t CONSTRAINT \"PK_FP_TY_KP_MFP1\" PRIMARY KEY (\"KPPZXH\")\n" + " USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS NOLOGGING \n" + " STORAGE(INITIAL 40960 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n" + " PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" + " BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" + " TABLESPACE \"DZFP_HWXS1_IDX\" ENABLE\n" + " ) SEGMENT CREATION IMMEDIATE \n" + " PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" + " NOCOMPRESS LOGGING\n" + " STORAGE(INITIAL 40960 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n" + " PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" + " BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" + " TABLESPACE \"DZFP_HWXS1_IDX\" \n" + " LOB (\"CONTENT\") STORE AS BASICFILE \"DZFP_HWXS1_IDX\"(\n" + " TABLESPACE \"DZFP_HWXS1_IDX\" ENABLE STORAGE IN ROW CHUNK 8192 PCTVERSION 10\n" + " NOCACHE LOGGING \n" + " STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n" + " PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" + " BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)) "; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(74, visitor.getColumns().size()); { String text = SQLUtils.toOracleString(stmt); assertEquals("CREATE TABLE \"SC01\".\"TB01\" (\n" + "\t\"KPPZXH\" VARCHAR2(80) NOT NULL ENABLE,\n" + "\t\"NSRDZDAH\" VARCHAR2(80) NOT NULL ENABLE,\n" + "\t\"NSRSBH\" VARCHAR2(80) DEFAULT NULL,\n" + "\t\"NSRMC\" VARCHAR2(160) DEFAULT NULL,\n" + "\t\"KPFDZJDH\" VARCHAR2(400) DEFAULT NULL,\n" + "\t\"KPFYHJZH\" VARCHAR2(400) DEFAULT NULL,\n" + "\t\"FPZLDM\" VARCHAR2(20) NOT NULL ENABLE,\n" + "\t\"DZFPHM\" VARCHAR2(40),\n" + "\t\"KPRQ\" DATE NOT NULL ENABLE,\n" + "\t\"HYFL\" VARCHAR2(40) NOT NULL ENABLE,\n" + "\t\"SPFNSRMC\" VARCHAR2(400) DEFAULT NULL,\n" + "\t\"SPFYHJZH\" VARCHAR2(400) DEFAULT NULL,\n" + "\t\"HJ\" NUMBER(20, 2) DEFAULT 0,\n" + "\t\"SL\" NUMBER(20, 2) DEFAULT 0,\n" + "\t\"SE\" NUMBER(20, 2) DEFAULT 0,\n" + "\t\"KPR\" VARCHAR2(40) DEFAULT NULL,\n" + "\t\"SKR\" VARCHAR2(40) DEFAULT NULL,\n" + "\t\"LRRQ\" DATE,\n" + "\t\"ZFBZ\" CHAR(1) DEFAULT 'N' NOT NULL ENABLE,\n" + "\t\"YJBZ\" CHAR(1) DEFAULT 'N' NOT NULL ENABLE,\n" + "\t\"GHFQYLX\" VARCHAR2(20),\n" + "\t\"SPFDZJDH\" VARCHAR2(400),\n" + "\t\"SPFNSRSBH\" VARCHAR2(60),\n" + "\t\"FPCJBZ\" CHAR(1),\n" + "\t\"FPBZ\" CHAR(1) DEFAULT '0',\n" + "\t\"JSJE\" NUMBER(20, 2),\n" + "\t\"ZJLX\" VARCHAR2(20),\n" + "\t\"KJFSBH\" VARCHAR2(40),\n" + "\t\"SQBHM\" VARCHAR2(160),\n" + "\t\"WSPZHM\" VARCHAR2(80),\n" + "\t\"LZFPHM\" VARCHAR2(40),\n" + "\t\"HCJE\" NUMBER(20, 2) DEFAULT 0,\n" + "\t\"XHFQYLX_DM\" VARCHAR2(20),\n" + "\t\"YNSE\" NUMBER(20, 2),\n" + "\t\"BZ\" VARCHAR2(600),\n" + "\t\"ZFYY\" VARCHAR2(20),\n" + "\t\"HCYY\" VARCHAR2(20),\n" + "\t\"ZFRQ\" DATE,\n" + "\t\"FPZL\" VARCHAR2(20),\n" + "\t\"SWJG_DM\" VARCHAR2(40),\n" + "\t\"HTHM\" VARCHAR2(160),\n" + "\t\"XYZHS\" VARCHAR2(160),\n" + "\t\"JGRQ\" DATE,\n" + "\t\"SHBZ\" VARCHAR2(40),\n" + "\t\"BIZHONG\" VARCHAR2(40),\n" + "\t\"DKJE\" NUMBER(20, 2),\n" + "\t\"DSWSPZHM\" VARCHAR2(80),\n" + "\t\"DKYF\" DATE,\n" + "\t\"JGTK\" VARCHAR2(200),\n" + "\t\"HXDH\" VARCHAR2(80),\n" + "\t\"HL\" NUMBER(20, 6),\n" + "\t\"LAJE\" NUMBER(20, 2),\n" + "\t\"HC_LCBZ\" CHAR(1),\n" + "\t\"SPR_BHYY\" VARCHAR2(400),\n" + "\t\"CONTENT\" BLOB,\n" + "\t\"ZF_LCBZ\" CHAR(1),\n" + "\t\"FPDM\" VARCHAR2(40),\n" + "\t\"FPHM\" VARCHAR2(40),\n" + "\t\"GHFSJH\" VARCHAR2(30),\n" + "\t\"GHFDZYX\" VARCHAR2(100),\n" + "\t\"GHFZH\" VARCHAR2(100),\n" + "\t\"KPLX\" VARCHAR2(2),\n" + "\t\"JSHJ\" NUMBER(18, 2),\n" + "\t\"HJJE\" NUMBER(18, 2),\n" + "\t\"HJSE\" NUMBER(18, 2),\n" + "\t\"YFPDM\" VARCHAR2(24),\n" + "\t\"YFPHM\" VARCHAR2(16),\n" + "\t\"FHR\" VARCHAR2(16),\n" + "\t\"EWM\" VARCHAR2(4000),\n" + "\t\"FPMW\" VARCHAR2(224),\n" + "\t\"JYM\" VARCHAR2(40),\n" + "\t\"JQBH\" VARCHAR2(24),\n" + "\t\"ERPTID\" VARCHAR2(80),\n" + "\t\"DSPTDM\" VARCHAR2(40),\n" + "\tCONSTRAINT \"PK_FP_TY_KP_MFP1\" PRIMARY KEY (\"KPPZXH\")\n" + "\t\tUSING INDEX\n" + "\t\tPCTFREE 10\n" + "\t\tINITRANS 2\n" + "\t\tMAXTRANS 255\n" + "\t\tNOLOGGING\n" + "\t\tTABLESPACE \"DZFP_HWXS1_IDX\"\n" + "\t\tSTORAGE (\n" + "\t\t\tINITIAL 40960\n" + "\t\t\tNEXT 1048576\n" + "\t\t\tMINEXTENTS 1\n" + "\t\t\tMAXEXTENTS 2147483645\n" + "\t\t\tPCTINCREASE 0\n" + "\t\t\tFREELISTS 1\n" + "\t\t\tFREELIST GROUPS 1\n" + "\t\t\tBUFFER_POOL DEFAULT\n" + "\t\t\tFLASH_CACHE DEFAULT\n" + "\t\t\tCELL_FLASH_CACHE DEFAULT\n" + "\t\t)\n" + "\t\tCOMPUTE STATISTICS\n" + "\t\tENABLE\n" + ")\n" + "PCTFREE 10\n" + "PCTUSED 40\n" + "INITRANS 1\n" + "MAXTRANS 255\n" + "NOCOMPRESS\n" + "LOGGING\n" + "TABLESPACE \"DZFP_HWXS1_IDX\"\n" + "STORAGE (\n" + "\tINITIAL 40960\n" + "\tNEXT 1048576\n" + "\tMINEXTENTS 1\n" + "\tMAXEXTENTS 2147483645\n" + "\tPCTINCREASE 0\n" + "\tFREELISTS 1\n" + "\tFREELIST GROUPS 1\n" + "\tBUFFER_POOL DEFAULT\n" + "\tFLASH_CACHE DEFAULT\n" + "\tCELL_FLASH_CACHE DEFAULT\n" + ")\n" + "LOB (\"CONTENT\") STORE AS BASICFILE \"DZFP_HWXS1_IDX\" (\n" + "\tLOGGING\n" + "\tTABLESPACE \"DZFP_HWXS1_IDX\"\n" + "\tSTORAGE (\n" + "\t\tINITIAL 1048576\n" + "\t\tNEXT 1048576\n" + "\t\tMINEXTENTS 1\n" + "\t\tMAXEXTENTS 2147483645\n" + "\t\tPCTINCREASE 0\n" + "\t\tFREELISTS 1\n" + "\t\tFREELIST GROUPS 1\n" + "\t\tBUFFER_POOL DEFAULT\n" + "\t\tFLASH_CACHE DEFAULT\n" + "\t\tCELL_FLASH_CACHE DEFAULT\n" + "\t)\n" + "\tENABLE STORAGE IN ROW\n" + "\tCHUNK 8192\n" + "\tNOCACHE\n" + ")", text); } // assertTrue(visitor.getColumns().contains(new TableStat.Column("acduser.vw_acd_info", "xzqh"))); // assertTrue(visitor.getOrderByColumns().contains(new TableStat.Column("employees", "last_name"))); } }
OracleSelectTest69
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/jdk/EnumTypingTest.java
{ "start": 736, "end": 796 }
enum ____ implements EnumInterface { A, B }; static
Tag
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/mixed/ObservableConcatMapMaybe.java
{ "start": 1459, "end": 2303 }
class ____<T, R> extends Observable<R> { final Observable<T> source; final Function<? super T, ? extends MaybeSource<? extends R>> mapper; final ErrorMode errorMode; final int prefetch; public ObservableConcatMapMaybe(Observable<T> source, Function<? super T, ? extends MaybeSource<? extends R>> mapper, ErrorMode errorMode, int prefetch) { this.source = source; this.mapper = mapper; this.errorMode = errorMode; this.prefetch = prefetch; } @Override protected void subscribeActual(Observer<? super R> observer) { if (!ScalarXMapZHelper.tryAsMaybe(source, mapper, observer)) { source.subscribe(new ConcatMapMaybeMainObserver<>(observer, mapper, prefetch, errorMode)); } } static final
ObservableConcatMapMaybe
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/pagination/DB2LimitHandler.java
{ "start": 461, "end": 943 }
class ____ extends OffsetFetchLimitHandler { public static final DB2LimitHandler INSTANCE = new DB2LimitHandler(); public DB2LimitHandler() { super(true); } @Override String insert(String offsetFetch, String sql) { //on DB2, offset/fetch comes after all the //various "for update"ish clauses //see https://www.ibm.com/support/knowledgecenter/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0000879.html return super.insertAtEnd( offsetFetch, sql ); } }
DB2LimitHandler
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/integration/MockitoBeanWithMultipleExistingBeansAndOnePrimaryAndOneConflictingQualifierIntegrationTests.java
{ "start": 2739, "end": 2793 }
class ____ { } @Component("baseService") static
Config
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/subclass/Cat.java
{ "start": 429, "end": 745 }
class ____ extends Animal { @ManyToMany @JoinTable( name = "cat_toys", joinColumns = @JoinColumn(name = "cat_name", referencedColumnName = "name") ) private List<Toy> toys = new ArrayList<>(); public List<Toy> getToys() { return toys; } public void setToys(List<Toy> toys) { this.toys = toys; } }
Cat
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/eventbus/impl/codecs/JsonArrayMessageCodec.java
{ "start": 644, "end": 1336 }
class ____ implements MessageCodec<JsonArray, JsonArray> { @Override public void encodeToWire(Buffer buffer, JsonArray jsonArray) { Buffer encoded = jsonArray.toBuffer(); buffer.appendInt(encoded.length()); buffer.appendBuffer(encoded); } @Override public JsonArray decodeFromWire(int pos, Buffer buffer) { int length = buffer.getInt(pos); pos += 4; return new JsonArray(buffer.slice(pos, pos + length)); } @Override public JsonArray transform(JsonArray jsonArray) { return jsonArray.copy(); } @Override public String name() { return "jsonarray"; } @Override public byte systemCodecID() { return 14; } }
JsonArrayMessageCodec
java
google__dagger
javatests/dagger/internal/codegen/SubcomponentValidationTest.java
{ "start": 9112, "end": 9434 }
interface ____ {", " ChildComponent newChildComponent(TestModule testModule);", "}"); Source childComponentFile = CompilerTests.javaSource("test.ChildComponent", "package test;", "", "import dagger.Subcomponent;", "", "@Subcomponent", "
TestComponent
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/ignore/expand/FlattenedToolBox.java
{ "start": 237, "end": 1341 }
class ____ { private String brand; private String hammerDescription; private Integer hammerSize; private Boolean wrenchIsBahco; private String wrenchDescription; public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getHammerDescription() { return hammerDescription; } public void setHammerDescription(String hammerDescription) { this.hammerDescription = hammerDescription; } public Integer getHammerSize() { return hammerSize; } public void setHammerSize(Integer hammerSize) { this.hammerSize = hammerSize; } public Boolean getWrenchIsBahco() { return wrenchIsBahco; } public void setWrenchIsBahco(Boolean wrenchIsBahco) { this.wrenchIsBahco = wrenchIsBahco; } public String getWrenchDescription() { return wrenchDescription; } public void setWrenchDescription(String wrenchDescription) { this.wrenchDescription = wrenchDescription; } }
FlattenedToolBox
java
elastic__elasticsearch
x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/RestSqlSecurityIT.java
{ "start": 14289, "end": 15595 }
class ____ extends AuditLogAsserter { @Override public AuditLogAsserter expect( String eventType, String action, String principal, String realm, Matcher<? extends Iterable<? extends String>> indicesMatcher, String request ) { final Matcher<String> runByPrincipalMatcher = principal.equals("test_admin") ? Matchers.nullValue(String.class) : Matchers.is("test_admin"); final Matcher<String> runByRealmMatcher = realm.equals("default_file") ? Matchers.nullValue(String.class) : Matchers.is("default_file"); logCheckers.add( m -> eventType.equals(m.get("event.action")) && action.equals(m.get("action")) && principal.equals(m.get("user.name")) && realm.equals(m.get("user.realm")) && runByPrincipalMatcher.matches(m.get("user.run_by.name")) && runByRealmMatcher.matches(m.get("user.run_by.realm")) && indicesMatcher.matches(m.get("indices")) && request.equals(m.get("request.name")) ); return this; } } }
RestAuditLogAsserter
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/visitors/AbstractPluginVisitor.java
{ "start": 1489, "end": 2155 }
class ____<A extends Annotation> implements PluginVisitor<A> { /** Status logger. */ protected static final Logger LOGGER = StatusLogger.getLogger(); /** * */ protected final Class<A> clazz; /** * */ protected A annotation; /** * */ protected String[] aliases; /** * */ protected Class<?> conversionType; /** * */ protected StrSubstitutor substitutor; /** * */ protected Member member; /** * This constructor must be overridden by implementation classes as a no-arg constructor. * * @param clazz the annotation
AbstractPluginVisitor
java
quarkusio__quarkus
extensions/cache/deployment/src/main/java/io/quarkus/cache/deployment/CachedResultsProcessor.java
{ "start": 16293, "end": 16529 }
class ____ found in index: " + type.name()); } if (!injectedClazz.isInterface() && !injectedClazz.hasNoArgsConstructor()) { throw new IllegalStateException( "@CachedResults
not
java
quarkusio__quarkus
extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddPortToOpenshiftConfig.java
{ "start": 231, "end": 1425 }
class ____ extends Configurator<OpenshiftConfigFluent<?>> { private final Port port; public AddPortToOpenshiftConfig(Port port) { this.port = port; } @Override public void visit(OpenshiftConfigFluent<?> config) { if (!hasPort(config)) { config.addToPorts(port); } } /** * Check if the {@link OpenShiftConfig} already has port. * * @param config The port. * @return True if port with same container port exists. */ private boolean hasPort(OpenshiftConfigFluent<?> config) { for (Port p : config.buildPorts()) { if (Objects.equals(p.getContainerPort(), port.getContainerPort())) { return true; } } return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AddPortToOpenshiftConfig addPort = (AddPortToOpenshiftConfig) o; return Objects.equals(port, addPort.port); } @Override public int hashCode() { return Objects.hash(port); } }
AddPortToOpenshiftConfig
java
quarkusio__quarkus
extensions/hibernate-validator/runtime/src/main/java/io/quarkus/hibernate/validator/runtime/HibernateBeanValidationConfigValidator.java
{ "start": 504, "end": 1691 }
class ____ implements BeanValidationConfigValidator { public HibernateBeanValidationConfigValidator(Set<String> constraints, Set<Class<?>> classesToBeValidated) { PredefinedScopeHibernateValidatorConfiguration configuration = Validation .byProvider(PredefinedScopeHibernateValidator.class) .configure(); // TODO - There is no way to retrieve locales from configuration here (even manually). We need to add a way to configure the validator from SmallRye Config. configuration .ignoreXmlConfiguration() .builtinConstraints(constraints) .initializeBeanMetaData(classesToBeValidated) .constraintValidatorFactory(new DefaultConstraintValidatorFactory()) .traversableResolver(new TraverseAllTraversableResolver()); ConfigValidatorHolder.initialize(configuration.buildValidatorFactory()); } @Override public Validator getValidator() { return ConfigValidatorHolder.getValidator(); } // Store in a holder, so we can easily reference it and shutdown the validator public static
HibernateBeanValidationConfigValidator
java
spring-projects__spring-boot
module/spring-boot-restclient-test/src/test/java/org/springframework/boot/restclient/test/autoconfigure/AutoConfigureMockRestServiceServerWithRestTemplateRootUriIntegrationTests.java
{ "start": 2587, "end": 2763 }
class ____ { @Bean RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder.rootUri("/rest").build(); } } }
RootUriConfiguration
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/TwitterDirectMessageEndpointBuilderFactory.java
{ "start": 54828, "end": 60238 }
interface ____ extends TwitterDirectMessageEndpointConsumerBuilder, TwitterDirectMessageEndpointProducerBuilder { default AdvancedTwitterDirectMessageEndpointBuilder advanced() { return (AdvancedTwitterDirectMessageEndpointBuilder) this; } /** * The http proxy host which can be used for the camel-twitter. Can also * be configured on the TwitterComponent level instead. * * The option is a: <code>java.lang.String</code> type. * * Group: proxy * * @param httpProxyHost the value to set * @return the dsl builder */ default TwitterDirectMessageEndpointBuilder httpProxyHost(String httpProxyHost) { doSetProperty("httpProxyHost", httpProxyHost); return this; } /** * The http proxy password which can be used for the camel-twitter. Can * also be configured on the TwitterComponent level instead. * * The option is a: <code>java.lang.String</code> type. * * Group: proxy * * @param httpProxyPassword the value to set * @return the dsl builder */ default TwitterDirectMessageEndpointBuilder httpProxyPassword(String httpProxyPassword) { doSetProperty("httpProxyPassword", httpProxyPassword); return this; } /** * The http proxy port which can be used for the camel-twitter. Can also * be configured on the TwitterComponent level instead. * * The option is a: <code>java.lang.Integer</code> type. * * Group: proxy * * @param httpProxyPort the value to set * @return the dsl builder */ default TwitterDirectMessageEndpointBuilder httpProxyPort(Integer httpProxyPort) { doSetProperty("httpProxyPort", httpProxyPort); return this; } /** * The http proxy port which can be used for the camel-twitter. Can also * be configured on the TwitterComponent level instead. * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Group: proxy * * @param httpProxyPort the value to set * @return the dsl builder */ default TwitterDirectMessageEndpointBuilder httpProxyPort(String httpProxyPort) { doSetProperty("httpProxyPort", httpProxyPort); return this; } /** * The http proxy user which can be used for the camel-twitter. Can also * be configured on the TwitterComponent level instead. * * The option is a: <code>java.lang.String</code> type. * * Group: proxy * * @param httpProxyUser the value to set * @return the dsl builder */ default TwitterDirectMessageEndpointBuilder httpProxyUser(String httpProxyUser) { doSetProperty("httpProxyUser", httpProxyUser); return this; } /** * The access token. Can also be configured on the TwitterComponent * level instead. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param accessToken the value to set * @return the dsl builder */ default TwitterDirectMessageEndpointBuilder accessToken(String accessToken) { doSetProperty("accessToken", accessToken); return this; } /** * The access secret. Can also be configured on the TwitterComponent * level instead. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param accessTokenSecret the value to set * @return the dsl builder */ default TwitterDirectMessageEndpointBuilder accessTokenSecret(String accessTokenSecret) { doSetProperty("accessTokenSecret", accessTokenSecret); return this; } /** * The consumer key. Can also be configured on the TwitterComponent * level instead. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param consumerKey the value to set * @return the dsl builder */ default TwitterDirectMessageEndpointBuilder consumerKey(String consumerKey) { doSetProperty("consumerKey", consumerKey); return this; } /** * The consumer secret. Can also be configured on the TwitterComponent * level instead. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param consumerSecret the value to set * @return the dsl builder */ default TwitterDirectMessageEndpointBuilder consumerSecret(String consumerSecret) { doSetProperty("consumerSecret", consumerSecret); return this; } } /** * Advanced builder for endpoint for the Twitter Direct Message component. */ public
TwitterDirectMessageEndpointBuilder
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/MRCaching.java
{ "start": 5767, "end": 5840 }
class ____ just emits the sum of the input values. */ public static
that
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/inheritfromconfig/CarDto.java
{ "start": 239, "end": 448 }
class ____ extends BaseVehicleDto { private String colour; public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } }
CarDto
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/MlAutoUpdateService.java
{ "start": 934, "end": 3479 }
interface ____ { boolean isMinTransportVersionSupported(TransportVersion minTransportVersion); boolean isAbleToRun(ClusterState latestState); String getName(); void runUpdate(ClusterState latestState); } private final List<UpdateAction> updateActions; private final Set<String> currentlyUpdating; private final Set<String> completedUpdates; private final ThreadPool threadPool; public MlAutoUpdateService(ThreadPool threadPool, List<UpdateAction> updateActions) { this.updateActions = updateActions; this.completedUpdates = ConcurrentHashMap.newKeySet(); this.currentlyUpdating = ConcurrentHashMap.newKeySet(); this.threadPool = threadPool; } @Override public void clusterChanged(ClusterChangedEvent event) { if (event.localNodeMaster() == false) { return; } if (event.state().blocks().hasGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK)) { return; } if (completedUpdates.size() == updateActions.size()) { return; // all work complete } final var latestState = event.state(); TransportVersion minTransportVersion = latestState.getMinTransportVersion(); final List<UpdateAction> toRun = updateActions.stream() .filter(action -> action.isMinTransportVersionSupported(minTransportVersion)) .filter(action -> completedUpdates.contains(action.getName()) == false) .filter(action -> action.isAbleToRun(latestState)) .filter(action -> currentlyUpdating.add(action.getName())) .toList(); threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME) .execute(() -> toRun.forEach((action) -> this.runUpdate(action, latestState))); } private void runUpdate(UpdateAction action, ClusterState latestState) { try { logger.debug(() -> "[" + action.getName() + "] starting executing update action"); action.runUpdate(latestState); this.completedUpdates.add(action.getName()); logger.debug(() -> "[" + action.getName() + "] succeeded executing update action"); } catch (Exception ex) { logger.warn(() -> "[" + action.getName() + "] failure executing update action", ex); } finally { this.currentlyUpdating.remove(action.getName()); logger.debug(() -> "[" + action.getName() + "] no longer executing update action"); } } }
UpdateAction
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeTransferSocketSize.java
{ "start": 1235, "end": 2661 }
class ____ { @Test public void testSpecifiedDataSocketSize() throws Exception { Configuration conf = new HdfsConfiguration(); conf.setInt( DFSConfigKeys.DFS_DATANODE_TRANSFER_SOCKET_RECV_BUFFER_SIZE_KEY, 4 * 1024); SimulatedFSDataset.setFactory(conf); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); try { List<DataNode> datanodes = cluster.getDataNodes(); DataNode datanode = datanodes.get(0); assertEquals(4 * 1024, datanode.getXferServer().getPeerServer().getReceiveBufferSize(), "Receive buffer size should be 4K"); } finally { if (cluster != null) { cluster.shutdown(); } } } @Test public void testAutoTuningDataSocketSize() throws Exception { Configuration conf = new HdfsConfiguration(); conf.setInt( DFSConfigKeys.DFS_DATANODE_TRANSFER_SOCKET_RECV_BUFFER_SIZE_KEY, 0); SimulatedFSDataset.setFactory(conf); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); try { List<DataNode> datanodes = cluster.getDataNodes(); DataNode datanode = datanodes.get(0); assertTrue( datanode.getXferServer().getPeerServer().getReceiveBufferSize() > 0, "Receive buffer size should be a default value (determined by kernel)"); } finally { if (cluster != null) { cluster.shutdown(); } } } }
TestDataNodeTransferSocketSize
java
google__error-prone
core/src/main/java/com/google/errorprone/refaster/PlaceholderMethod.java
{ "start": 3283, "end": 4765 }
class ____ implements Matcher<ExpressionTree> { @Override public boolean matches(ExpressionTree t, VisitorState state) { try { return (allowsIdentity || !(t instanceof PlaceholderParamIdent)) && (matchesClass == null || matchesClass.newInstance().matches(t, state)) && (notMatchesClass == null || !notMatchesClass.newInstance().matches(t, state)) && allowedKinds.test(t.getKind()); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } } return new PlaceholderMethod( StringName.of(name), returnType, parameters, new PlaceholderMatcher(), ImmutableClassToInstanceMap.<Annotation, Annotation>copyOf(annotations)); } ImmutableSet<UVariableDecl> parameters() { return annotatedParameters().keySet(); } /** Parameters which must be referenced in any tree matched to this placeholder. */ Set<UVariableDecl> requiredParameters() { return Maps.filterValues( annotatedParameters(), (ImmutableClassToInstanceMap<Annotation> annotations) -> !annotations.containsKey(MayOptionallyUse.class)) .keySet(); } PlaceholderExpressionKey exprKey() { return new PlaceholderExpressionKey(name().contents(), this); } PlaceholderBlockKey blockKey() { return new PlaceholderBlockKey(name().contents(), this); } static final
PlaceholderMatcher
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/validators/ParamValidationCheckerTest.java
{ "start": 67458, "end": 67631 }
class ____ extends Single<Object> { @Override public void subscribeActual(SingleObserver<? super Object> observer) { // not invoked, the
NeverSingle
java
google__error-prone
check_api/src/main/java/com/google/errorprone/ErrorPronePlugins.java
{ "start": 1174, "end": 2379 }
class ____ { public static ScannerSupplier loadPlugins(ScannerSupplier scannerSupplier, Context context) { JavaFileManager fileManager = context.get(JavaFileManager.class); // Unlike in annotation processor discovery, we never search CLASS_PATH if // ANNOTATION_PROCESSOR_PATH is unavailable. if (!fileManager.hasLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH)) { return scannerSupplier; } // Use the same classloader that Error Prone was loaded from to avoid classloader skew // when using Error Prone plugins together with the Error Prone javac plugin. JavacProcessingEnvironment processingEnvironment = JavacProcessingEnvironment.instance(context); ClassLoader loader = processingEnvironment.getProcessorClassLoader(); ImmutableList<Class<? extends BugChecker>> extraBugCheckers = ServiceLoader.load(BugChecker.class, loader).stream() .map(ServiceLoader.Provider::type) .collect(toImmutableList()); if (extraBugCheckers.isEmpty()) { return scannerSupplier; } return scannerSupplier.plus(ScannerSupplier.fromBugCheckerClasses(extraBugCheckers)); } private ErrorPronePlugins() {} }
ErrorPronePlugins
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java
{ "start": 20577, "end": 20709 }
class ____ { @ResponseBody public CustomDeferredResult handle() { return null; } } private static
DeferredResultSubclassHandler
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/plugins/UberModuleClassLoaderTests.java
{ "start": 40458, "end": 42201 }
interface ____ { String getLetter(); } """; String requiredParentModuleInfo = """ module p.required { exports p.required; } """; Map<String, CharSequence> requiredModuleSources = new HashMap<>(); requiredModuleSources.put("p.required.LetterService", serviceFromRequiredParent); requiredModuleSources.put("module-info", requiredParentModuleInfo); var requiredModuleCompiled = InMemoryJavaCompiler.compile(requiredModuleSources); assertThat(requiredModuleCompiled, notNullValue()); Path parentJar = libDir.resolve("parent.jar"); JarUtils.createJarWithEntries( parentJar, requiredModuleCompiled.entrySet() .stream() .collect(Collectors.toMap(e -> e.getKey().replace(".", "/") + ".class", Map.Entry::getValue)) ); return parentJar; } private static UberModuleClassLoader getLoader(Path jar) { return getLoader(List.of(jar)); } private static UberModuleClassLoader getLoader(List<Path> jars) { return UberModuleClassLoader.getInstance( UberModuleClassLoaderTests.class.getClassLoader(), MODULE_NAME, jars.stream().map(UberModuleClassLoaderTests::pathToUrlUnchecked).collect(Collectors.toSet()) ); } private static URL pathToUrlUnchecked(Path path) { try { return toUrl(path); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } /* * Instantiates an instance of FooBar. First generates and compiles the code, then packages it, * and lastly loads the FooBar
LetterService
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/booleanarrays/BooleanArrays_assertDoesNotHaveDuplicates_Test.java
{ "start": 1646, "end": 2634 }
class ____ extends BooleanArraysBaseTest { @Test void should_pass_if_actual_does_not_have_duplicates() { arrays.assertDoesNotHaveDuplicates(someInfo(), actual); } @Test void should_pass_if_actual_is_empty() { arrays.assertDoesNotHaveDuplicates(someInfo(), emptyArray()); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertDoesNotHaveDuplicates(someInfo(), null)) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_contains_duplicates() { actual = arrayOf(true, true, false); AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> arrays.assertDoesNotHaveDuplicates(info, actual)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldNotHaveDuplicates(actual, newLinkedHashSet(true))); } }
BooleanArrays_assertDoesNotHaveDuplicates_Test
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpSimpleConsumeStreamingPartialReadIT.java
{ "start": 1693, "end": 3865 }
class ____ extends SftpServerTestSupport { @Test public void testSftpSimpleConsume() throws Exception { String expected = "Hello World"; // create file using regular file template.sendBodyAndHeader("file://" + service.getFtpRootDir(), expected, Exchange.FILE_NAME, "hello.txt"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedHeaderReceived(Exchange.FILE_NAME, "hello.txt"); context.getRouteController().startRoute("foo"); MockEndpoint.assertIsSatisfied(context); InputStream is = mock.getExchanges().get(0).getIn().getBody(InputStream.class); assertNotNull(is); // Wait a little bit for the move to finish. File resultFile = new File(service.getFtpRootDir() + File.separator + "failed", "hello.txt"); await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> assertTrue(resultFile.exists())); assertFalse(resultFile.isDirectory()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("sftp://localhost:{{ftp.server.port}}/{{ftp.root.dir}}" + "?username=admin&password=admin&delay=10000&disconnect=true&streamDownload=true" + "&move=done&moveFailed=failed&knownHostsFile=" + service.getKnownHostsFile()) .routeId("foo").noAutoStartup().process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().getBody(InputStream.class).read(); } }).to("mock:result").process(new Processor() { @Override public void process(Exchange exchange) throws Exception { throw new Exception("INTENTIONAL ERROR"); } }); } }; } }
SftpSimpleConsumeStreamingPartialReadIT
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/junit4/rules/SpringClassRule.java
{ "start": 2348, "end": 3299 }
class ____ { * * &#064;ClassRule * public static final SpringClassRule springClassRule = new SpringClassRule(); * * &#064;Rule * public final SpringMethodRule springMethodRule = new SpringMethodRule(); * * // ... * }</code></pre> * * <p>The following list constitutes all annotations currently supported directly * or indirectly by {@code SpringClassRule}. <em>(Note that additional annotations * may be supported by various * {@link org.springframework.test.context.TestExecutionListener TestExecutionListener} or * {@link org.springframework.test.context.TestContextBootstrapper TestContextBootstrapper} * implementations.)</em> * * <ul> * <li>{@link org.springframework.test.annotation.ProfileValueSourceConfiguration @ProfileValueSourceConfiguration}</li> * <li>{@link org.springframework.test.annotation.IfProfileValue @IfProfileValue}</li> * </ul> * * <p><strong>NOTE:</strong> This
ExampleSpringIntegrationTest
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/oauth2/WorkloadIdentityTokenProvider.java
{ "start": 2041, "end": 6992 }
class ____ implements ClientAssertionProvider { private final String tokenFile; FileBasedClientAssertionProvider(String tokenFile) { this.tokenFile = tokenFile; } @Override public void initialize(Configuration configuration, String accountName) throws IOException { // No initialization needed for file-based provider } @Override public String getClientAssertion() throws IOException { String clientAssertion = EMPTY_STRING; try { File file = new File(tokenFile); clientAssertion = FileUtils.readFileToString(file, StandardCharsets.UTF_8); } catch (Exception e) { throw new IOException(TOKEN_FILE_READ_ERROR + tokenFile, e); } clientAssertion = clientAssertion.trim(); if (Strings.isNullOrEmpty(clientAssertion)) { throw new IOException(EMPTY_TOKEN_FILE_ERROR + tokenFile); } return clientAssertion; } } private final String authEndpoint; private final String clientId; private final ClientAssertionProvider clientAssertionProvider; private long tokenFetchTime = -1; /** * Constructor with custom ClientAssertionProvider. * Use this for custom token retrieval mechanisms like Kubernetes Token Request API. * * @param authority OAuth authority URL * @param tenantId Azure AD tenant ID * @param clientId Azure AD client ID * @param clientAssertionProvider Custom provider for client assertions */ public WorkloadIdentityTokenProvider(final String authority, final String tenantId, final String clientId, ClientAssertionProvider clientAssertionProvider) { Preconditions.checkNotNull(authority, "authority"); Preconditions.checkNotNull(tenantId, "tenantId"); Preconditions.checkNotNull(clientId, "clientId"); Preconditions.checkNotNull(clientAssertionProvider, "clientAssertionProvider"); this.authEndpoint = authority + tenantId + OAUTH2_TOKEN_PATH; this.clientId = clientId; this.clientAssertionProvider = clientAssertionProvider; } /** * Constructor with file-based token reading (backward compatibility). * * @param authority OAuth authority URL * @param tenantId Azure AD tenant ID * @param clientId Azure AD client ID * @param tokenFile Path to file containing the JWT token */ public WorkloadIdentityTokenProvider(final String authority, final String tenantId, final String clientId, final String tokenFile) { Preconditions.checkNotNull(authority, "authority"); Preconditions.checkNotNull(tenantId, "tenantId"); Preconditions.checkNotNull(clientId, "clientId"); Preconditions.checkNotNull(tokenFile, "tokenFile"); this.authEndpoint = authority + tenantId + OAUTH2_TOKEN_PATH; this.clientId = clientId; this.clientAssertionProvider = new FileBasedClientAssertionProvider(tokenFile); } @Override protected AzureADToken refreshToken() throws IOException { LOG.debug("AADToken: refreshing token from JWT Assertion"); String clientAssertion = clientAssertionProvider.getClientAssertion(); AzureADToken token = getTokenUsingJWTAssertion(clientAssertion); tokenFetchTime = System.currentTimeMillis(); return token; } /** * Checks if the token is about to expire as per base expiry logic. * Otherwise, expire if there is a clock skew issue in the system. * * @return true if the token is expiring in next 1 hour or if a token has * never been fetched */ @Override protected boolean isTokenAboutToExpire() { if (tokenFetchTime == -1 || super.isTokenAboutToExpire()) { return true; } // In case of, any clock skew issues, refresh token. long elapsedTimeSinceLastTokenRefreshInMillis = System.currentTimeMillis() - tokenFetchTime; boolean expiring = elapsedTimeSinceLastTokenRefreshInMillis < 0; if (expiring) { // Clock Skew issue. Refresh token. LOG.debug("JWTToken: token renewing. Time elapsed since last token fetch:" + " {} milliseconds", elapsedTimeSinceLastTokenRefreshInMillis); } return expiring; } /** * Gets the Azure AD token from a client assertion in JWT format. * This method exists to make unit testing possible. * * @param clientAssertion the client assertion. * @return the Azure AD token. * @throws IOException if there is a failure in connecting to Azure AD. */ @VisibleForTesting AzureADToken getTokenUsingJWTAssertion(String clientAssertion) throws IOException { return AzureADAuthenticator .getTokenUsingJWTAssertion(authEndpoint, clientId, clientAssertion); } /** * Returns the last time the token was fetched from the token file. * This method exists to make unit testing possible. * * @return the time the token was last fetched. */ @VisibleForTesting long getTokenFetchTime() { return tokenFetchTime; } }
FileBasedClientAssertionProvider
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/JodaInstantWithMillisTest.java
{ "start": 2923, "end": 3284 }
class ____ { private static final Instant INSTANT = Instant.now().withMillis(42); } """) .doTest(); } @Test public void instantConstructorLongPrimitiveInsideJoda() { helper .addSourceLines( "TestClass.java", """ package org.joda.time; public
TestClass
java
apache__flink
flink-rpc/flink-rpc-akka/src/test/java/org/apache/flink/runtime/rpc/pekko/PekkoActorSystemTest.java
{ "start": 3309, "end": 3659 }
class ____ extends AbstractActor { @Override public Receive createReceive() { return ReceiveBuilder.create().match(Fail.class, this::handleFail).build(); } private void handleFail(Fail fail) { throw new RuntimeException(fail.getErrorCause()); } } private static final
SimpleActor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/any/discriminator/many/ManyToAnyTests.java
{ "start": 898, "end": 2158 }
class ____ { @Test public void testManyToAnyUsage(SessionFactoryScope sessions) { sessions.inTransaction( (session) -> { final Loan loan = session.find( Loan.class, 1 ); final CashPayment cashPayment = session.find( CashPayment.class, 1 ); final CardPayment cardPayment = session.find( CardPayment.class, 1 ); final CheckPayment checkPayment = session.find( CheckPayment.class, 1 ); loan.getPayments().add( cardPayment ); session.flush(); loan.getPayments().add( checkPayment ); session.flush(); loan.getPayments().add( cashPayment ); session.flush(); } ); } @BeforeEach void prepareTestData(SessionFactoryScope sessions) { sessions.inTransaction( (session) -> { final Loan loan = new Loan( 1, "1" ); final CashPayment cashPayment = new CashPayment( 1, 50.00 ); final CardPayment cardPayment = new CardPayment( 1, 150.00, "123-456-789" ); final CheckPayment checkPayment = new CheckPayment( 1, 250.00, 1001, "123", "987" ); session.persist( loan ); session.persist( cashPayment ); session.persist( cardPayment ); session.persist( checkPayment ); } ); } @AfterEach void dropTestData(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } }
ManyToAnyTests
java
dropwizard__dropwizard
dropwizard-jersey/src/main/java/io/dropwizard/jersey/DropwizardResourceConfig.java
{ "start": 14676, "end": 15048 }
class ____ extends AbstractBinder { private final MetricRegistry metricRegistry; public MetricRegistryBinder(MetricRegistry metricRegistry) { this.metricRegistry = metricRegistry; } @Override protected void configure() { bind(metricRegistry).to(MetricRegistry.class); } } }
MetricRegistryBinder
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/cache/interceptor/NamedCacheResolver.java
{ "start": 1012, "end": 1610 }
class ____ extends AbstractCacheResolver { private @Nullable Collection<String> cacheNames; public NamedCacheResolver() { } public NamedCacheResolver(CacheManager cacheManager, String... cacheNames) { super(cacheManager); this.cacheNames = List.of(cacheNames); } /** * Set the cache name(s) that this resolver should use. */ public void setCacheNames(Collection<String> cacheNames) { this.cacheNames = cacheNames; } @Override protected @Nullable Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) { return this.cacheNames; } }
NamedCacheResolver
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/TruthIncompatibleTypeTest.java
{ "start": 12560, "end": 13081 }
class ____ { public void f(Iterable<Long> xs, Correspondence<Long, String> c) { assertThat(xs).comparingElementsUsing(c).doesNotContain(""); } } """) .doTest(); } @Test public void mapContainsExactlyEntriesIn_keyTypesDiffer() { compilationHelper .addSourceLines( "Test.java", """ import static com.google.common.truth.Truth.assertThat; import java.util.Map; public
Test
java
elastic__elasticsearch
x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/RandomizedTimeSeriesIT.java
{ "start": 6001, "end": 11977 }
enum ____ { MAX, MIN, AVG, SUM, COUNT } static List<Integer> valuesInWindow(List<Map<String, Object>> pointsInGroup, String metricName) { @SuppressWarnings("unchecked") var values = pointsInGroup.stream() .map(doc -> ((Map<String, Integer>) doc.get("metrics")).get(metricName)) .filter(Objects::nonNull) .collect(Collectors.toList()); return values; } static Map<String, List<Tuple<String, Tuple<Instant, Double>>>> groupByTimeseries( List<Map<String, Object>> pointsInGroup, String metricName ) { return pointsInGroup.stream() .filter(doc -> doc.containsKey("metrics") && ((Map<String, Object>) doc.get("metrics")).containsKey(metricName)) .map(doc -> { String docKey = ((Map<String, Object>) doc.get("attributes")).entrySet() .stream() .map(entry -> entry.getKey() + ":" + entry.getValue()) .collect(Collectors.joining(",")); var docTs = Instant.parse((String) doc.get("@timestamp")); var docValue = switch (((Map<String, Object>) doc.get("metrics")).get(metricName)) { case Integer i -> i.doubleValue(); case Long l -> l.doubleValue(); case Float f -> f.doubleValue(); case Double d -> d; default -> throw new IllegalStateException( "Unexpected value type: " + ((Map<String, Object>) doc.get("metrics")).get(metricName) + " of class " + ((Map<String, Object>) doc.get("metrics")).get(metricName).getClass() ); }; return new Tuple<>(docKey, new Tuple<>(docTs, docValue)); }) .collect(Collectors.groupingBy(Tuple::v1)); } static Object aggregatePerTimeseries( Map<String, List<Tuple<String, Tuple<Instant, Double>>>> timeseries, Agg crossAgg, Agg timeseriesAgg ) { var res = timeseries.values().stream().map(timeseriesList -> { List<Double> values = timeseriesList.stream().map(t -> t.v2().v2()).collect(Collectors.toList()); return aggregateValuesInWindow(values, timeseriesAgg); }).filter(Objects::nonNull).toList(); if (res.isEmpty() && timeseriesAgg == Agg.COUNT) { res = List.of(0.0); } return switch (crossAgg) { case MAX -> res.isEmpty() ? null : res.stream().mapToDouble(Double::doubleValue).max().orElseThrow(); case MIN -> res.isEmpty() ? null : res.stream().mapToDouble(Double::doubleValue).min().orElseThrow(); case AVG -> res.isEmpty() ? null : res.stream().mapToDouble(Double::doubleValue).average().orElseThrow(); case SUM -> res.isEmpty() ? null : res.stream().mapToDouble(Double::doubleValue).sum(); case COUNT -> Integer.toUnsignedLong(res.size()); }; } static Double aggregateValuesInWindow(List<Double> values, Agg agg) { return switch (agg) { case MAX -> values.stream().max(Double::compareTo).orElseThrow(); case MIN -> values.stream().min(Double::compareTo).orElseThrow(); case AVG -> values.stream().mapToDouble(Double::doubleValue).average().orElseThrow(); case SUM -> values.isEmpty() ? null : values.stream().mapToDouble(Double::doubleValue).sum(); case COUNT -> (double) values.size(); }; } static List<String> getRowKey(List<Object> row, List<String> groupingAttributes, int timestampIndex) { List<String> rowKey = new ArrayList<>(); for (int i = 0; i < groupingAttributes.size(); i++) { Object value = row.get(i + timestampIndex + 1); if (value != null) { rowKey.add(groupingAttributes.get(i) + ":" + value); } } rowKey.add(Long.toString(Instant.parse((String) row.get(timestampIndex)).toEpochMilli() / 1000)); return rowKey; } static Integer getTimestampIndex(String esqlQuery) { // first we get the stats command after the pipe var statsIndex = esqlQuery.indexOf("| STATS"); var nextPipe = esqlQuery.indexOf("|", statsIndex + 1); var statsCommand = esqlQuery.substring(statsIndex, nextPipe); // then we count the number of commas before "BY " var byTbucketIndex = statsCommand.indexOf("BY "); var statsPart = statsCommand.substring(0, byTbucketIndex); // the number of columns is the number of commas + 1 return (int) statsPart.chars().filter(ch -> ch == ',').count() + 1; } @Override public EsqlQueryResponse run(EsqlQueryRequest request) { assumeTrue("time series available in snapshot builds only", Build.current().isSnapshot()); return super.run(request); } @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return List.of(DataStreamsPlugin.class, LocalStateCompositeXPackPlugin.class, AggregateMetricMapperPlugin.class, EsqlPlugin.class); } record RateRange(Double lower, Double upper) implements Comparable<RateRange> { @Override public int compareTo(RateRange o) { // Compare first by lower bound, then by upper bound int cmp = this.lower.compareTo(o.lower); if (cmp == 0) { return this.upper.compareTo(o.upper); } return cmp; } public int compareToFindingMax(RateRange o) { // Compare first by upper bound, then by lower bound int cmp = this.upper.compareTo(o.upper); if (cmp == 0) { return this.lower.compareTo(o.lower); } return cmp; } }
Agg
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ProvidedStorageMap.java
{ "start": 2649, "end": 8310 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(ProvidedStorageMap.class); // limit to a single provider for now private RwLock lock; private BlockManager bm; private BlockAliasMap aliasMap; private final String storageId; private final ProvidedDescriptor providedDescriptor; private final DatanodeStorageInfo providedStorageInfo; private boolean providedEnabled; private int defaultReplication; ProvidedStorageMap(RwLock lock, BlockManager bm, Configuration conf) { storageId = conf.get(DFSConfigKeys.DFS_PROVIDER_STORAGEUUID, DFSConfigKeys.DFS_PROVIDER_STORAGEUUID_DEFAULT); providedEnabled = conf.getBoolean( DFSConfigKeys.DFS_NAMENODE_PROVIDED_ENABLED, DFSConfigKeys.DFS_NAMENODE_PROVIDED_ENABLED_DEFAULT); if (!providedEnabled) { // disable mapping aliasMap = null; providedDescriptor = null; providedStorageInfo = null; return; } DatanodeStorage ds = new DatanodeStorage( storageId, State.NORMAL, StorageType.PROVIDED); providedDescriptor = new ProvidedDescriptor(); providedStorageInfo = providedDescriptor.createProvidedStorage(ds); this.defaultReplication = conf.getInt(DFSConfigKeys.DFS_REPLICATION_KEY, DFSConfigKeys.DFS_REPLICATION_DEFAULT); this.bm = bm; this.lock = lock; // load block reader into storage Class<? extends BlockAliasMap> aliasMapClass = conf.getClass( DFSConfigKeys.DFS_PROVIDED_ALIASMAP_CLASS, TextFileRegionAliasMap.class, BlockAliasMap.class); aliasMap = ReflectionUtils.newInstance(aliasMapClass, conf); LOG.info("Loaded alias map class: " + aliasMap.getClass() + " storage: " + providedStorageInfo); } /** * @param dn datanode descriptor * @param s data node storage * @return the {@link DatanodeStorageInfo} for the specified datanode. * If {@code s} corresponds to a provided storage, the storage info * representing provided storage is returned. * @throws IOException */ DatanodeStorageInfo getStorage(DatanodeDescriptor dn, DatanodeStorage s) throws IOException { if (providedEnabled && storageId.equals(s.getStorageID())) { if (StorageType.PROVIDED.equals(s.getStorageType())) { if (providedStorageInfo.getState() == State.FAILED && s.getState() == State.NORMAL) { providedStorageInfo.setState(State.NORMAL); LOG.info("Provided storage transitioning to state " + State.NORMAL); } if (dn.getStorageInfo(s.getStorageID()) == null) { dn.injectStorage(providedStorageInfo); } processProvidedStorageReport(); return providedDescriptor.getProvidedStorage(dn, s); } LOG.warn("Reserved storage {} reported as non-provided from {}", s, dn); } return dn.getStorageInfo(s.getStorageID()); } private void processProvidedStorageReport() throws IOException { assert lock.hasWriteLock(RwLockMode.GLOBAL) : "Not holding write lock"; if (providedStorageInfo.getBlockReportCount() == 0 || providedDescriptor.activeProvidedDatanodes() == 0) { LOG.info("Calling process first blk report from storage: " + providedStorageInfo); // first pass; periodic refresh should call bm.processReport BlockAliasMap.Reader<BlockAlias> reader = aliasMap.getReader(null, bm.getBlockPoolId()); if (reader != null) { bm.processFirstBlockReport(providedStorageInfo, new ProvidedBlockList(reader.iterator())); } } } @VisibleForTesting public DatanodeStorageInfo getProvidedStorageInfo() { return providedStorageInfo; } public LocatedBlockBuilder newLocatedBlocks(int maxValue) { if (!providedEnabled) { return new LocatedBlockBuilder(maxValue); } return new ProvidedBlocksBuilder(maxValue); } public void removeDatanode(DatanodeDescriptor dnToRemove) { if (providedEnabled) { assert lock.hasWriteLock(RwLockMode.BM) : "Not holding write lock"; providedDescriptor.remove(dnToRemove); // if all datanodes fail, set the block report count to 0 if (providedDescriptor.activeProvidedDatanodes() == 0) { providedStorageInfo.setBlockReportCount(0); } } } public long getCapacity() { if (providedStorageInfo == null) { return 0; } return providedStorageInfo.getCapacity(); } public void updateStorage(DatanodeDescriptor node, DatanodeStorage storage) { if (isProvidedStorage(storage.getStorageID())) { if (StorageType.PROVIDED.equals(storage.getStorageType())) { node.injectStorage(providedStorageInfo); return; } else { LOG.warn("Reserved storage {} reported as non-provided from {}", storage, node); } } node.updateStorage(storage); } private boolean isProvidedStorage(String dnStorageId) { return providedEnabled && storageId.equals(dnStorageId); } /** * Choose a datanode that reported a volume of {@link StorageType} PROVIDED. * * @return the {@link DatanodeDescriptor} corresponding to a datanode that * reported a volume with {@link StorageType} PROVIDED. If multiple * datanodes report a PROVIDED volume, one is chosen uniformly at * random. */ public DatanodeDescriptor chooseProvidedDatanode() { return providedDescriptor.chooseRandom(); } @VisibleForTesting public BlockAliasMap getAliasMap() { return aliasMap; } /** * Builder used for creating {@link LocatedBlocks} when a block is provided. */
ProvidedStorageMap
java
apache__hadoop
hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-workload/src/main/java/org/apache/hadoop/tools/dynamometer/workloadgenerator/audit/AuditLogHiveTableParser.java
{ "start": 2071, "end": 2739 }
class ____ implements AuditCommandParser { private static final String FIELD_SEPARATOR = "\u0001"; @Override public void initialize(Configuration conf) throws IOException { // Nothing to be done } @Override public AuditReplayCommand parse(Long sequence, Text inputLine, Function<Long, Long> relativeToAbsolute) throws IOException { String[] fields = inputLine.toString().split(FIELD_SEPARATOR); long absoluteTimestamp = relativeToAbsolute .apply(Long.parseLong(fields[0])); return new AuditReplayCommand(sequence, absoluteTimestamp, fields[1], fields[2], fields[3], fields[4], fields[5]); } }
AuditLogHiveTableParser
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/ColumnNameIterator.java
{ "start": 369, "end": 899 }
class ____ implements Iterator<String> { public static ColumnNameIterator from(Iterator<Selectable> selectables) { return new ColumnNameIterator() { public boolean hasNext() { return selectables.hasNext(); } public String next() { final Selectable next = selectables.next(); if ( next.isFormula() ) { throw new FormulaNotSupportedException(); } return ( (org.hibernate.mapping.Column) next ).getName(); } public void remove() { selectables.remove(); } }; } }
ColumnNameIterator
java
quarkusio__quarkus
independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusInternalAttribute.java
{ "start": 1200, "end": 4495 }
class ____ extends AbstractReferenceCounted implements InterfaceHttpData { private final List<ByteBuf> value = new ArrayList<>(); private final Charset charset; private int size; QuarkusInternalAttribute(Charset charset) { this.charset = charset; } @Override public HttpDataType getHttpDataType() { return HttpDataType.InternalAttribute; } public void addValue(String value) { ObjectUtil.checkNotNull(value, "value"); ByteBuf buf = Unpooled.copiedBuffer(value, charset); this.value.add(buf); size += buf.readableBytes(); } public void addValue(String value, int rank) { ObjectUtil.checkNotNull(value, "value"); ByteBuf buf = Unpooled.copiedBuffer(value, charset); this.value.add(rank, buf); size += buf.readableBytes(); } public void setValue(String value, int rank) { ObjectUtil.checkNotNull(value, "value"); ByteBuf buf = Unpooled.copiedBuffer(value, charset); ByteBuf old = this.value.set(rank, buf); if (old != null) { size -= old.readableBytes(); old.release(); } size += buf.readableBytes(); } @Override public int hashCode() { return getName().hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof QuarkusInternalAttribute)) { return false; } QuarkusInternalAttribute attribute = (QuarkusInternalAttribute) o; return getName().equalsIgnoreCase(attribute.getName()); } @Override public int compareTo(InterfaceHttpData o) { if (!(o instanceof QuarkusInternalAttribute)) { throw new ClassCastException("Cannot compare " + getHttpDataType() + " with " + o.getHttpDataType()); } return compareTo((QuarkusInternalAttribute) o); } public int compareTo(QuarkusInternalAttribute o) { return getName().compareToIgnoreCase(o.getName()); } @Override public String toString() { StringBuilder result = new StringBuilder(); for (ByteBuf elt : value) { result.append(elt.toString(charset)); } return result.toString(); } public int size() { return size; } public ByteBuf toByteBuf() { return Unpooled.compositeBuffer().addComponents(value).writerIndex(size()).readerIndex(0); } @Override public String getName() { return "InternalAttribute"; } @Override protected void deallocate() { // Do nothing } @Override public InterfaceHttpData retain() { for (ByteBuf buf : value) { buf.retain(); } return this; } @Override public InterfaceHttpData retain(int increment) { for (ByteBuf buf : value) { buf.retain(increment); } return this; } @Override public InterfaceHttpData touch() { for (ByteBuf buf : value) { buf.touch(); } return this; } @Override public InterfaceHttpData touch(Object hint) { for (ByteBuf buf : value) { buf.touch(hint); } return this; } }
QuarkusInternalAttribute
java
elastic__elasticsearch
x-pack/plugin/esql/qa/server/multi-node/src/javaRestTest/java/org/elasticsearch/xpack/esql/qa/multi_node/KnnSemanticTextIT.java
{ "start": 663, "end": 1005 }
class ____ extends KnnSemanticTextTestCase { @ClassRule public static ElasticsearchCluster cluster = Clusters.testCluster( spec -> spec.module("x-pack-inference").plugin("inference-service-test") ); @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } }
KnnSemanticTextIT
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/fields/RecursiveComparisonAssert_for_object_arrays_Test.java
{ "start": 1148, "end": 2279 }
class ____ extends WithComparingFieldsIntrospectionStrategyBaseTest { private final Person[] actual = { new Person("Sheldon"), new Person("Leonard") }; // verify we don't need to cast actual to an Object as before when only Object assertions provided usingRecursiveComparison() @Test void should_be_directly_usable_with_arrays() { // GIVEN PersonDto[] expected = { new PersonDto("Sheldon"), new PersonDto("Leonard") }; // WHEN/THEN then(actual).usingRecursiveComparison(recursiveComparisonConfiguration) .isEqualTo(expected); } @Test void should_propagate_comparator_by_type() { // WHEN var currentConfiguration = assertThat(actual).usingComparatorForType(ALWAYS_EQUALS_STRING, String.class) .usingRecursiveComparison(recursiveComparisonConfiguration) .getRecursiveComparisonConfiguration(); // THEN then(currentConfiguration.comparatorByTypes()).contains(entry(dualClass(String.class, null), ALWAYS_EQUALS_STRING)); } }
RecursiveComparisonAssert_for_object_arrays_Test
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/scanning/InjectedClassConverterField.java
{ "start": 77, "end": 517 }
class ____ { final String methodName; final String injectedClassName; public InjectedClassConverterField(String methodName, String injectedClassName) { this.methodName = methodName; this.injectedClassName = injectedClassName; } public String getMethodName() { return methodName; } public String getInjectedClassName() { return injectedClassName; } }
InjectedClassConverterField
java
netty__netty
buffer/src/main/java/io/netty/buffer/ReadOnlyUnsafeDirectByteBuf.java
{ "start": 1162, "end": 4020 }
class ____ slice the passed in ByteBuffer which means the memoryAddress // may be different if the position != 0. memoryAddress = PlatformDependent.directBufferAddress(buffer); } @Override protected byte _getByte(int index) { return UnsafeByteBufUtil.getByte(addr(index)); } @Override protected short _getShort(int index) { return UnsafeByteBufUtil.getShort(addr(index)); } @Override protected int _getUnsignedMedium(int index) { return UnsafeByteBufUtil.getUnsignedMedium(addr(index)); } @Override protected int _getInt(int index) { return UnsafeByteBufUtil.getInt(addr(index)); } @Override protected long _getLong(int index) { return UnsafeByteBufUtil.getLong(addr(index)); } @Override protected ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length, boolean internal) { checkIndex(index, length); ObjectUtil.checkNotNull(dst, "dst"); if (dstIndex < 0 || dstIndex > dst.capacity() - length) { throw new IndexOutOfBoundsException("dstIndex: " + dstIndex); } if (dst.hasMemoryAddress()) { PlatformDependent.copyMemory(addr(index), dst.memoryAddress() + dstIndex, length); } else if (dst.hasArray()) { PlatformDependent.copyMemory(addr(index), dst.array(), dst.arrayOffset() + dstIndex, length); } else { dst.setBytes(dstIndex, this, index, length); } return this; } @Override protected ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length, boolean internal) { checkIndex(index, length); ObjectUtil.checkNotNull(dst, "dst"); if (dstIndex < 0 || dstIndex > dst.length - length) { throw new IndexOutOfBoundsException(String.format( "dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dst.length)); } if (length != 0) { PlatformDependent.copyMemory(addr(index), dst, dstIndex, length); } return this; } @Override public ByteBuf copy(int index, int length) { checkIndex(index, length); ByteBuf copy = alloc().directBuffer(length, maxCapacity()); if (length != 0) { if (copy.hasMemoryAddress()) { PlatformDependent.copyMemory(addr(index), copy.memoryAddress(), length); copy.setIndex(0, length); } else { copy.writeBytes(this, index, length); } } return copy; } @Override public boolean hasMemoryAddress() { return true; } @Override public long memoryAddress() { return memoryAddress; } private long addr(int index) { return memoryAddress + index; } }
will
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/datafeed/DatafeedUpdateTests.java
{ "start": 3463, "end": 5477 }
class ____ extends AbstractXContentSerializingTestCase<DatafeedUpdate> { public static final String[] EXPAND_WILDCARDS_VALUES = { "open", "closed", "hidden" }; private ClusterState clusterState; @Before public void init() { clusterState = mock(ClusterState.class); } @Override protected DatafeedUpdate createTestInstance() { return createRandomized(DatafeedConfigTests.randomValidDatafeedId()); } public static DatafeedUpdate createRandomized(String datafeedId) { return createRandomized(datafeedId, null); } public static DatafeedUpdate createRandomized(String datafeedId, @Nullable DatafeedConfig datafeed) { DatafeedUpdate.Builder builder = new DatafeedUpdate.Builder(datafeedId); if (randomBoolean()) { builder.setQueryDelay(TimeValue.timeValueMillis(randomIntBetween(1, Integer.MAX_VALUE))); } if (randomBoolean()) { builder.setFrequency(TimeValue.timeValueSeconds(randomIntBetween(1, Integer.MAX_VALUE))); } if (randomBoolean()) { builder.setIndices(DatafeedConfigTests.randomStringList(1, 10)); } if (randomBoolean()) { builder.setQuery(createTestQueryProvider(randomAlphaOfLengthBetween(1, 10), randomAlphaOfLengthBetween(1, 10))); } if (randomBoolean()) { int scriptsSize = randomInt(3); List<SearchSourceBuilder.ScriptField> scriptFields = new ArrayList<>(scriptsSize); for (int scriptIndex = 0; scriptIndex < scriptsSize; scriptIndex++) { scriptFields.add( new SearchSourceBuilder.ScriptField(randomAlphaOfLength(10), mockScript(randomAlphaOfLength(10)), randomBoolean()) ); } builder.setScriptFields(scriptFields); } if (randomBoolean() && datafeed == null) { // can only test with a single agg as the xcontent order gets randomized by test base
DatafeedUpdateTests
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/resilience/ConcurrencyLimitTests.java
{ "start": 1866, "end": 6460 }
class ____ { @Test void withSimpleInterceptor() { NonAnnotatedBean target = new NonAnnotatedBean(); ProxyFactory pf = new ProxyFactory(); pf.setTarget(target); pf.addAdvice(new ConcurrencyThrottleInterceptor(2)); NonAnnotatedBean proxy = (NonAnnotatedBean) pf.getProxy(); List<CompletableFuture<?>> futures = new ArrayList<>(10); for (int i = 0; i < 10; i++) { futures.add(CompletableFuture.runAsync(proxy::concurrentOperation)); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); assertThat(target.current).hasValue(0); assertThat(target.counter).hasValue(10); } @Test void withPostProcessorForMethod() { AnnotatedMethodBean proxy = createProxy(AnnotatedMethodBean.class); AnnotatedMethodBean target = (AnnotatedMethodBean) AopProxyUtils.getSingletonTarget(proxy); List<CompletableFuture<?>> futures = new ArrayList<>(10); for (int i = 0; i < 10; i++) { futures.add(CompletableFuture.runAsync(proxy::concurrentOperation)); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); assertThat(target.current).hasValue(0); } @Test void withPostProcessorForMethodWithUnboundedConcurrency() { AnnotatedMethodBean proxy = createProxy(AnnotatedMethodBean.class); AnnotatedMethodBean target = (AnnotatedMethodBean) AopProxyUtils.getSingletonTarget(proxy); List<CompletableFuture<?>> futures = new ArrayList<>(10); for (int i = 0; i < 10; i++) { futures.add(CompletableFuture.runAsync(proxy::unboundedConcurrency)); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); assertThat(target.current).hasValue(10); } @Test void withPostProcessorForClass() { AnnotatedClassBean proxy = createProxy(AnnotatedClassBean.class); AnnotatedClassBean target = (AnnotatedClassBean) AopProxyUtils.getSingletonTarget(proxy); List<CompletableFuture<?>> futures = new ArrayList<>(30); for (int i = 0; i < 10; i++) { futures.add(CompletableFuture.runAsync(proxy::concurrentOperation)); } for (int i = 0; i < 10; i++) { futures.add(CompletableFuture.runAsync(proxy::otherOperation)); } for (int i = 0; i < 10; i++) { futures.add(CompletableFuture.runAsync(proxy::overrideOperation)); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); assertThat(target.current).hasValue(0); } @Test void withPlaceholderResolution() { MockPropertySource mockPropertySource = new MockPropertySource("test").withProperty("test.concurrency.limit", "3"); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.getEnvironment().getPropertySources().addFirst(mockPropertySource); ctx.register(PlaceholderTestConfig.class, PlaceholderBean.class); ctx.refresh(); PlaceholderBean proxy = ctx.getBean(PlaceholderBean.class); PlaceholderBean target = (PlaceholderBean) AopProxyUtils.getSingletonTarget(proxy); // Test with limit=3 from MockPropertySource List<CompletableFuture<?>> futures = new ArrayList<>(10); for (int i = 0; i < 10; i++) { futures.add(CompletableFuture.runAsync(proxy::concurrentOperation)); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); assertThat(target.current).hasValue(0); ctx.close(); } @Test void configurationErrors() { ConfigurationErrorsBean proxy = createProxy(ConfigurationErrorsBean.class); assertThatIllegalStateException() .isThrownBy(proxy::emptyDeclaration) .withMessageMatching("@.+?ConcurrencyLimit(.+?) must be configured with a valid limit") .withMessageContaining("\"\"") .withMessageContaining(String.valueOf(Integer.MIN_VALUE)); assertThatIllegalStateException() .isThrownBy(proxy::negative42Int) .withMessageMatching("@.+?ConcurrencyLimit(.+?) must be configured with a valid limit") .withMessageContaining("-42"); assertThatIllegalStateException() .isThrownBy(proxy::negative42String) .withMessageMatching("@.+?ConcurrencyLimit(.+?) must be configured with a valid limit") .withMessageContaining("-42"); assertThatExceptionOfType(NumberFormatException.class) .isThrownBy(proxy::alphanumericString) .withMessageContaining("B2"); } private static <T> T createProxy(Class<T> beanClass) { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerBeanDefinition("bean", new RootBeanDefinition(beanClass)); ConcurrencyLimitBeanPostProcessor bpp = new ConcurrencyLimitBeanPostProcessor(); bpp.setBeanFactory(bf); bf.addBeanPostProcessor(bpp); return bf.getBean(beanClass); } static
ConcurrencyLimitTests
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/HazelcastMapEndpointBuilderFactory.java
{ "start": 22493, "end": 22820 }
interface ____ extends AdvancedHazelcastMapEndpointConsumerBuilder, AdvancedHazelcastMapEndpointProducerBuilder { default HazelcastMapEndpointBuilder basic() { return (HazelcastMapEndpointBuilder) this; } } public
AdvancedHazelcastMapEndpointBuilder
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/commit/terasort/ITestTerasortOnS3A.java
{ "start": 3295, "end": 12750 }
class ____ extends AbstractYarnClusterITest { private static final Logger LOG = LoggerFactory.getLogger(ITestTerasortOnS3A.class); public static final int EXPECTED_PARTITION_COUNT = 10; public static final int PARTITION_SAMPLE_SIZE = 1000; public static final int ROW_COUNT = 1000; /** * Duration tracker created in the first of the test cases and closed * in {@link #test_140_teracomplete()}. */ private static Optional<DurationInfo> terasortDuration = empty(); /** * Tracker of which stages are completed and how long they took. */ private static Map<String, DurationInfo> completedStages = new HashMap<>(); /** Name of the committer for this run. */ private final String committerName; /** Should Magic committer track pending commits in-memory. */ private final boolean trackCommitsInMemory; /** Base path for all the terasort input and output paths. */ private Path terasortPath; /** Input (teragen) path. */ private Path sortInput; /** Path where sorted data goes. */ private Path sortOutput; /** Path for validated job's output. */ private Path sortValidate; /** * Test array for parameterized test runs. * * @return the committer binding for this run. */ public static Collection<Object[]> params() { return Arrays.asList(new Object[][]{ {DirectoryStagingCommitter.NAME, false}, {MagicS3GuardCommitter.NAME, false}, {MagicS3GuardCommitter.NAME, true}}); } public ITestTerasortOnS3A(final String committerName, final boolean trackCommitsInMemory) { this.committerName = committerName; this.trackCommitsInMemory = trackCommitsInMemory; } @Override protected String committerName() { return committerName; } @BeforeEach @Override public void setup() throws Exception { super.setup(); requireScaleTestsEnabled(); assumeMultipartUploads(getFileSystem().getConf()); prepareToTerasort(); } @Override protected void deleteTestDirInTeardown() throws IOException { /* no-op */ } /** * Set up the job conf with the options for terasort chosen by the scale * options. * @param conf configuration */ @Override protected void applyCustomConfigOptions(JobConf conf) { // small sample size for faster runs conf.setInt(TeraSortConfigKeys.SAMPLE_SIZE.key(), getSampleSizeForEachPartition()); conf.setInt(TeraSortConfigKeys.NUM_PARTITIONS.key(), getExpectedPartitionCount()); conf.setBoolean( TeraSortConfigKeys.USE_SIMPLE_PARTITIONER.key(), false); conf.setBoolean( CommitConstants.FS_S3A_COMMITTER_MAGIC_TRACK_COMMITS_IN_MEMORY_ENABLED, trackCommitsInMemory); } private int getExpectedPartitionCount() { return EXPECTED_PARTITION_COUNT; } private int getSampleSizeForEachPartition() { return PARTITION_SAMPLE_SIZE; } protected int getRowCount() { return ROW_COUNT; } /** * Set up the terasort by initializing paths variables * The paths used must be unique across parameterized runs but * common across all test cases in a single parameterized run. */ private void prepareToTerasort() throws IOException { // small sample size for faster runs terasortPath = getFileSystem().qualify( new Path(S3ATestUtils.createTestPath(new Path("terasort-test")), "terasort-" + committerName + "-" + trackCommitsInMemory)); sortInput = new Path(terasortPath, "sortin"); sortOutput = new Path(terasortPath, "sortout"); sortValidate = new Path(terasortPath, "validate"); } /** * Declare that a stage has completed. * @param stage stage name/key in the map * @param d duration. */ private static void completedStage(final String stage, final DurationInfo d) { completedStages.put(stage, d); } /** * Declare a stage which is required for this test case. * @param stage stage name */ private static void requireStage(final String stage) { assumeTrue(completedStages.get(stage) != null, "Required stage was not completed: " + stage); } /** * Execute a single stage in the terasort. * Updates the completed stages map with the stage duration -if successful. * @param stage Stage name for the stages map. * @param jobConf job conf * @param dest destination directory -the _SUCCESS file will be expected here. * @param tool tool to run. * @param args args for the tool. * @param minimumFileCount minimum number of files to have been created * @throws Exception any failure */ private void executeStage( final String stage, final JobConf jobConf, final Path dest, final Tool tool, final String[] args, final int minimumFileCount) throws Exception { int result; DurationInfo d = new DurationInfo(LOG, stage); try { result = ToolRunner.run(jobConf, tool, args); } finally { d.close(); } dumpOutputTree(dest); assertThat(result) .describedAs(stage + "(" + StringUtils.join(", ", args) + ")" + " failed") .isEqualTo(0); validateSuccessFile(dest, committerName(), getFileSystem(), stage, minimumFileCount, ""); completedStage(stage, d); } /** * Set up terasort by cleaning out the destination, and note the initial * time before any of the jobs are executed. * * This is executed first <i>for each parameterized run</i>. * It is where all variables which need to be reset for each run need * to be reset. */ @Test public void test_100_terasort_setup() throws Throwable { describe("Setting up for a terasort with path of %s", terasortPath); getFileSystem().delete(terasortPath, true); completedStages = new HashMap<>(); terasortDuration = Optional.of(new DurationInfo(LOG, false, "Terasort")); } @Test public void test_110_teragen() throws Throwable { describe("Teragen to %s", sortInput); getFileSystem().delete(sortInput, true); JobConf jobConf = newJobConf(); patchConfigurationForCommitter(jobConf); executeStage("teragen", jobConf, sortInput, new TeraGen(), new String[]{Integer.toString(getRowCount()), sortInput.toString()}, 1); } @Test public void test_120_terasort() throws Throwable { describe("Terasort from %s to %s", sortInput, sortOutput); requireStage("teragen"); getFileSystem().delete(sortOutput, true); loadSuccessFile(getFileSystem(), sortInput, "previous teragen stage"); JobConf jobConf = newJobConf(); patchConfigurationForCommitter(jobConf); executeStage("terasort", jobConf, sortOutput, new TeraSort(), new String[]{sortInput.toString(), sortOutput.toString()}, 1); } @Test public void test_130_teravalidate() throws Throwable { describe("TeraValidate from %s to %s", sortOutput, sortValidate); requireStage("terasort"); getFileSystem().delete(sortValidate, true); loadSuccessFile(getFileSystem(), sortOutput, "previous terasort stage"); JobConf jobConf = newJobConf(); patchConfigurationForCommitter(jobConf); executeStage("teravalidate", jobConf, sortValidate, new TeraValidate(), new String[]{sortOutput.toString(), sortValidate.toString()}, 1); } /** * Print the results, and save to the base dir as a CSV file. * Why there? Makes it easy to list and compare. */ @Test public void test_140_teracomplete() throws Throwable { terasortDuration.ifPresent(d -> { d.close(); completedStage("overall", d); }); final StringBuilder results = new StringBuilder(); results.append("\"Operation\"\t\"Duration\"\n"); // this is how you dynamically create a function in a method // for use afterwards. // Works because there's no IOEs being raised in this sequence. Consumer<String> stage = (s) -> { DurationInfo duration = completedStages.get(s); results.append(String.format("\"%s\"\t\"%s\"\n", s, duration == null ? "" : duration)); }; stage.accept("teragen"); stage.accept("terasort"); stage.accept("teravalidate"); stage.accept("overall"); String text = results.toString(); File resultsFile = new File(getReportDir(), String.format("%s-%s.csv", committerName, trackCommitsInMemory)); FileUtils.write(resultsFile, text, StandardCharsets.UTF_8); LOG.info("Results are in {}\n{}", resultsFile, text); } /** * Reset the duration so if two committer tests are run sequentially. * Without this the total execution time is reported as from the start of * the first test suite to the end of the second. */ @Test public void test_150_teracleanup() throws Throwable { terasortDuration = Optional.empty(); } @Test public void test_200_directory_deletion() throws Throwable { getFileSystem().delete(terasortPath, true); } /** * Dump the files under a path -but not fail if the path is not present., * @param path path to dump * @throws Exception any failure. */ protected void dumpOutputTree(Path path) throws Exception { LOG.info("Files under output directory {}", path); try { lsR(getFileSystem(), path, true); } catch (FileNotFoundException e) { LOG.info("Output directory {} not found", path); } } }
ITestTerasortOnS3A
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/index/engine/TranslogHandler.java
{ "start": 1631, "end": 6218 }
class ____ implements Engine.TranslogRecoveryRunner { private final MapperService mapperService; private final AtomicLong appliedOperations = new AtomicLong(); long appliedOperations() { return appliedOperations.get(); } public TranslogHandler(MapperService mapperService) { this.mapperService = mapperService; } public TranslogHandler(NamedXContentRegistry xContentRegistry, IndexSettings indexSettings) { SimilarityService similarityService = new SimilarityService(indexSettings, null, emptyMap()); MapperRegistry mapperRegistry = new IndicesModule(emptyList()).getMapperRegistry(); mapperService = new MapperService( () -> TransportVersion.current(), indexSettings, (type, name) -> Lucene.STANDARD_ANALYZER, XContentParserConfiguration.EMPTY.withRegistry(xContentRegistry).withDeprecationHandler(LoggingDeprecationHandler.INSTANCE), similarityService, mapperRegistry, () -> null, indexSettings.getMode().idFieldMapperWithoutFieldData(), null, query -> { throw new UnsupportedOperationException("The bitset filter cache is not available in translog operations"); }, MapperMetrics.NOOP ); } private static void applyOperation(Engine engine, Engine.Operation operation) throws IOException { switch (operation.operationType()) { case INDEX -> engine.index((Engine.Index) operation); case DELETE -> engine.delete((Engine.Delete) operation); case NO_OP -> engine.noOp((Engine.NoOp) operation); default -> throw new IllegalStateException("No operation defined for [" + operation + "]"); } } @Override public int run(Engine engine, Translog.Snapshot snapshot) throws IOException { int opsRecovered = 0; Translog.Operation operation; while ((operation = snapshot.next()) != null) { applyOperation(engine, convertToEngineOp(operation, Engine.Operation.Origin.LOCAL_TRANSLOG_RECOVERY)); opsRecovered++; appliedOperations.incrementAndGet(); } engine.syncTranslog(); return opsRecovered; } public Engine.Operation convertToEngineOp(Translog.Operation operation, Engine.Operation.Origin origin) { // If a translog op is replayed on the primary (eg. ccr), we need to use external instead of null for its version type. final VersionType versionType = (origin == Engine.Operation.Origin.PRIMARY) ? VersionType.EXTERNAL : null; switch (operation.opType()) { case INDEX -> { final Translog.Index index = (Translog.Index) operation; final Engine.Index engineIndex = IndexShard.prepareIndex( mapperService, new SourceToParse( Uid.decodeId(index.uid()), index.source(), XContentHelper.xContentType(index.source()), index.routing() ), index.seqNo(), index.primaryTerm(), index.version(), versionType, origin, index.getAutoGeneratedIdTimestamp(), true, SequenceNumbers.UNASSIGNED_SEQ_NO, SequenceNumbers.UNASSIGNED_PRIMARY_TERM, System.nanoTime() ); return engineIndex; } case DELETE -> { final Translog.Delete delete = (Translog.Delete) operation; return IndexShard.prepareDelete( Uid.decodeId(delete.uid()), delete.seqNo(), delete.primaryTerm(), delete.version(), versionType, origin, SequenceNumbers.UNASSIGNED_SEQ_NO, SequenceNumbers.UNASSIGNED_PRIMARY_TERM ); } case NO_OP -> { final Translog.NoOp noOp = (Translog.NoOp) operation; final Engine.NoOp engineNoOp = new Engine.NoOp(noOp.seqNo(), noOp.primaryTerm(), origin, System.nanoTime(), noOp.reason()); return engineNoOp; } default -> throw new IllegalStateException("No operation defined for [" + operation + "]"); } } }
TranslogHandler
java
alibaba__druid
core/src/test/java/com/alibaba/druid/pool/ha/node/FileNodeListenerTest.java
{ "start": 533, "end": 4991 }
class ____ { @Test public void testHaWithPropertiesFile() throws Exception { // init a properties file String folder = System.getProperty("java.io.tmpdir"); File file = new File(folder + "/ha.properties"); file.deleteOnExit(); Properties properties = new Properties(); properties.setProperty("bar.username", "sa"); properties.setProperty("bar.password", ""); properties.setProperty("bar.url", "jdbc:derby:memory:bar;create=true"); writePropertiesFile(file, properties); // init HighAvailableDataSource FileNodeListener listener = new FileNodeListener(); listener.setFile(file.getAbsolutePath()); listener.setPrefix("foo"); listener.setIntervalSeconds(1); HighAvailableDataSource dataSource = new HighAvailableDataSource(); dataSource.setPoolPurgeIntervalSeconds(5); dataSource.setDataSourceFile(file.getAbsolutePath()); dataSource.setNodeListener(listener); dataSource.init(); assertTrue(dataSource.getDataSourceMap().isEmpty()); // Add one valid DataSource properties.setProperty("foo.username", "sa"); properties.setProperty("foo.password", ""); properties.setProperty("foo.url", "jdbc:derby:memory:foo;create=true"); writePropertiesFile(file, properties); Thread.sleep(6000); assertEquals(1, dataSource.getAvailableDataSourceMap().size()); DruidDataSource foo = (DruidDataSource) dataSource.getAvailableDataSourceMap().get("foo"); assertEquals("jdbc:derby:memory:foo;create=true", foo.getUrl()); // try to emove all but we have to keep one left writePropertiesFile(file, new Properties()); Thread.sleep(6000); assertEquals(1, dataSource.getAvailableDataSourceMap().size()); dataSource.destroy(); } private void writePropertiesFile(File file, Properties properties) throws IOException { FileWriter writer = new FileWriter(file); properties.store(writer, ""); writer.close(); } @Test public void testUpdate() throws InterruptedException { final CountDownLatch cdl = new CountDownLatch(1); String file = "/com/alibaba/druid/pool/ha/ha-with-prefix-datasource.properties"; FileNodeListener listener = new FileNodeListener(); listener.setFile(file); listener.setPrefix("prefix1"); listener.setObserver(new Observer() { @Override public void update(Observable o, Object arg) { cdl.countDown(); assertTrue(o instanceof FileNodeListener); assertTrue(arg instanceof NodeEvent[]); NodeEvent[] events = (NodeEvent[]) arg; assertEquals(1, events.length); assertEquals(NodeEventTypeEnum.ADD, events[0].getType()); assertEquals("prefix1.foo", events[0].getNodeName()); assertEquals("jdbc:derby:memory:foo1;create=true", events[0].getUrl()); } }); listener.init(); listener.update(); assertTrue(cdl.await(100, TimeUnit.MILLISECONDS)); } @Test public void testRefresh_emptyPropertiesMatch() { String file = "/com/alibaba/druid/pool/ha/ha-with-prefix-datasource.properties"; FileNodeListener listener = new FileNodeListener(); listener.setFile(file); listener.setPrefix("prefix0"); List<NodeEvent> list = listener.refresh(); assertTrue(listener.getProperties().isEmpty()); assertTrue(list.isEmpty()); } @Test public void testRefresh() { String file = "/com/alibaba/druid/pool/ha/ha-with-prefix-datasource.properties"; FileNodeListener listener = new FileNodeListener(); listener.setFile(file); listener.setPrefix("prefix1"); List<NodeEvent> list = listener.refresh(); Properties properties = listener.getProperties(); assertEquals(3, properties.size()); assertEquals("jdbc:derby:memory:foo1;create=true", properties.getProperty("prefix1.foo.url")); assertEquals(1, list.size()); NodeEvent event = list.get(0); assertEquals(NodeEventTypeEnum.ADD, event.getType()); assertEquals("prefix1.foo", event.getNodeName()); assertEquals("jdbc:derby:memory:foo1;create=true", event.getUrl()); } }
FileNodeListenerTest
java
spring-projects__spring-framework
spring-context-indexer/src/test/java/org/springframework/context/index/sample/type/AbstractRepo.java
{ "start": 733, "end": 784 }
class ____<T, I> implements Repo<T, I> { }
AbstractRepo
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestFsOptions.java
{ "start": 1037, "end": 2483 }
class ____ { @Test public void testProcessChecksumOpt() { ChecksumOpt defaultOpt = new ChecksumOpt(DataChecksum.Type.CRC32, 512); ChecksumOpt finalOpt; // Give a null finalOpt = ChecksumOpt.processChecksumOpt(defaultOpt, null); checkParams(defaultOpt, finalOpt); // null with bpc finalOpt = ChecksumOpt.processChecksumOpt(defaultOpt, null, 1024); checkParams(DataChecksum.Type.CRC32, 1024, finalOpt); ChecksumOpt myOpt = new ChecksumOpt(); // custom with unspecified parameters finalOpt = ChecksumOpt.processChecksumOpt(defaultOpt, myOpt); checkParams(defaultOpt, finalOpt); myOpt = new ChecksumOpt(DataChecksum.Type.CRC32C, 2048); // custom config finalOpt = ChecksumOpt.processChecksumOpt(defaultOpt, myOpt); checkParams(DataChecksum.Type.CRC32C, 2048, finalOpt); // custom config + bpc finalOpt = ChecksumOpt.processChecksumOpt(defaultOpt, myOpt, 4096); checkParams(DataChecksum.Type.CRC32C, 4096, finalOpt); } private void checkParams(ChecksumOpt expected, ChecksumOpt obtained) { assertEquals(expected.getChecksumType(), obtained.getChecksumType()); assertEquals(expected.getBytesPerChecksum(), obtained.getBytesPerChecksum()); } private void checkParams(DataChecksum.Type type, int bpc, ChecksumOpt obtained) { assertEquals(type, obtained.getChecksumType()); assertEquals(bpc, obtained.getBytesPerChecksum()); } }
TestFsOptions
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3104/Issue3104Mapper.java
{ "start": 1503, "end": 1770 }
class ____ { private final List<ChildSource> children; public Source(List<ChildSource> children) { this.children = children; } public List<ChildSource> getChildren() { return children; } }
Source
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/ancestor_ref/Blog.java
{ "start": 708, "end": 1309 }
class ____ { private Integer id; private String title; private Author author; private Author coAuthor; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Author getCoAuthor() { return coAuthor; } public void setCoAuthor(Author coAuthor) { this.coAuthor = coAuthor; } }
Blog