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
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractAtomicFieldUpdaterAssert.java
{ "start": 796, "end": 1130 }
class ____ all fieldupdater assertions. * * @param <SELF> the "self" type of this assertion class. * @param <VALUE> the type of the "actual" value. * @param <ATOMIC> the type of the "actual" atomic. * @param <OBJECT> the type of the object holding the updatable field. * @author epeee * @since 2.7.0 / 3.7.0 */ public abstract
for
java
quarkusio__quarkus
devtools/cli-common/src/test/java/io/quarkus/cli/common/gradle/GradleInitScriptTest.java
{ "start": 423, "end": 2353 }
class ____ { @Test public void testGetInitScript() { assertTrue(GradleInitScript.getInitScript(List.of("arg1", "arg2", "arg3")).isEmpty()); assertEquals("/some/path", GradleInitScript.getInitScript(List.of("arg1", "arg2", "--init-script=/some/path")).get()); assertEquals("/some/path", GradleInitScript.getInitScript(List.of("arg1", "--init-script=/some/path", "arg3")).get()); assertEquals("/some/path", GradleInitScript.getInitScript(List.of("--init-script=/some/path", "arg2", "arg3")).get()); } @Test public void testReadInitScriptDependencies() throws IOException { Path path = GradleInitScript.createInitScript(Set.of("g1:a1:v1", "g2:a2:v2")); System.out.println("path:" + path.toAbsolutePath().toString()); System.out.println("content:" + Files.readString(path)); List<String> gavs = GradleInitScript.readInitScriptDependencies(path); System.out.println("deps:" + gavs.stream().collect(Collectors.joining(", ", "[", "]"))); assertTrue(gavs.contains("g1:a1:v1")); assertTrue(gavs.contains("g2:a2:v2")); } @Test public void shouldGenerateSignleInitScriptParam() throws IOException { List<String> params = new ArrayList<>(); GradleInitScript.populateForExtensions(List.of("g1:a1"), params); GradleInitScript.populateForExtensions(List.of("g2:a2"), params); assertEquals(1l, params.stream().filter(p -> p.contains("--init-script=")).count()); Optional<Path> path = GradleInitScript.getInitScript(params).map(Path::of); List<String> gavs = GradleInitScript.readInitScriptDependencies(path.get()); System.out.println("gavs:" + gavs.stream().collect(Collectors.joining(",", "[", "]"))); assertTrue(gavs.contains("g1:a1:${quarkusPlatformVersion}")); assertTrue(gavs.contains("g2:a2:${quarkusPlatformVersion}")); } }
GradleInitScriptTest
java
elastic__elasticsearch
x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/operator/OperatorPrivilegesSingleNodeTests.java
{ "start": 1515, "end": 6959 }
class ____ extends SecuritySingleNodeTestCase { private static final String OPERATOR_USER_NAME = "test_operator"; @Override protected String configUsers() { return super.configUsers() + OPERATOR_USER_NAME + ":" + TEST_PASSWORD_HASHED + "\n"; } @Override protected String configRoles() { return super.configRoles() + """ limited_operator: cluster: - 'cluster:admin/voting_config/clear_exclusions' - 'cluster:admin/settings/update' - 'monitor' """; } @Override protected String configUsersRoles() { return super.configUsersRoles() + "limited_operator:" + OPERATOR_USER_NAME + "\n"; } @Override protected String configOperatorUsers() { return super.configOperatorUsers() + "operator:\n" + " - usernames: ['" + OPERATOR_USER_NAME + "']\n"; } @Override protected Settings nodeSettings() { Settings.Builder builder = Settings.builder().put(super.nodeSettings()); // Ensure the new settings can be configured builder.put("xpack.security.operator_privileges.enabled", "true"); return builder.build(); } public void testNormalSuperuserWillFailToCallOperatorOnlyAction() { final ClearVotingConfigExclusionsRequest clearVotingConfigExclusionsRequest = new ClearVotingConfigExclusionsRequest( TEST_REQUEST_TIMEOUT ); final ElasticsearchSecurityException e = expectThrows( ElasticsearchSecurityException.class, () -> client().execute(TransportClearVotingConfigExclusionsAction.TYPE, clearVotingConfigExclusionsRequest).actionGet() ); assertThat(e.getCause().getMessage(), containsString("Operator privileges are required for action")); } public void testNormalSuperuserWillFailToSetOperatorOnlySettings() { final Settings settings = Settings.builder().put(IPFilter.IP_FILTER_ENABLED_SETTING.getKey(), "null").build(); final ClusterUpdateSettingsRequest clusterUpdateSettingsRequest = new ClusterUpdateSettingsRequest( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT ); if (randomBoolean()) { clusterUpdateSettingsRequest.transientSettings(settings); } else { clusterUpdateSettingsRequest.persistentSettings(settings); } final ElasticsearchSecurityException e = expectThrows( ElasticsearchSecurityException.class, () -> client().execute(ClusterUpdateSettingsAction.INSTANCE, clusterUpdateSettingsRequest).actionGet() ); assertThat(e.getCause().getMessage(), containsString("Operator privileges are required for setting")); } public void testOperatorUserWillSucceedToCallOperatorOnlyAction() { final Client client = createOperatorClient(); final ClearVotingConfigExclusionsRequest clearVotingConfigExclusionsRequest = new ClearVotingConfigExclusionsRequest( TEST_REQUEST_TIMEOUT ); client.execute(TransportClearVotingConfigExclusionsAction.TYPE, clearVotingConfigExclusionsRequest).actionGet(); } public void testOperatorUserWillSucceedToSetOperatorOnlySettings() { final Client client = createOperatorClient(); final ClusterUpdateSettingsRequest clusterUpdateSettingsRequest = new ClusterUpdateSettingsRequest( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT ); final Settings settings = Settings.builder().put(IPFilter.IP_FILTER_ENABLED_SETTING.getKey(), false).build(); final boolean useTransientSetting = randomBoolean(); try { if (useTransientSetting) { clusterUpdateSettingsRequest.transientSettings(settings); } else { clusterUpdateSettingsRequest.persistentSettings(settings); } client.execute(ClusterUpdateSettingsAction.INSTANCE, clusterUpdateSettingsRequest).actionGet(); } finally { final ClusterUpdateSettingsRequest clearSettingsRequest = new ClusterUpdateSettingsRequest( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT ); final Settings clearSettings = Settings.builder().putNull(IPFilter.IP_FILTER_ENABLED_SETTING.getKey()).build(); if (useTransientSetting) { clearSettingsRequest.transientSettings(clearSettings); } else { clearSettingsRequest.persistentSettings(clearSettings); } client.execute(ClusterUpdateSettingsAction.INSTANCE, clearSettingsRequest).actionGet(); } } public void testOperatorUserIsStillSubjectToRoleLimits() { final Client client = createOperatorClient(); final GetUsersRequest getUsersRequest = new GetUsersRequest(); final ElasticsearchSecurityException e = expectThrows( ElasticsearchSecurityException.class, () -> client.execute(GetUsersAction.INSTANCE, getUsersRequest).actionGet() ); assertThat(e.getMessage(), containsString("is unauthorized for user")); } private Client createOperatorClient() { return client().filterWithHeader( Map.of("Authorization", basicAuthHeaderValue(OPERATOR_USER_NAME, new SecureString(TEST_PASSWORD.toCharArray()))) ); } }
OperatorPrivilegesSingleNodeTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/TimerSerializerSnapshot.java
{ "start": 1111, "end": 2318 }
class ____<K, N> extends CompositeTypeSerializerSnapshot< TimerHeapInternalTimer<K, N>, TimerSerializer<K, N>> { private static final int VERSION = 2; public TimerSerializerSnapshot() {} public TimerSerializerSnapshot(TimerSerializer<K, N> timerSerializer) { super(timerSerializer); } @Override protected int getCurrentOuterSnapshotVersion() { return VERSION; } @Override protected TimerSerializer<K, N> createOuterSerializerWithNestedSerializers( TypeSerializer<?>[] nestedSerializers) { @SuppressWarnings("unchecked") final TypeSerializer<K> keySerializer = (TypeSerializer<K>) nestedSerializers[0]; @SuppressWarnings("unchecked") final TypeSerializer<N> namespaceSerializer = (TypeSerializer<N>) nestedSerializers[1]; return new TimerSerializer<>(keySerializer, namespaceSerializer); } @Override protected TypeSerializer<?>[] getNestedSerializers(TimerSerializer<K, N> outerSerializer) { return new TypeSerializer<?>[] { outerSerializer.getKeySerializer(), outerSerializer.getNamespaceSerializer() }; } }
TimerSerializerSnapshot
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/DockerBuildTask.java
{ "start": 4827, "end": 9519 }
class ____ implements WorkAction<Parameters> { private final ExecOperations execOperations; @Inject public DockerBuildAction(ExecOperations execOperations) { this.execOperations = execOperations; } /** * Wraps `docker pull` in a retry loop, to try and provide some resilience against * transient errors * @param baseImage the image to pull. */ private void pullBaseImage(String baseImage) { final int maxAttempts = 10; for (int attempt = 1; attempt <= maxAttempts; attempt++) { try { LoggedExec.exec(execOperations, spec -> { maybeConfigureDockerConfig(spec); spec.executable("docker"); spec.args("pull"); spec.environment("DOCKER_BUILDKIT", "1"); spec.args(baseImage); }); return; } catch (Exception e) { LOGGER.warn("Attempt {}/{} to pull Docker base image {} failed", attempt, maxAttempts, baseImage); } } // If we successfully ran `docker pull` above, we would have returned before this point. throw new GradleException("Failed to pull Docker base image [" + baseImage + "], all attempts failed"); } private void maybeConfigureDockerConfig(ExecSpec spec) { String dockerConfig = System.getenv("DOCKER_CONFIG"); if (dockerConfig != null) { spec.environment("DOCKER_CONFIG", dockerConfig); } } @Override public void execute() { final Parameters parameters = getParameters(); if (parameters.getPull().get()) { parameters.getBaseImages().get().forEach(this::pullBaseImage); } final List<String> tags = parameters.getTags().get(); final boolean isCrossPlatform = isCrossPlatform(); LoggedExec.exec(execOperations, spec -> { maybeConfigureDockerConfig(spec); spec.executable("docker"); spec.environment("DOCKER_BUILDKIT", "1"); if (isCrossPlatform) { spec.args("buildx"); } spec.args("build", parameters.getDockerContext().get().getAsFile().getAbsolutePath()); if (isCrossPlatform) { spec.args("--platform", parameters.getPlatforms().get().stream().collect(Collectors.joining(","))); } if (parameters.getNoCache().get()) { spec.args("--no-cache"); } tags.forEach(tag -> spec.args("--tag", tag)); parameters.getBuildArgs().get().forEach((k, v) -> spec.args("--build-arg", k + "=" + v)); if (parameters.getPush().getOrElse(false)) { spec.args("--push"); } }); // Fetch the Docker image's hash, and write it to desk as the task's output. Doing this allows us // to do proper up-to-date checks in Gradle. try { // multi-platform image builds do not end up in local registry, so we need to pull the just build image // first to get the checksum and also serves as a test for the image being pushed correctly if (parameters.getPlatforms().get().size() > 1 && parameters.getPush().getOrElse(false)) { pullBaseImage(tags.get(0)); } final String checksum = getImageChecksum(tags.get(0)); Files.writeString(parameters.getMarkerFile().getAsFile().get().toPath(), checksum + "\n"); } catch (IOException e) { throw new RuntimeException("Failed to write marker file", e); } } private boolean isCrossPlatform() { return getParameters().getPlatforms() .get() .stream() .anyMatch(any -> any.equals(Architecture.current().dockerPlatform) == false); } private String getImageChecksum(String imageTag) { final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); execOperations.exec(spec -> { spec.setCommandLine("docker", "inspect", "--format", "{{ .Id }}", imageTag); spec.setStandardOutput(stdout); spec.setIgnoreExitValue(false); }); return stdout.toString().trim(); } }
DockerBuildAction
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/generic/DataRepositoryGenericParametersTest.java
{ "start": 1917, "end": 9448 }
class ____ { @Test @IgnoreCompilationErrors @WithClasses({Cat.class, CatRepository.class}) public void test() throws NoSuchMethodException { final var repositoryClass = CatRepository.class; System.out.println( getMetaModelSourceAsString( repositoryClass ) ); assertMetamodelClassGeneratedFor( repositoryClass ); final var types = new HashMap<Class<?>, Map<String, String>>(); collectTypeParameters( repositoryClass, types, Object.class ); final var actualTypes = ActualTypes.actualTypes( repositoryClass ); final Class<?> metamodelClass = getMetamodelClassFor( repositoryClass ); final var methodList = new HashSet<Method>(); getMethods( repositoryClass, methodList ); final var methods = methodList.stream().sorted( comparing( Method::getName ) ).toList(); for ( final var method : methods ) { final Class<?> methodDeclaringClass = method.getDeclaringClass(); final var genericParameterTypes = method.getGenericParameterTypes(); final var actualTypeArgumentsX = stream( genericParameterTypes ) .map( t -> actualTypes.getActualType( t, methodDeclaringClass ) ) .toArray( Type[]::new ); final var classes = stream( actualTypeArgumentsX ).map( DataRepositoryGenericParametersTest::toClass ).toArray( Class[]::new ); final var method1 = metamodelClass.getMethod( method.getName(), classes ); final var genericParameterTypes1 = method1.getGenericParameterTypes(); for ( var n = 0; n < genericParameterTypes.length; ++n ) { final var expected = actualTypeArgumentsX[n]; final var actual = genericParameterTypes1[n]; assertFalse( expected instanceof ParameterizedType && actual instanceof Class, "Failed for method " + method.toGenericString() ); final var expectedTypeName = expected.getTypeName(); final var actualTypeName = actual.getTypeName(); assertEquals( expectedTypeName, actualTypeName, "Failed for parameter %d of method %s".formatted( n, method.toGenericString() ) ); } } } private static Class<?> toClass(Type t) { if ( Objects.requireNonNull( t ) instanceof Class<?> c ) { return c; } else if ( t instanceof ParameterizedType pt ) { return (Class<?>) pt.getRawType(); } else if ( t instanceof TypeVariable<?> tv ) { return (Class<?>) tv.getBounds()[0]; } else if ( t instanceof GenericArrayType at ) { final var componentType = at.getGenericComponentType(); final var ct = toClass( componentType ); return ct.arrayType(); } throw new IllegalStateException( "Unexpected value: " + t ); } private void collectTypeParameters(Type type, Map<Class<?>, Map<String, String>> acc, Type subType) throws IllegalStateException { Class<?> key; if ( Objects.requireNonNull( subType ) instanceof ParameterizedType pt ) { key = (Class<?>) pt.getRawType(); } else if ( subType instanceof Class<?> cls ) { key = cls; } else { throw new IllegalStateException( "Unexpected value: " + subType ); } final var paramsMap = requireNonNullElseGet( acc.get( key ), Map::<String, String>of ); final Class<?> clazz; if ( type instanceof ParameterizedType pt ) { final var params = new HashMap<String, String>(); //noinspection rawtypes clazz = (Class) pt.getRawType(); final var typeParameters = clazz.getTypeParameters(); final var actualTypeArguments = pt.getActualTypeArguments(); for ( var n = 0; n < typeParameters.length; ++n ) { final var typeName = actualTypeArguments[n].getTypeName(); params.put( typeParameters[n].getName(), requireNonNullElse( paramsMap.get( typeName ), typeName ) ); } acc.put( clazz, params ); } else if ( type instanceof Class<?> cls ) { acc.put( cls, Map.of() ); clazz = cls; } else { throw new IllegalStateException( "Unexpected value: %s".formatted( type ) ); } for ( final var itype : clazz.getGenericInterfaces() ) { collectTypeParameters( itype, acc, type ); } } private void getMethods(Class<?> clazz, Collection<Method> methods) { addAll( methods, clazz.getDeclaredMethods() ); for ( final var iface : clazz.getInterfaces() ) { getMethods( iface, methods ); } } private record AnnotatedTypeImpl(AnnotatedType annotatedType, Type actualType) implements AnnotatedType { @Override public Type getType() { return actualType; } @Override public <T extends Annotation> T getAnnotation(@Nonnull Class<T> annotationClass) { return annotatedType.getAnnotation( annotationClass ); } @Override @Nonnull public Annotation[] getAnnotations() { return annotatedType.getAnnotations(); } @Override @Nonnull public Annotation[] getDeclaredAnnotations() { return annotatedType.getDeclaredAnnotations(); } } private record TypeVariableImpl(TypeVariable<?> tv, Type[] bounds, AnnotatedType[] annotatedBounds) implements TypeVariable<GenericDeclaration> { @Override public String getTypeName() { return tv.getTypeName(); } @Override @Nullable public <T extends Annotation> T getAnnotation(@Nonnull Class<T> annotationClass) { return tv.getAnnotation( annotationClass ); } @Override @Nonnull public Annotation[] getAnnotations() { return tv.getAnnotations(); } @Override @Nonnull public Annotation[] getDeclaredAnnotations() { return tv.getDeclaredAnnotations(); } @Override @Nonnull public Type[] getBounds() { return bounds; } @Override public GenericDeclaration getGenericDeclaration() { return tv.getGenericDeclaration(); } @Override public String getName() { return tv.getName(); } @Override public @Nonnull AnnotatedType[] getAnnotatedBounds() { return annotatedBounds; } } private record WildcardTypeImpl(Type[] upper, Type[] lower) implements WildcardType { @Override public String getTypeName() { return "?" + (upper.length > 0 ? " extends " + upper[0].getTypeName() : "") + (lower.length > 0 ? " super " + lower[0].getTypeName() : ""); } @Override @Nonnull public Type[] getUpperBounds() { return upper; } @Override @Nonnull public Type[] getLowerBounds() { return lower; } } private record ParameterizedTypeImpl(Type rawType, Type[] typeArguments, @Nullable Type ownerType) implements ParameterizedType { @Override public Type[] getActualTypeArguments() { return typeArguments; } @Override public Type getRawType() { return rawType; } @Override @Nullable public Type getOwnerType() { return ownerType; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); if ( ownerType != null ) { sb.append( ownerType.getTypeName() ); sb.append( "$" ); if ( ownerType instanceof ParameterizedType parameterizedType ) { // Find simple name of nested type by removing the // shared prefix with owner. sb.append( rawType.getTypeName().replace( parameterizedType.getRawType().getTypeName() + "$", "" ) ); } else if ( rawType instanceof Class<?> clazz ) { sb.append( clazz.getSimpleName() ); } else { sb.append( rawType.getTypeName() ); } } else { sb.append( rawType.getTypeName() ); } if ( typeArguments != null ) { final StringJoiner sj = new StringJoiner( ", ", "<", ">" ); sj.setEmptyValue( "" ); for ( Type t : typeArguments ) { sj.add( t.getTypeName() ); } sb.append( sj ); } return sb.toString(); } } private static
DataRepositoryGenericParametersTest
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/sagemaker/SageMakerServiceTests.java
{ "start": 4087, "end": 23413 }
class ____ extends InferenceServiceTestCase { private static final String QUERY = "query"; private static final List<String> INPUT = List.of("input"); private static final InputType INPUT_TYPE = InputType.UNSPECIFIED; private SageMakerModelBuilder modelBuilder; private SageMakerClient client; private SageMakerSchemas schemas; private SageMakerService sageMakerService; private ThreadPool threadPool; @Before public void init() { modelBuilder = mock(); client = mock(); schemas = mock(); threadPool = mock(); when(threadPool.executor(anyString())).thenReturn(EsExecutors.DIRECT_EXECUTOR_SERVICE); when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY)); sageMakerService = new SageMakerService(modelBuilder, client, schemas, threadPool, Map::of, mockClusterServiceEmpty()); } public void testSupportedTaskTypes() { sageMakerService.supportedTaskTypes(); verify(schemas, only()).supportedTaskTypes(); } public void testSupportedStreamingTasks() { sageMakerService.supportedStreamingTasks(); verify(schemas, only()).supportedStreamingTasks(); } public void testParseRequestConfig() { sageMakerService.parseRequestConfig("modelId", TaskType.ANY, Map.of(), assertNoFailureListener(model -> { verify(modelBuilder, only()).fromRequest(eq("modelId"), eq(TaskType.ANY), eq(SageMakerService.NAME), eq(Map.of())); })); } public void testParsePersistedConfigWithSecrets() { sageMakerService.parsePersistedConfigWithSecrets("modelId", TaskType.ANY, Map.of(), Map.of()); verify(modelBuilder, only()).fromStorage(eq("modelId"), eq(TaskType.ANY), eq(SageMakerService.NAME), eq(Map.of()), eq(Map.of())); } public void testParsePersistedConfig() { sageMakerService.parsePersistedConfig("modelId", TaskType.ANY, Map.of()); verify(modelBuilder, only()).fromStorage(eq("modelId"), eq(TaskType.ANY), eq(SageMakerService.NAME), eq(Map.of()), eq(null)); } public void testInferWithWrongModel() { sageMakerService.infer( mockUnsupportedModel(), QUERY, false, null, INPUT, false, null, INPUT_TYPE, THIRTY_SECONDS, assertUnsupportedModel() ); } private static Model mockUnsupportedModel() { Model model = mock(); ModelConfigurations modelConfigurations = mock(); when(modelConfigurations.getService()).thenReturn("mockService"); when(modelConfigurations.getInferenceEntityId()).thenReturn("mockInferenceId"); when(model.getConfigurations()).thenReturn(modelConfigurations); return model; } private static <T> ActionListener<T> assertUnsupportedModel() { return assertNoSuccessListener(e -> { assertThat(e, isA(ElasticsearchStatusException.class)); assertThat( e.getMessage(), equalTo( "The internal model was invalid, please delete the service [mockService] " + "with id [mockInferenceId] and add it again." ) ); assertThat(((ElasticsearchStatusException) e).status(), equalTo(RestStatus.INTERNAL_SERVER_ERROR)); }); } public void testInfer() { var model = mockModel(); SageMakerSchema schema = mock(); when(schemas.schemaFor(model)).thenReturn(schema); mockInvoke(); sageMakerService.infer( model, QUERY, null, null, INPUT, false, null, INPUT_TYPE, THIRTY_SECONDS, assertNoFailureListener(ignored -> { verify(schemas, only()).schemaFor(eq(model)); verify(schema, times(1)).request(eq(model), assertRequest()); verify(schema, times(1)).response(eq(model), any(), any()); }) ); verify(client, only()).invoke(any(), any(), any(), any()); verifyNoMoreInteractions(client, schemas, schema); } @SuppressWarnings("unchecked") public void test_nullTimeoutUsesClusterSetting() throws InterruptedException { var model = mockModel(); when(schemas.schemaFor(model)).thenReturn(mock()); var configuredTimeout = TimeValue.timeValueSeconds(15); var clusterService = mockClusterService( Settings.builder().put(InferencePlugin.INFERENCE_QUERY_TIMEOUT.getKey(), configuredTimeout).build() ); var service = new SageMakerService(modelBuilder, client, schemas, threadPool, Map::of, clusterService); var capturedTimeout = new AtomicReference<TimeValue>(); doAnswer(ans -> { capturedTimeout.set(ans.getArgument(2)); ((ActionListener<InvokeEndpointResponse>) ans.getArgument(3)).onResponse(null); return null; }).when(client).invoke(any(), any(), any(), any()); var latch = new CountDownLatch(1); var latchedListener = new LatchedActionListener<>(ActionListener.<InferenceServiceResults>noop(), latch); service.infer(model, QUERY, null, null, INPUT, false, null, InputType.SEARCH, null, latchedListener); assertTrue(latch.await(30, TimeUnit.SECONDS)); assertEquals(configuredTimeout, capturedTimeout.get()); } @SuppressWarnings("unchecked") public void test_providedTimeoutPropagateProperly() throws InterruptedException { var model = mockModel(); when(schemas.schemaFor(model)).thenReturn(mock()); var providedTimeout = TimeValue.timeValueSeconds(45); var clusterService = mockClusterService( Settings.builder().put(InferencePlugin.INFERENCE_QUERY_TIMEOUT.getKey(), TimeValue.timeValueSeconds(15)).build() ); var service = new SageMakerService(modelBuilder, client, schemas, threadPool, Map::of, clusterService); var capturedTimeout = new AtomicReference<TimeValue>(); doAnswer(ans -> { capturedTimeout.set(ans.getArgument(2)); ((ActionListener<InvokeEndpointResponse>) ans.getArgument(3)).onResponse(null); return null; }).when(client).invoke(any(), any(), any(), any()); var latch = new CountDownLatch(1); var latchedListener = new LatchedActionListener<>(ActionListener.<InferenceServiceResults>noop(), latch); service.infer(model, QUERY, null, null, INPUT, false, null, InputType.SEARCH, providedTimeout, latchedListener); assertTrue(latch.await(30, TimeUnit.SECONDS)); assertEquals(providedTimeout, capturedTimeout.get()); } private SageMakerModel mockModel() { SageMakerModel model = mock(); when(model.override(null)).thenReturn(model); when(model.awsSecretSettings()).thenReturn( Optional.of(new AwsSecretSettings(new SecureString("test-accessKey"), new SecureString("test-secretKey"))) ); return model; } private void mockInvoke() { doAnswer(ans -> { ActionListener<InvokeEndpointResponse> responseListener = ans.getArgument(3); responseListener.onResponse(InvokeEndpointResponse.builder().build()); return null; // Void }).when(client).invoke(any(), any(), any(), any()); } private static SageMakerInferenceRequest assertRequest() { return assertArg(request -> { assertThat(request.query(), equalTo(QUERY)); assertThat(request.input(), containsInAnyOrder(INPUT.toArray())); assertThat(request.inputType(), equalTo(InputType.UNSPECIFIED)); assertNull(request.returnDocuments()); assertNull(request.topN()); }); } public void testInferStream() { SageMakerModel model = mockModel(); SageMakerStreamSchema schema = mock(); when(schemas.streamSchemaFor(model)).thenReturn(schema); mockInvokeStream(); sageMakerService.infer(model, QUERY, null, null, INPUT, true, null, INPUT_TYPE, THIRTY_SECONDS, assertNoFailureListener(ignored -> { verify(schemas, only()).streamSchemaFor(eq(model)); verify(schema, times(1)).streamRequest(eq(model), assertRequest()); verify(schema, times(1)).streamResponse(eq(model), any()); })); verify(client, only()).invokeStream(any(), any(), any(), any()); verifyNoMoreInteractions(client, schemas, schema); } private void mockInvokeStream() { doAnswer(ans -> { ActionListener<SageMakerClient.SageMakerStream> responseListener = ans.getArgument(3); responseListener.onResponse( new SageMakerClient.SageMakerStream(InvokeEndpointWithResponseStreamResponse.builder().build(), mock()) ); return null; // Void }).when(client).invokeStream(any(), any(), any(), any()); } public void testInferError() { SageMakerModel model = mockModel(); var expectedException = new IllegalArgumentException("hola"); SageMakerSchema schema = mock(); when(schemas.schemaFor(model)).thenReturn(schema); mockInvokeFailure(expectedException); sageMakerService.infer( model, QUERY, null, null, INPUT, false, null, INPUT_TYPE, THIRTY_SECONDS, assertNoSuccessListener(ignored -> { verify(schemas, only()).schemaFor(eq(model)); verify(schema, times(1)).request(eq(model), assertRequest()); verify(schema, times(1)).error(eq(model), assertArg(e -> assertThat(e, equalTo(expectedException)))); }) ); verify(client, only()).invoke(any(), any(), any(), any()); verifyNoMoreInteractions(client, schemas, schema); } private void mockInvokeFailure(Exception e) { doAnswer(ans -> { ActionListener<?> responseListener = ans.getArgument(3); responseListener.onFailure(e); return null; // Void }).when(client).invoke(any(), any(), any(), any()); } public void testInferException() { SageMakerModel model = mockModel(); when(model.getInferenceEntityId()).thenReturn("some id"); SageMakerStreamSchema schema = mock(); when(schemas.streamSchemaFor(model)).thenReturn(schema); doThrow(new IllegalArgumentException("wow, really?")).when(client).invokeStream(any(), any(), any(), any()); sageMakerService.infer(model, QUERY, null, null, INPUT, true, null, INPUT_TYPE, THIRTY_SECONDS, assertNoSuccessListener(e -> { verify(schemas, only()).streamSchemaFor(eq(model)); verify(schema, times(1)).streamRequest(eq(model), assertRequest()); assertThat(e, isA(ElasticsearchStatusException.class)); assertThat(((ElasticsearchStatusException) e).status(), equalTo(RestStatus.INTERNAL_SERVER_ERROR)); assertThat(e.getMessage(), equalTo("Failed to call SageMaker for inference id [some id].")); })); verify(client, only()).invokeStream(any(), any(), any(), any()); verifyNoMoreInteractions(client, schemas, schema); } public void testUnifiedInferWithWrongModel() { sageMakerService.unifiedCompletionInfer( mockUnsupportedModel(), randomUnifiedCompletionRequest(), THIRTY_SECONDS, assertUnsupportedModel() ); } public void testUnifiedInfer() { var model = mockModel(); SageMakerStreamSchema schema = mock(); when(schemas.streamSchemaFor(model)).thenReturn(schema); mockInvokeStream(); sageMakerService.unifiedCompletionInfer( model, randomUnifiedCompletionRequest(), THIRTY_SECONDS, assertNoFailureListener(ignored -> { verify(schemas, only()).streamSchemaFor(eq(model)); verify(schema, times(1)).chatCompletionStreamRequest(eq(model), any()); verify(schema, times(1)).chatCompletionStreamResponse(eq(model), any()); }) ); verify(client, only()).invokeStream(any(), any(), any(), any()); verifyNoMoreInteractions(client, schemas, schema); } public void testUnifiedInferError() { var model = mockModel(); var expectedException = new IllegalArgumentException("hola"); SageMakerStreamSchema schema = mock(); when(schemas.streamSchemaFor(model)).thenReturn(schema); mockInvokeStreamFailure(expectedException); sageMakerService.unifiedCompletionInfer( model, randomUnifiedCompletionRequest(), THIRTY_SECONDS, assertNoSuccessListener(ignored -> { verify(schemas, only()).streamSchemaFor(eq(model)); verify(schema, times(1)).chatCompletionStreamRequest(eq(model), any()); verify(schema, times(1)).chatCompletionError(eq(model), assertArg(e -> assertThat(e, equalTo(expectedException)))); }) ); verify(client, only()).invokeStream(any(), any(), any(), any()); verifyNoMoreInteractions(client, schemas, schema); } private void mockInvokeStreamFailure(Exception e) { doAnswer(ans -> { ActionListener<?> responseListener = ans.getArgument(3); responseListener.onFailure(e); return null; // Void }).when(client).invokeStream(any(), any(), any(), any()); } public void testUnifiedInferException() { SageMakerModel model = mockModel(); when(model.getInferenceEntityId()).thenReturn("some id"); SageMakerStreamSchema schema = mock(); when(schemas.streamSchemaFor(model)).thenReturn(schema); doThrow(new IllegalArgumentException("wow, rude")).when(client).invokeStream(any(), any(), any(), any()); sageMakerService.unifiedCompletionInfer(model, randomUnifiedCompletionRequest(), THIRTY_SECONDS, assertNoSuccessListener(e -> { verify(schemas, only()).streamSchemaFor(eq(model)); verify(schema, times(1)).chatCompletionStreamRequest(eq(model), any()); assertThat(e, isA(ElasticsearchStatusException.class)); assertThat(((ElasticsearchStatusException) e).status(), equalTo(RestStatus.INTERNAL_SERVER_ERROR)); assertThat(e.getMessage(), equalTo("Failed to call SageMaker for inference id [some id].")); })); verify(client, only()).invokeStream(any(), any(), any(), any()); verifyNoMoreInteractions(client, schemas, schema); } public void testChunkedInferWithWrongModel() { sageMakerService.chunkedInfer( mockUnsupportedModel(), QUERY, INPUT.stream().map(ChunkInferenceInput::new).toList(), null, INPUT_TYPE, THIRTY_SECONDS, assertUnsupportedModel() ); } public void testChunkedInfer() throws Exception { var model = mockModelForChunking(); SageMakerSchema schema = mock(); when(schema.response(any(), any(), any())).thenReturn(DenseEmbeddingFloatResultsTests.createRandomResults()); when(schemas.schemaFor(model)).thenReturn(schema); mockInvoke(); var expectedInput = Set.of("first", "second"); sageMakerService.chunkedInfer( model, QUERY, expectedInput.stream().map(ChunkInferenceInput::new).toList(), null, INPUT_TYPE, THIRTY_SECONDS, assertOnce(assertNoFailureListener(chunkedInferences -> { verify(schemas, times(2)).schemaFor(eq(model)); verify(schema, times(2)).request(eq(model), assertChunkRequest(expectedInput)); verify(schema, times(2)).response(eq(model), any(), any()); })) ); verify(client, times(2)).invoke(any(), any(), any(), any()); verifyNoMoreInteractions(client, schemas, schema); } private SageMakerModel mockModelForChunking() { var model = mockModel(); when(model.batchSize()).thenReturn(Optional.of(1)); ModelConfigurations modelConfigurations = mock(); when(modelConfigurations.getChunkingSettings()).thenReturn(new WordBoundaryChunkingSettings(1, 0)); when(model.getConfigurations()).thenReturn(modelConfigurations); return model; } private static SageMakerInferenceRequest assertChunkRequest(Set<String> expectedInput) { return assertArg(request -> { assertThat(request.query(), equalTo(QUERY)); assertThat(request.input(), hasSize(1)); assertThat(request.input().get(0), in(expectedInput)); assertThat(request.inputType(), equalTo(InputType.UNSPECIFIED)); assertNull(request.returnDocuments()); assertNull(request.topN()); assertFalse(request.stream()); }); } public void testChunkedInferError() { var model = mockModelForChunking(); var expectedException = new IllegalArgumentException("hola"); SageMakerSchema schema = mock(); when(schema.error(any(), any())).thenReturn(expectedException); when(schemas.schemaFor(model)).thenReturn(schema); mockInvokeFailure(expectedException); var expectedInput = Set.of("first", "second"); var expectedOutput = Stream.of(expectedException, expectedException).map(ChunkedInferenceError::new).toArray(); sageMakerService.chunkedInfer( model, QUERY, expectedInput.stream().map(ChunkInferenceInput::new).toList(), null, INPUT_TYPE, THIRTY_SECONDS, assertOnce(assertNoFailureListener(chunkedInferences -> { verify(schemas, times(2)).schemaFor(eq(model)); verify(schema, times(2)).request(eq(model), assertChunkRequest(expectedInput)); verify(schema, times(2)).error(eq(model), assertArg(e -> assertThat(e, equalTo(expectedException)))); assertThat(chunkedInferences, containsInAnyOrder(expectedOutput)); })) ); verify(client, times(2)).invoke(any(), any(), any(), any()); verifyNoMoreInteractions(client, schemas, schema); } public void testClose() throws IOException { sageMakerService.close(); verify(client, only()).close(); } @Override public InferenceService createInferenceService() { when(schemas.supportedTaskTypes()).thenReturn(EnumSet.of(TaskType.RERANK, TaskType.TEXT_EMBEDDING, TaskType.COMPLETION)); return sageMakerService; } @Override protected void assertRerankerWindowSize(RerankingInferenceService rerankingInferenceService) { assertThat( rerankingInferenceService.rerankerWindowSize("any model"), is(RerankingInferenceService.CONSERVATIVE_DEFAULT_WINDOW_SIZE) ); } }
SageMakerServiceTests
java
quarkusio__quarkus
test-framework/junit5/src/test/java/io/quarkus/test/junit/util/QuarkusTestProfileAwareClassOrdererTest.java
{ "start": 15125, "end": 15209 }
class ____ { } @QuarkusTestResource(Manager4.class) private static
Test03a
java
spring-projects__spring-boot
module/spring-boot-micrometer-tracing/src/main/java/org/springframework/boot/micrometer/tracing/autoconfigure/LogCorrelationEnvironmentPostProcessor.java
{ "start": 1988, "end": 2703 }
class ____ extends EnumerablePropertySource<Object> { private static final String NAME = "logCorrelation"; private final Environment environment; LogCorrelationPropertySource(Object source, Environment environment) { super(NAME, source); this.environment = environment; } @Override public String[] getPropertyNames() { return new String[] { LoggingSystem.EXPECT_CORRELATION_ID_PROPERTY }; } @Override public @Nullable Object getProperty(String name) { if (name.equals(LoggingSystem.EXPECT_CORRELATION_ID_PROPERTY)) { return this.environment.getProperty("management.tracing.export.enabled", Boolean.class, Boolean.TRUE); } return null; } } }
LogCorrelationPropertySource
java
alibaba__nacos
core/src/test/java/com/alibaba/nacos/core/utils/ReuseHttpServletRequestTest.java
{ "start": 1247, "end": 3755 }
class ____ { private MockHttpServletRequest target; private ReuseHttpServletRequest reuseHttpServletRequest; @BeforeEach void setUp() throws IOException { target = new MockHttpServletRequest(); target.setContentType("application/json"); target.setParameter("name", "test"); target.setParameter("value", "123"); reuseHttpServletRequest = new ReuseHttpServletRequest(target); } @Test void testConstructor() throws IOException { try { new ReuseHttpServletRequest(null); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { assertEquals("Request cannot be null", e.getMessage()); } ReuseHttpServletRequest request = new ReuseHttpServletRequest(target); assertNotNull(request); } @Test void testGetBody() throws Exception { Object body = reuseHttpServletRequest.getBody(); assertNotNull(body); assertEquals("name=test&value=123&", body.toString()); target.setContentType(MediaType.MULTIPART_FORM_DATA); body = reuseHttpServletRequest.getBody(); assertNotNull(body); } @Test void testGetReader() throws IOException { BufferedReader reader = reuseHttpServletRequest.getReader(); assertNotNull(reader); } @Test void testGetParameterMap() { Map<String, String[]> parameterMap = reuseHttpServletRequest.getParameterMap(); assertNotNull(parameterMap); assertEquals(2, parameterMap.size()); assertEquals("test", parameterMap.get("name")[0]); assertEquals("123", parameterMap.get("value")[0]); } @Test void testGetParameter() { String name = reuseHttpServletRequest.getParameter("name"); assertNotNull(name); assertEquals("test", name); } @Test void testGetParameterValues() { String[] values = reuseHttpServletRequest.getParameterValues("value"); assertNotNull(values); assertEquals(1, values.length); assertEquals("123", values[0]); } @Test void testGetInputStream() throws IOException { ServletInputStream inputStream = reuseHttpServletRequest.getInputStream(); assertNotNull(inputStream); int read = inputStream.read(); while (read != -1) { read = inputStream.read(); } } }
ReuseHttpServletRequestTest
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/subscriptions/SubscriptionArbiterTest.java
{ "start": 898, "end": 7770 }
class ____ extends RxJavaTest { @Test public void setSubscriptionMissed() { SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); BooleanSubscription bs1 = new BooleanSubscription(); sa.setSubscription(bs1); BooleanSubscription bs2 = new BooleanSubscription(); sa.setSubscription(bs2); assertTrue(bs1.isCancelled()); assertFalse(bs2.isCancelled()); } @Test public void invalidDeferredRequest() { SubscriptionArbiter sa = new SubscriptionArbiter(true); List<Throwable> errors = TestHelper.trackPluginErrors(); try { sa.request(-99); TestHelper.assertError(errors, 0, IllegalArgumentException.class, "n > 0 required but it was -99"); } finally { RxJavaPlugins.reset(); } } @Test public void unbounded() { SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.request(Long.MAX_VALUE); assertEquals(Long.MAX_VALUE, sa.requested); assertTrue(sa.isUnbounded()); sa.unbounded = false; sa.request(Long.MAX_VALUE); assertEquals(Long.MAX_VALUE, sa.requested); sa.produced(1); assertEquals(Long.MAX_VALUE, sa.requested); sa.unbounded = false; sa.produced(Long.MAX_VALUE); assertEquals(Long.MAX_VALUE, sa.requested); } @Test public void cancelled() { SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.cancelled = true; BooleanSubscription bs1 = new BooleanSubscription(); sa.missedSubscription.set(bs1); sa.getAndIncrement(); sa.drainLoop(); assertTrue(bs1.isCancelled()); } @Test public void drainUnbounded() { SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); sa.requested = Long.MAX_VALUE; sa.drainLoop(); } @Test public void drainMissedRequested() { SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); sa.requested = 0; sa.missedRequested.set(1); sa.drainLoop(); assertEquals(1, sa.requested); } @Test public void drainMissedRequestedProduced() { SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); sa.requested = 0; sa.missedRequested.set(Long.MAX_VALUE); sa.missedProduced.set(1); sa.drainLoop(); assertEquals(Long.MAX_VALUE, sa.requested); } @Test public void drainMissedRequestedMoreProduced() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); sa.requested = 0; sa.missedRequested.set(1); sa.missedProduced.set(2); sa.drainLoop(); assertEquals(0, sa.requested); TestHelper.assertError(errors, 0, IllegalStateException.class, "More produced than requested: -1"); } finally { RxJavaPlugins.reset(); } } @Test public void missedSubscriptionNoPrior() { SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.getAndIncrement(); BooleanSubscription bs1 = new BooleanSubscription(); sa.missedSubscription.set(bs1); sa.drainLoop(); assertSame(bs1, sa.actual); } @Test public void noCancelFastPath() { SubscriptionArbiter sa = new SubscriptionArbiter(false); BooleanSubscription bs1 = new BooleanSubscription(); BooleanSubscription bs2 = new BooleanSubscription(); sa.setSubscription(bs1); sa.setSubscription(bs2); assertFalse(bs1.isCancelled()); assertFalse(bs2.isCancelled()); } @Test public void cancelFastPath() { SubscriptionArbiter sa = new SubscriptionArbiter(true); BooleanSubscription bs1 = new BooleanSubscription(); BooleanSubscription bs2 = new BooleanSubscription(); sa.setSubscription(bs1); sa.setSubscription(bs2); assertTrue(bs1.isCancelled()); assertFalse(bs2.isCancelled()); } @Test public void noCancelSlowPathReplace() { SubscriptionArbiter sa = new SubscriptionArbiter(false); BooleanSubscription bs1 = new BooleanSubscription(); BooleanSubscription bs2 = new BooleanSubscription(); BooleanSubscription bs3 = new BooleanSubscription(); sa.setSubscription(bs1); sa.getAndIncrement(); sa.setSubscription(bs2); sa.setSubscription(bs3); sa.drainLoop(); assertFalse(bs1.isCancelled()); assertFalse(bs2.isCancelled()); assertFalse(bs3.isCancelled()); } @Test public void cancelSlowPathReplace() { SubscriptionArbiter sa = new SubscriptionArbiter(true); BooleanSubscription bs1 = new BooleanSubscription(); BooleanSubscription bs2 = new BooleanSubscription(); BooleanSubscription bs3 = new BooleanSubscription(); sa.setSubscription(bs1); sa.getAndIncrement(); sa.setSubscription(bs2); sa.setSubscription(bs3); sa.drainLoop(); assertTrue(bs1.isCancelled()); assertTrue(bs2.isCancelled()); assertFalse(bs3.isCancelled()); } @Test public void noCancelSlowPath() { SubscriptionArbiter sa = new SubscriptionArbiter(false); BooleanSubscription bs1 = new BooleanSubscription(); BooleanSubscription bs2 = new BooleanSubscription(); sa.setSubscription(bs1); sa.getAndIncrement(); sa.setSubscription(bs2); sa.drainLoop(); assertFalse(bs1.isCancelled()); assertFalse(bs2.isCancelled()); } @Test public void cancelSlowPath() { SubscriptionArbiter sa = new SubscriptionArbiter(true); BooleanSubscription bs1 = new BooleanSubscription(); BooleanSubscription bs2 = new BooleanSubscription(); sa.setSubscription(bs1); sa.getAndIncrement(); sa.setSubscription(bs2); sa.drainLoop(); assertTrue(bs1.isCancelled()); assertFalse(bs2.isCancelled()); } @Test public void moreProducedViolationFastPath() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { SubscriptionArbiter sa = new SubscriptionArbiter(true); sa.produced(2); assertEquals(0, sa.requested); TestHelper.assertError(errors, 0, IllegalStateException.class, "More produced than requested: -2"); } finally { RxJavaPlugins.reset(); } } }
SubscriptionArbiterTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inject/JavaxInjectOnAbstractMethodTest.java
{ "start": 3498, "end": 3573 }
class ____ { abstract void abstractMethod(); } /** Concrete
TestClass2
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Shell.java
{ "start": 1673, "end": 1951 }
class ____ running a Shell command. * * <code>Shell</code> can be used to run shell commands like <code>du</code> or * <code>df</code>. It also offers facilities to gate commands by * time-intervals. */ @InterfaceAudience.Public @InterfaceStability.Evolving public abstract
for
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/test/java/org/elasticsearch/xpack/esql/core/async/AsyncTaskManagementServiceTests.java
{ "start": 4358, "end": 15336 }
class ____ implements AsyncTaskManagementService.AsyncOperation<TestRequest, TestResponse, TestTask> { @Override public TestTask createTask( TestRequest request, long id, String type, String action, TaskId parentTaskId, Map<String, String> headers, Map<String, String> originHeaders, AsyncExecutionId asyncExecutionId ) { return new TestTask( id, type, action, request.getDescription(), parentTaskId, headers, originHeaders, asyncExecutionId, request.keepAlive ); } @Override public void execute(TestRequest request, TestTask task, ActionListener<TestResponse> listener) { if (request.string.equals("die")) { listener.onFailure(new IllegalArgumentException("test exception")); } else { listener.onResponse(new TestResponse("response for [" + request.string + "]", task.getExecutionId().getEncoded())); } } @Override public TestResponse initialResponse(TestTask task) { return new TestResponse(null, task.getExecutionId().getEncoded()); } @Override public TestResponse readResponse(StreamInput inputStream) throws IOException { return new TestResponse(inputStream); } } public String index = "test-index"; @Before public void setup() { clusterService = getInstanceFromNode(ClusterService.class); transportService = getInstanceFromNode(TransportService.class); BigArrays bigArrays = getInstanceFromNode(BigArrays.class); AsyncTaskIndexService<StoredAsyncResponse<TestResponse>> store = new AsyncTaskIndexService<>( index, clusterService, transportService.getThreadPool().getThreadContext(), client(), "test", in -> new StoredAsyncResponse<>(TestResponse::new, in), writableRegistry(), bigArrays ); results = new AsyncResultsService<>( store, false, TestTask.class, (task, listener, timeout) -> addCompletionListener(transportService.getThreadPool(), task, listener, timeout), transportService.getTaskManager(), clusterService ); } /** * Shutdown the executor so we don't leak threads into other test runs. */ @After public void shutdownExec() { executorService.shutdown(); } private AsyncTaskManagementService<TestRequest, TestResponse, TestTask> createManagementService( AsyncTaskManagementService.AsyncOperation<TestRequest, TestResponse, TestTask> operation ) { BigArrays bigArrays = getInstanceFromNode(BigArrays.class); return new AsyncTaskManagementService<>( index, client(), "test_origin", writableRegistry(), transportService.getTaskManager(), "test_action", operation, TestTask.class, clusterService, transportService.getThreadPool(), bigArrays ); } public void testReturnBeforeTimeout() throws Exception { AsyncTaskManagementService<TestRequest, TestResponse, TestTask> service = createManagementService(new TestOperation()); boolean success = randomBoolean(); boolean keepOnCompletion = randomBoolean(); CountDownLatch latch = new CountDownLatch(1); TestRequest request = new TestRequest(success ? randomAlphaOfLength(10) : "die", TimeValue.timeValueDays(1)); service.asyncExecute(request, TimeValue.timeValueMinutes(1), keepOnCompletion, ActionListener.wrap(r -> { assertThat(success, equalTo(true)); assertThat(r.string, equalTo("response for [" + request.string + "]")); assertThat(r.id, notNullValue()); latch.countDown(); }, e -> { assertThat(success, equalTo(false)); assertThat(e.getMessage(), equalTo("test exception")); latch.countDown(); })); assertThat(latch.await(10, TimeUnit.SECONDS), equalTo(true)); } public void testReturnAfterTimeout() throws Exception { CountDownLatch executionLatch = new CountDownLatch(1); AsyncTaskManagementService<TestRequest, TestResponse, TestTask> service = createManagementService(new TestOperation() { @Override public void execute(TestRequest request, TestTask task, ActionListener<TestResponse> listener) { executorService.submit(() -> { try { assertThat(executionLatch.await(10, TimeUnit.SECONDS), equalTo(true)); } catch (InterruptedException ex) { fail("Shouldn't be here"); } super.execute(request, task, listener); }); } }); boolean success = randomBoolean(); boolean keepOnCompletion = randomBoolean(); boolean timeoutOnFirstAttempt = randomBoolean(); boolean waitForCompletion = randomBoolean(); CountDownLatch latch = new CountDownLatch(1); TestRequest request = new TestRequest(success ? randomAlphaOfLength(10) : "die", TimeValue.timeValueDays(1)); AtomicReference<TestResponse> responseHolder = new AtomicReference<>(); service.asyncExecute(request, TimeValue.timeValueMillis(1), keepOnCompletion, ActionTestUtils.assertNoFailureListener(r -> { assertThat(r.string, nullValue()); assertThat(r.id, notNullValue()); assertThat(responseHolder.getAndSet(r), nullValue()); latch.countDown(); })); assertThat(latch.await(20, TimeUnit.SECONDS), equalTo(true)); if (timeoutOnFirstAttempt) { logger.trace("Getting an in-flight response"); // try getting results, but fail with timeout because it is not ready yet StoredAsyncResponse<TestResponse> response = getResponse(responseHolder.get().id, TimeValue.timeValueMillis(2)); assertThat(response.getException(), nullValue()); assertThat(response.getResponse(), notNullValue()); assertThat(response.getResponse().id, equalTo(responseHolder.get().id)); assertThat(response.getResponse().string, nullValue()); } if (waitForCompletion) { // now we are waiting for the task to finish logger.trace("Waiting for response to complete"); var getFuture = getResponse(responseHolder.get().id, TimeValue.timeValueSeconds(5), TimeValue.MINUS_ONE); executionLatch.countDown(); var response = safeGet(getFuture); if (success) { assertThat(response.getException(), nullValue()); assertThat(response.getResponse(), notNullValue()); assertThat(response.getResponse().id, equalTo(responseHolder.get().id)); assertThat(response.getResponse().string, equalTo("response for [" + request.string + "]")); } else { assertThat(response.getException(), notNullValue()); assertThat(response.getResponse(), nullValue()); assertThat(response.getException().getMessage(), equalTo("test exception")); } } else { executionLatch.countDown(); } // finally wait until the task disappears and get the response from the index logger.trace("Wait for task to disappear "); assertBusy(() -> { Task task = transportService.getTaskManager().getTask(AsyncExecutionId.decode(responseHolder.get().id).getTaskId().getId()); assertThat(task, nullValue()); }); logger.trace("Getting the final response from the index"); StoredAsyncResponse<TestResponse> response = getResponse(responseHolder.get().id, TimeValue.ZERO); if (success) { assertThat(response.getException(), nullValue()); assertThat(response.getResponse(), notNullValue()); assertThat(response.getResponse().string, equalTo("response for [" + request.string + "]")); } else { assertThat(response.getException(), notNullValue()); assertThat(response.getResponse(), nullValue()); assertThat(response.getException().getMessage(), equalTo("test exception")); } } public void testUpdateKeepAliveToTask() throws Exception { long now = System.currentTimeMillis(); CountDownLatch executionLatch = new CountDownLatch(1); AsyncTaskManagementService<TestRequest, TestResponse, TestTask> service = createManagementService(new TestOperation() { @Override public void execute(TestRequest request, TestTask task, ActionListener<TestResponse> listener) { executorService.submit(() -> { try { assertThat(executionLatch.await(10, TimeUnit.SECONDS), equalTo(true)); } catch (InterruptedException ex) { throw new AssertionError(ex); } super.execute(request, task, listener); }); } }); TestRequest request = new TestRequest(randomAlphaOfLength(10), TimeValue.timeValueHours(1)); PlainActionFuture<TestResponse> submitResp = new PlainActionFuture<>(); try { service.asyncExecute(request, TimeValue.timeValueMillis(1), true, submitResp); String id = submitResp.get().id; assertThat(id, notNullValue()); TimeValue keepAlive = TimeValue.timeValueDays(between(1, 10)); var resp1 = safeGet(getResponse(id, TimeValue.ZERO, keepAlive)); assertThat(resp1.getExpirationTime(), greaterThanOrEqualTo(now + keepAlive.millis())); } finally { executionLatch.countDown(); } } private StoredAsyncResponse<TestResponse> getResponse(String id, TimeValue timeout) throws InterruptedException { return safeGet(getResponse(id, timeout, TimeValue.MINUS_ONE)); } private PlainActionFuture<StoredAsyncResponse<TestResponse>> getResponse(String id, TimeValue timeout, TimeValue keepAlive) { PlainActionFuture<StoredAsyncResponse<TestResponse>> future = new PlainActionFuture<>(); GetAsyncResultRequest getResultsRequest = new GetAsyncResultRequest(id).setWaitForCompletionTimeout(timeout); getResultsRequest.setKeepAlive(keepAlive); results.retrieveResult(getResultsRequest, future); return future; } }
TestOperation
java
apache__hadoop
hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSyncReverseBase.java
{ "start": 2298, "end": 28649 }
class ____ { private MiniDFSCluster cluster; private final Configuration conf = new HdfsConfiguration(); private DistributedFileSystem dfs; private DistCpOptions.Builder optionsBuilder; private DistCpContext distCpContext; private Path source; private boolean isSrcNotSameAsTgt = true; private final Path target = new Path("/target"); private final long blockSize = 1024; private final short dataNum = 1; abstract void initSourcePath(); private static List<String> lsr(final String prefix, final FsShell shell, Path rootDir) throws Exception { return lsr(prefix, shell, rootDir.toString(), null); } private List<String> lsrSource(final String prefix, final FsShell shell, Path rootDir) throws Exception { final Path spath = isSrcNotSameAsTgt? rootDir : new Path(rootDir.toString(), HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s1"); return lsr(prefix, shell, spath.toString(), null); } private static List<String> lsr(final String prefix, final FsShell shell, String rootDir, String glob) throws Exception { final String dir = glob == null ? rootDir : glob; System.out.println(prefix + " lsr root=" + rootDir); final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(bytes); final PrintStream oldOut = System.out; final PrintStream oldErr = System.err; System.setOut(out); System.setErr(out); final String results; try { assertEquals(0, shell.run(new String[] {"-lsr", dir })); results = bytes.toString(); } finally { IOUtils.closeStream(out); System.setOut(oldOut); System.setErr(oldErr); } System.out.println("lsr results:\n" + results); String dirname = rootDir; if (rootDir.lastIndexOf(Path.SEPARATOR) != -1) { dirname = rootDir.substring(rootDir.lastIndexOf(Path.SEPARATOR)); } final List<String> paths = new ArrayList<String>(); for (StringTokenizer t = new StringTokenizer(results, "\n"); t .hasMoreTokens();) { final String s = t.nextToken(); final int i = s.indexOf(dirname); if (i >= 0) { paths.add(s.substring(i + dirname.length())); } } Collections.sort(paths); System.out .println("lsr paths = " + paths.toString().replace(", ", ",\n ")); return paths; } public void setSource(final Path src) { this.source = src; } public void setSrcNotSameAsTgt(final boolean srcNotSameAsTgt) { isSrcNotSameAsTgt = srcNotSameAsTgt; } @BeforeEach public void setUp() throws Exception { initSourcePath(); cluster = new MiniDFSCluster.Builder(conf).numDataNodes(dataNum).build(); cluster.waitActive(); dfs = cluster.getFileSystem(); if (isSrcNotSameAsTgt) { dfs.mkdirs(source); } dfs.mkdirs(target); optionsBuilder = new DistCpOptions.Builder(Arrays.asList(source), target) .withSyncFolder(true) .withUseRdiff("s2", "s1"); final DistCpOptions options = optionsBuilder.build(); options.appendToConf(conf); distCpContext = new DistCpContext(options); conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, target.toString()); conf.set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, target.toString()); } @AfterEach public void tearDown() throws Exception { IOUtils.cleanupWithLogger(null, dfs); if (cluster != null) { cluster.shutdown(); } } /** * Test the sync returns false in the following scenarios: * 1. the source/target dir are not snapshottable dir * 2. the source/target does not have the given snapshots * 3. changes have been made in target */ @Test public void testFallback() throws Exception { // the source/target dir are not snapshottable dir assertFalse(sync()); // make sure the source path has been updated to the snapshot path final Path spath = new Path(source, HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s1"); assertEquals(spath, distCpContext.getSourcePaths().get(0)); // reset source path in options optionsBuilder.withSourcePaths(Arrays.asList(source)); // the source/target does not have the given snapshots dfs.allowSnapshot(source); dfs.allowSnapshot(target); assertFalse(sync()); assertEquals(spath, distCpContext.getSourcePaths().get(0)); // reset source path in options optionsBuilder.withSourcePaths(Arrays.asList(source)); this.enableAndCreateFirstSnapshot(); dfs.createSnapshot(target, "s2"); assertTrue(sync()); // reset source paths in options optionsBuilder.withSourcePaths(Arrays.asList(source)); // changes have been made in target final Path subTarget = new Path(target, "sub"); dfs.mkdirs(subTarget); assertFalse(sync()); // make sure the source path has been updated to the snapshot path assertEquals(spath, distCpContext.getSourcePaths().get(0)); // reset source paths in options optionsBuilder.withSourcePaths(Arrays.asList(source)); dfs.delete(subTarget, true); assertTrue(sync()); } private void syncAndVerify() throws Exception { final FsShell shell = new FsShell(conf); lsrSource("Before sync source: ", shell, source); lsr("Before sync target: ", shell, target); assertTrue(sync()); lsrSource("After sync source: ", shell, source); lsr("After sync target: ", shell, target); verifyCopy(dfs.getFileStatus(source), dfs.getFileStatus(target), false); } private boolean sync() throws Exception { distCpContext = new DistCpContext(optionsBuilder.build()); final DistCpSync distCpSync = new DistCpSync(distCpContext, conf); return distCpSync.sync(); } private void enableAndCreateFirstSnapshot() throws Exception { if (isSrcNotSameAsTgt) { dfs.allowSnapshot(source); dfs.createSnapshot(source, "s1"); } dfs.allowSnapshot(target); dfs.createSnapshot(target, "s1"); } private void createSecondSnapshotAtTarget() throws Exception { dfs.createSnapshot(target, "s2"); } private void createMiddleSnapshotAtTarget() throws Exception { dfs.createSnapshot(target, "s1.5"); } /** * create some files and directories under the given directory. * the final subtree looks like this: * dir/ * foo/ bar/ * d1/ f1 d2/ f2 * f3 f4 */ private void initData(Path dir) throws Exception { final Path foo = new Path(dir, "foo"); final Path bar = new Path(dir, "bar"); final Path d1 = new Path(foo, "d1"); final Path f1 = new Path(foo, "f1"); final Path d2 = new Path(bar, "d2"); final Path f2 = new Path(bar, "f2"); final Path f3 = new Path(d1, "f3"); final Path f4 = new Path(d2, "f4"); DFSTestUtil.createFile(dfs, f1, blockSize, dataNum, 0); DFSTestUtil.createFile(dfs, f2, blockSize, dataNum, 0); DFSTestUtil.createFile(dfs, f3, blockSize, dataNum, 0); DFSTestUtil.createFile(dfs, f4, blockSize, dataNum, 0); } /** * make some changes under the given directory (created in the above way). * 1. rename dir/foo/d1 to dir/bar/d1 * 2. delete dir/bar/d1/f3 * 3. rename dir/foo to /dir/bar/d1/foo * 4. delete dir/bar/d1/foo/f1 * 5. create file dir/bar/d1/foo/f1 whose size is 2*BLOCK_SIZE * 6. append one BLOCK to file dir/bar/f2 * 7. rename dir/bar to dir/foo * * Thus after all these ops the subtree looks like this: * dir/ * foo/ * d1/ f2(A) d2/ * foo/ f4 * f1(new) */ private int changeData(Path dir) throws Exception { final Path foo = new Path(dir, "foo"); final Path bar = new Path(dir, "bar"); final Path d1 = new Path(foo, "d1"); final Path f2 = new Path(bar, "f2"); final Path bar_d1 = new Path(bar, "d1"); int numDeletedModified = 0; dfs.rename(d1, bar_d1); numDeletedModified += 1; // modify ./foo numDeletedModified += 1; // modify ./bar final Path f3 = new Path(bar_d1, "f3"); dfs.delete(f3, true); numDeletedModified += 1; // delete f3 final Path newfoo = new Path(bar_d1, "foo"); dfs.rename(foo, newfoo); numDeletedModified += 1; // modify ./foo/d1 final Path f1 = new Path(newfoo, "f1"); dfs.delete(f1, true); numDeletedModified += 1; // delete ./foo/f1 DFSTestUtil.createFile(dfs, f1, 2 * blockSize, dataNum, 0); DFSTestUtil.appendFile(dfs, f2, (int) blockSize); numDeletedModified += 1; // modify ./bar/f2 dfs.rename(bar, new Path(dir, "foo")); return numDeletedModified; } /** * Test the basic functionality. */ @Test public void testSync() throws Exception { if (isSrcNotSameAsTgt) { initData(source); } initData(target); enableAndCreateFirstSnapshot(); final FsShell shell = new FsShell(conf); lsrSource("Before source: ", shell, source); lsr("Before target: ", shell, target); // make changes under target int numDeletedModified = changeData(target); createSecondSnapshotAtTarget(); SnapshotDiffReport report = dfs.getSnapshotDiffReport(target, "s2", "s1"); System.out.println(report); final DistCpSync distCpSync = new DistCpSync(distCpContext, conf); lsr("Before sync target: ", shell, target); // do the sync assertTrue(distCpSync.sync()); lsr("After sync target: ", shell, target); // make sure the source path has been updated to the snapshot path final Path spath = new Path(source, HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s1"); assertEquals(spath, distCpContext.getSourcePaths().get(0)); // build copy listing final Path listingPath = new Path("/tmp/META/fileList.seq"); CopyListing listing = new SimpleCopyListing(conf, new Credentials(), distCpSync); listing.buildListing(listingPath, distCpContext); Map<Text, CopyListingFileStatus> copyListing = getListing(listingPath); CopyMapper copyMapper = new CopyMapper(); StubContext stubContext = new StubContext(conf, null, 0); Mapper<Text, CopyListingFileStatus, Text, Text>.Context context = stubContext.getContext(); // Enable append context.getConfiguration().setBoolean( DistCpOptionSwitch.APPEND.getConfigLabel(), true); copyMapper.setup(context); for (Map.Entry<Text, CopyListingFileStatus> entry : copyListing.entrySet()) { copyMapper.map(entry.getKey(), entry.getValue(), context); } lsrSource("After mapper source: ", shell, source); lsr("After mapper target: ", shell, target); // verify that we only list modified and created files/directories assertEquals(numDeletedModified, copyListing.size()); // verify that we only copied new appended data of f2 and the new file f1 assertEquals(blockSize * 3, stubContext.getReporter() .getCounter(CopyMapper.Counter.BYTESCOPIED).getValue()); // verify the source and target now has the same structure verifyCopy(dfs.getFileStatus(spath), dfs.getFileStatus(target), false); } private Map<Text, CopyListingFileStatus> getListing(Path listingPath) throws Exception { SequenceFile.Reader reader = null; Map<Text, CopyListingFileStatus> values = new HashMap<>(); try { reader = new SequenceFile.Reader(conf, SequenceFile.Reader.file(listingPath)); Text key = new Text(); CopyListingFileStatus value = new CopyListingFileStatus(); while (reader.next(key, value)) { values.put(key, value); key = new Text(); value = new CopyListingFileStatus(); } } finally { if (reader != null) { reader.close(); } } return values; } private void verifyCopy(FileStatus s, FileStatus t, boolean compareName) throws Exception { assertEquals(s.isDirectory(), t.isDirectory()); if (compareName) { assertEquals(s.getPath().getName(), t.getPath().getName()); } if (!s.isDirectory()) { // verify the file content is the same byte[] sbytes = DFSTestUtil.readFileBuffer(dfs, s.getPath()); byte[] tbytes = DFSTestUtil.readFileBuffer(dfs, t.getPath()); assertArrayEquals(sbytes, tbytes); } else { FileStatus[] slist = dfs.listStatus(s.getPath()); FileStatus[] tlist = dfs.listStatus(t.getPath()); assertEquals(slist.length, tlist.length); for (int i = 0; i < slist.length; i++) { verifyCopy(slist[i], tlist[i], true); } } } /** * Test the case that "current" is snapshotted as "s2". * @throws Exception */ @Test public void testSyncWithCurrent() throws Exception { optionsBuilder.withUseRdiff(".", "s1"); if (isSrcNotSameAsTgt) { initData(source); } initData(target); enableAndCreateFirstSnapshot(); // make changes under target changeData(target); // do the sync assertTrue(sync()); final Path spath = new Path(source, HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s1"); // make sure the source path is still unchanged assertEquals(spath, distCpContext.getSourcePaths().get(0)); } private void initData2(Path dir) throws Exception { final Path test = new Path(dir, "test"); final Path foo = new Path(dir, "foo"); final Path bar = new Path(dir, "bar"); final Path f1 = new Path(test, "f1"); final Path f2 = new Path(foo, "f2"); final Path f3 = new Path(bar, "f3"); DFSTestUtil.createFile(dfs, f1, blockSize, dataNum, 0L); DFSTestUtil.createFile(dfs, f2, blockSize, dataNum, 1L); DFSTestUtil.createFile(dfs, f3, blockSize, dataNum, 2L); } private void changeData2(Path dir) throws Exception { final Path tmpFoo = new Path(dir, "tmpFoo"); final Path test = new Path(dir, "test"); final Path foo = new Path(dir, "foo"); final Path bar = new Path(dir, "bar"); dfs.rename(test, tmpFoo); dfs.rename(foo, test); dfs.rename(bar, foo); dfs.rename(tmpFoo, bar); } @Test public void testSync2() throws Exception { if (isSrcNotSameAsTgt) { initData2(source); } initData2(target); enableAndCreateFirstSnapshot(); // make changes under target changeData2(target); createSecondSnapshotAtTarget(); SnapshotDiffReport report = dfs.getSnapshotDiffReport(target, "s2", "s1"); System.out.println(report); syncAndVerify(); } private void initData3(Path dir) throws Exception { final Path test = new Path(dir, "test"); final Path foo = new Path(dir, "foo"); final Path bar = new Path(dir, "bar"); final Path f1 = new Path(test, "file"); final Path f2 = new Path(foo, "file"); final Path f3 = new Path(bar, "file"); DFSTestUtil.createFile(dfs, f1, blockSize, dataNum, 0L); DFSTestUtil.createFile(dfs, f2, blockSize * 2, dataNum, 1L); DFSTestUtil.createFile(dfs, f3, blockSize * 3, dataNum, 2L); } private void changeData3(Path dir) throws Exception { final Path test = new Path(dir, "test"); final Path foo = new Path(dir, "foo"); final Path bar = new Path(dir, "bar"); final Path f1 = new Path(test, "file"); final Path f2 = new Path(foo, "file"); final Path f3 = new Path(bar, "file"); final Path newf1 = new Path(test, "newfile"); final Path newf2 = new Path(foo, "newfile"); final Path newf3 = new Path(bar, "newfile"); dfs.rename(f1, newf1); dfs.rename(f2, newf2); dfs.rename(f3, newf3); } /** * Test a case where there are multiple source files with the same name. */ @Test public void testSync3() throws Exception { if (isSrcNotSameAsTgt) { initData3(source); } initData3(target); enableAndCreateFirstSnapshot(); // make changes under target changeData3(target); createSecondSnapshotAtTarget(); SnapshotDiffReport report = dfs.getSnapshotDiffReport(target, "s2", "s1"); System.out.println(report); syncAndVerify(); } private void initData4(Path dir) throws Exception { final Path d1 = new Path(dir, "d1"); final Path d2 = new Path(d1, "d2"); final Path f1 = new Path(d2, "f1"); DFSTestUtil.createFile(dfs, f1, blockSize, dataNum, 0L); } private int changeData4(Path dir) throws Exception { final Path d1 = new Path(dir, "d1"); final Path d11 = new Path(dir, "d11"); final Path d2 = new Path(d1, "d2"); final Path d21 = new Path(d1, "d21"); final Path f1 = new Path(d2, "f1"); int numDeletedAndModified = 0; dfs.delete(f1, false); numDeletedAndModified += 1; dfs.rename(d2, d21); numDeletedAndModified += 1; dfs.rename(d1, d11); numDeletedAndModified += 1; return numDeletedAndModified; } /** * Test a case where multiple level dirs are renamed. */ @Test public void testSync4() throws Exception { if (isSrcNotSameAsTgt) { initData4(source); } initData4(target); enableAndCreateFirstSnapshot(); final FsShell shell = new FsShell(conf); lsr("Before change target: ", shell, target); // make changes under target int numDeletedAndModified = changeData4(target); createSecondSnapshotAtTarget(); SnapshotDiffReport report = dfs.getSnapshotDiffReport(target, "s2", "s1"); System.out.println(report); testAndVerify(numDeletedAndModified); } private void initData5(Path dir) throws Exception { final Path d1 = new Path(dir, "d1"); final Path d2 = new Path(dir, "d2"); final Path f1 = new Path(d1, "f1"); final Path f2 = new Path(d2, "f2"); DFSTestUtil.createFile(dfs, f1, blockSize, dataNum, 0L); DFSTestUtil.createFile(dfs, f2, blockSize, dataNum, 0L); } private int changeData5(Path dir) throws Exception { final Path d1 = new Path(dir, "d1"); final Path d2 = new Path(dir, "d2"); final Path f1 = new Path(d1, "f1"); final Path tmp = new Path(dir, "tmp"); int numDeletedAndModified = 0; dfs.delete(f1, false); numDeletedAndModified += 1; dfs.rename(d1, tmp); numDeletedAndModified += 1; dfs.rename(d2, d1); numDeletedAndModified += 1; final Path f2 = new Path(d1, "f2"); dfs.delete(f2, false); numDeletedAndModified += 1; return numDeletedAndModified; } /** * Test a case with different delete and rename sequences. */ @Test public void testSync5() throws Exception { if (isSrcNotSameAsTgt) { initData5(source); } initData5(target); enableAndCreateFirstSnapshot(); // make changes under target int numDeletedAndModified = changeData5(target); createSecondSnapshotAtTarget(); SnapshotDiffReport report = dfs.getSnapshotDiffReport(target, "s2", "s1"); System.out.println(report); testAndVerify(numDeletedAndModified); } private void testAndVerify(int numDeletedAndModified) throws Exception{ SnapshotDiffReport report = dfs.getSnapshotDiffReport(target, "s2", "s1"); System.out.println(report); final FsShell shell = new FsShell(conf); lsrSource("Before sync source: ", shell, source); lsr("Before sync target: ", shell, target); DistCpSync distCpSync = new DistCpSync(distCpContext, conf); // do the sync distCpSync.sync(); lsr("After sync target: ", shell, target); // make sure the source path has been updated to the snapshot path final Path spath = new Path(source, HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s1"); assertEquals(spath, distCpContext.getSourcePaths().get(0)); // build copy listing final Path listingPath = new Path("/tmp/META/fileList.seq"); CopyListing listing = new SimpleCopyListing(conf, new Credentials(), distCpSync); listing.buildListing(listingPath, distCpContext); Map<Text, CopyListingFileStatus> copyListing = getListing(listingPath); CopyMapper copyMapper = new CopyMapper(); StubContext stubContext = new StubContext(conf, null, 0); Mapper<Text, CopyListingFileStatus, Text, Text>.Context context = stubContext.getContext(); // Enable append context.getConfiguration().setBoolean( DistCpOptionSwitch.APPEND.getConfigLabel(), true); copyMapper.setup(context); for (Map.Entry<Text, CopyListingFileStatus> entry : copyListing.entrySet()) { copyMapper.map(entry.getKey(), entry.getValue(), context); } // verify that we only list modified and created files/directories assertEquals(numDeletedAndModified, copyListing.size()); lsr("After Copy target: ", shell, target); // verify the source and target now has the same structure verifyCopy(dfs.getFileStatus(spath), dfs.getFileStatus(target), false); } private void initData6(Path dir) throws Exception { final Path foo = new Path(dir, "foo"); final Path bar = new Path(dir, "bar"); final Path foo_f1 = new Path(foo, "f1"); final Path bar_f1 = new Path(bar, "f1"); DFSTestUtil.createFile(dfs, foo_f1, blockSize, dataNum, 0L); DFSTestUtil.createFile(dfs, bar_f1, blockSize, dataNum, 0L); } private int changeData6(Path dir) throws Exception { final Path foo = new Path(dir, "foo"); final Path bar = new Path(dir, "bar"); final Path foo2 = new Path(dir, "foo2"); final Path foo_f1 = new Path(foo, "f1"); int numDeletedModified = 0; dfs.rename(foo, foo2); dfs.rename(bar, foo); dfs.rename(foo2, bar); DFSTestUtil.appendFile(dfs, foo_f1, (int) blockSize); numDeletedModified += 1; // modify ./bar/f1 return numDeletedModified; } /** * Test a case where there is a cycle in renaming dirs. */ @Test public void testSync6() throws Exception { if (isSrcNotSameAsTgt) { initData6(source); } initData6(target); enableAndCreateFirstSnapshot(); int numDeletedModified = changeData6(target); createSecondSnapshotAtTarget(); testAndVerify(numDeletedModified); } private void initData7(Path dir) throws Exception { final Path foo = new Path(dir, "foo"); final Path bar = new Path(dir, "bar"); final Path foo_f1 = new Path(foo, "f1"); final Path bar_f1 = new Path(bar, "f1"); DFSTestUtil.createFile(dfs, foo_f1, blockSize, dataNum, 0L); DFSTestUtil.createFile(dfs, bar_f1, blockSize, dataNum, 0L); } private int changeData7(Path dir) throws Exception { final Path foo = new Path(dir, "foo"); final Path foo2 = new Path(dir, "foo2"); final Path foo_f1 = new Path(foo, "f1"); final Path foo2_f2 = new Path(foo2, "f2"); final Path foo_d1 = new Path(foo, "d1"); final Path foo_d1_f3 = new Path(foo_d1, "f3"); int numDeletedAndModified = 0; dfs.rename(foo, foo2); DFSTestUtil.createFile(dfs, foo_f1, blockSize, dataNum, 0L); DFSTestUtil.appendFile(dfs, foo_f1, (int) blockSize); dfs.rename(foo_f1, foo2_f2); /* * Difference between snapshot s1 and current directory under directory /target: M . + ./foo R ./foo -> ./foo2 M ./foo + ./foo/f2 */ numDeletedAndModified += 1; // "M ./foo" DFSTestUtil.createFile(dfs, foo_d1_f3, blockSize, dataNum, 0L); return numDeletedAndModified; } /** * Test a case where rename a dir, then create a new dir with the same name * and sub dir. */ @Test public void testSync7() throws Exception { if (isSrcNotSameAsTgt) { initData7(source); } initData7(target); enableAndCreateFirstSnapshot(); int numDeletedAndModified = changeData7(target); createSecondSnapshotAtTarget(); testAndVerify(numDeletedAndModified); } private void initData8(Path dir) throws Exception { final Path foo = new Path(dir, "foo"); final Path bar = new Path(dir, "bar"); final Path d1 = new Path(dir, "d1"); final Path foo_f1 = new Path(foo, "f1"); final Path bar_f1 = new Path(bar, "f1"); final Path d1_f1 = new Path(d1, "f1"); DFSTestUtil.createFile(dfs, foo_f1, blockSize, dataNum, 0L); DFSTestUtil.createFile(dfs, bar_f1, blockSize, dataNum, 0L); DFSTestUtil.createFile(dfs, d1_f1, blockSize, dataNum, 0L); } private int changeData8(Path dir, boolean createMiddleSnapshot) throws Exception { final Path foo = new Path(dir, "foo"); final Path createdDir = new Path(dir, "c"); final Path d1 = new Path(dir, "d1"); final Path d1_f1 = new Path(d1, "f1"); final Path createdDir_f1 = new Path(createdDir, "f1"); final Path foo_f3 = new Path(foo, "f3"); final Path new_foo = new Path(createdDir, "foo"); final Path foo_f4 = new Path(foo, "f4"); final Path foo_d1 = new Path(foo, "d1"); final Path bar = new Path(dir, "bar"); final Path bar1 = new Path(dir, "bar1"); int numDeletedAndModified = 0; DFSTestUtil.createFile(dfs, foo_f3, blockSize, dataNum, 0L); DFSTestUtil.createFile(dfs, createdDir_f1, blockSize, dataNum, 0L); dfs.rename(createdDir_f1, foo_f4); dfs.rename(d1_f1, createdDir_f1); // rename ./d1/f1 -> ./c/f1 numDeletedAndModified += 1; // modify ./c/foo/d1 if (createMiddleSnapshot) { this.createMiddleSnapshotAtTarget(); } dfs.rename(d1, foo_d1); numDeletedAndModified += 1; // modify ./c/foo dfs.rename(foo, new_foo); dfs.rename(bar, bar1); return numDeletedAndModified; } /** * Test a case where create a dir, then mv a existed dir into it. */ @Test public void testSync8() throws Exception { if (isSrcNotSameAsTgt) { initData8(source); } initData8(target); enableAndCreateFirstSnapshot(); int numDeletedModified = changeData8(target, false); createSecondSnapshotAtTarget(); testAndVerify(numDeletedModified); } /** * Test a case where create a dir, then mv a existed dir into it. * The difference between this one and testSync8 is, this one * also creates a snapshot s1.5 in between s1 and s2. */ @Test public void testSync9() throws Exception { if (isSrcNotSameAsTgt) { initData8(source); } initData8(target); enableAndCreateFirstSnapshot(); int numDeletedModified = changeData8(target, true); createSecondSnapshotAtTarget(); testAndVerify(numDeletedModified); } }
TestDistCpSyncReverseBase
java
apache__spark
common/network-common/src/main/java/org/apache/spark/network/protocol/MessageEncoder.java
{ "start": 1421, "end": 3949 }
class ____ extends MessageToMessageEncoder<Message> { private static final SparkLogger logger = SparkLoggerFactory.getLogger(MessageEncoder.class); public static final MessageEncoder INSTANCE = new MessageEncoder(); private MessageEncoder() {} /*** * Encodes a Message by invoking its encode() method. For non-data messages, we will add one * ByteBuf to 'out' containing the total frame length, the message type, and the message itself. * In the case of a ChunkFetchSuccess, we will also add the ManagedBuffer corresponding to the * data to 'out', in order to enable zero-copy transfer. */ @Override public void encode(ChannelHandlerContext ctx, Message in, List<Object> out) throws Exception { Object body = null; long bodyLength = 0; boolean isBodyInFrame = false; // If the message has a body, take it out to enable zero-copy transfer for the payload. if (in.body() != null) { try { bodyLength = in.body().size(); body = in.body().convertToNetty(); isBodyInFrame = in.isBodyInFrame(); } catch (Exception e) { in.body().release(); if (in instanceof AbstractResponseMessage resp) { // Re-encode this message as a failure response. String error = e.getMessage() != null ? e.getMessage() : "null"; logger.error("Error processing {} for client {}", e, MDC.of(LogKeys.MESSAGE, in), MDC.of(LogKeys.HOST_PORT, ctx.channel().remoteAddress())); encode(ctx, resp.createFailureResponse(error), out); } else { throw e; } return; } } Message.Type msgType = in.type(); // All messages have the frame length, message type, and message itself. The frame length // may optionally include the length of the body data, depending on what message is being // sent. int headerLength = 8 + msgType.encodedLength() + in.encodedLength(); long frameLength = headerLength + (isBodyInFrame ? bodyLength : 0); ByteBuf header = ctx.alloc().buffer(headerLength); header.writeLong(frameLength); msgType.encode(header); in.encode(header); assert header.writableBytes() == 0; if (body != null) { // We transfer ownership of the reference on in.body() to MessageWithHeader. // This reference will be freed when MessageWithHeader.deallocate() is called. out.add(new MessageWithHeader(in.body(), header, body, bodyLength)); } else { out.add(header); } } }
MessageEncoder
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/testutils/statemigration/TestType.java
{ "start": 7653, "end": 8483 }
class ____ extends TestTypeSerializerBase { private static final long serialVersionUID = -2959080770523247215L; @Override public void serialize(TestType record, DataOutputView target) throws IOException { throw new UnsupportedOperationException( "This is an incompatible serializer; shouldn't be used."); } @Override public TestType deserialize(DataInputView source) throws IOException { throw new UnsupportedOperationException( "This is an incompatible serializer; shouldn't be used."); } @Override public TypeSerializerSnapshot<TestType> snapshotConfiguration() { return new IncompatibleTestTypeSerializerSnapshot(); } public static
IncompatibleTestTypeSerializer
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/source/ParameterProvidedMethods.java
{ "start": 3103, "end": 3566 }
class ____ { private Map<Parameter, List<SourceMethod>> contextProvidedMethods = new HashMap<>(); private Builder() { } public void addMethodsForParameter(Parameter param, List<SourceMethod> methods) { contextProvidedMethods.put( param, methods ); } public ParameterProvidedMethods build() { return new ParameterProvidedMethods( contextProvidedMethods ); } } }
Builder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/changelog/StateChange.java
{ "start": 1076, "end": 2170 }
class ____ implements Serializable { /* For metadata, see FLINK-23035.*/ public static final int META_KEY_GROUP = -1; private static final long serialVersionUID = 1L; private final int keyGroup; private final byte[] change; StateChange(byte[] change) { this.keyGroup = META_KEY_GROUP; this.change = Preconditions.checkNotNull(change); } StateChange(int keyGroup, byte[] change) { Preconditions.checkArgument(keyGroup >= 0); this.keyGroup = keyGroup; this.change = Preconditions.checkNotNull(change); } public static StateChange ofMetadataChange(byte[] change) { return new StateChange(change); } public static StateChange ofDataChange(int keyGroup, byte[] change) { return new StateChange(keyGroup, change); } @Override public String toString() { return String.format("keyGroup=%d, dataSize=%d", keyGroup, change.length); } public int getKeyGroup() { return keyGroup; } public byte[] getChange() { return change; } }
StateChange
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/topic/LmqTopicConfigManager.java
{ "start": 1047, "end": 2021 }
class ____ extends TopicConfigManager { public LmqTopicConfigManager(BrokerController brokerController) { super(brokerController); } @Override public TopicConfig selectTopicConfig(final String topic) { if (MixAll.isLmq(topic)) { return simpleLmqTopicConfig(topic); } return super.selectTopicConfig(topic); } @Override public void updateTopicConfig(final TopicConfig topicConfig) { if (topicConfig == null || MixAll.isLmq(topicConfig.getTopicName())) { return; } super.updateTopicConfig(topicConfig); } private TopicConfig simpleLmqTopicConfig(String topic) { return new TopicConfig(topic, 1, 1, PermName.PERM_READ | PermName.PERM_WRITE); } @Override public boolean containsTopic(String topic) { if (MixAll.isLmq(topic)) { return true; } return super.containsTopic(topic); } }
LmqTopicConfigManager
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 43178, "end": 44180 }
class ____<T extends Number> {", " public abstract Builder<T> t(T t);", " public abstract NestedAutoValue<T> build();", " }", "", " public static <T extends Number> Builder<T> builder() {", " return AutoValue_NestedAutoValue.builder();", " }", "}"); JavaFileObject expectedOutput = JavaFileObjects.forSourceLines( "foo.bar.AutoValue_Baz", "package foo.bar;", "", "import com.google.common.base.Optional;", "import com.google.common.collect.ImmutableMap;", "import java.util.Arrays;", "import java.util.List;", "import java.util.Map;", sorted( GeneratedImport.importGeneratedAnnotationType(), "import javax.annotation.Nullable;"), "", "@Generated(\"" + AutoValueProcessor.class.getName() + "\")", "final
Builder
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1828/FirstMapper.java
{ "start": 304, "end": 767 }
interface ____ { FirstMapper INSTANCE = Mappers.getMapper( FirstMapper.class ); @Mapping(target = "completeAddress.lineOne", source = "specialAddress.line1") @Mapping(target = "completeAddress.lineTwo", source = "specialAddress.line2") @Mapping(target = "completeAddress.city", source = "generalAddress.city") @Mapping(target = "completeAddress.country", source = "generalAddress.country") Person mapPerson(Employee employee); }
FirstMapper
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/TimelineStoreMapAdapter.java
{ "start": 1050, "end": 1688 }
interface ____<K, V> { /** * @param key * @return map(key) */ V get(K key); /** * Add mapping key->value in the map * @param key * @param value */ void put(K key, V value); /** * Remove mapping with key keyToRemove * @param keyToRemove */ void remove(K keyToRemove); /** * @return the iterator of the value set of the map */ CloseableIterator<V> valueSetIterator(); /** * Return the iterator of the value set of the map, starting from minV if type * V is comparable. * @param minV * @return */ CloseableIterator<V> valueSetIterator(V minV);
TimelineStoreMapAdapter
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/internal/util/collections/StandardStack.java
{ "start": 569, "end": 3072 }
class ____<T> implements Stack<T> { private Object[] elements; private int top = 0; public StandardStack() { } public StandardStack(T initialValue) { push( initialValue ); } /** * @deprecated use the default constructor instead */ @Deprecated(forRemoval = true) public StandardStack(Class<T> type) { } /** * @deprecated use {@link #StandardStack(Object)} instead. */ @Deprecated(forRemoval = true) public StandardStack(Class<T> type, T initial) { push( initial ); } private void init() { elements = new Object[8]; } @Override public void push(T e) { if ( elements == null ) { init(); } if ( top == elements.length ) { grow(); } elements[top++] = e; } @Override public T pop() { if ( isEmpty() ) { throw new NoSuchElementException(); } T e = (T) elements[--top]; elements[top] = null; return e; } @Override public T getCurrent() { if ( isEmpty() ) { return null; } return (T) elements[top - 1]; } @Override public T peek(int offsetFromTop) { if ( isEmpty() ) { return null; } return (T) elements[top - offsetFromTop - 1]; } @Override public T getRoot() { if ( isEmpty() ) { return null; } return (T) elements[0]; } @Override public int depth() { return top; } @Override public boolean isEmpty() { return top == 0; } @Override public void clear() { if ( elements != null ) { Arrays.fill( elements, 0, top, null ); } top = 0; } @Override public void visitRootFirst(Consumer<T> action) { for ( int i = 0; i < top; i++ ) { action.accept( (T) elements[i] ); } } @Override public <X> X findCurrentFirst(Function<T, X> function) { for ( int i = top - 1; i >= 0; i-- ) { final X result = function.apply( (T) elements[i] ); if ( result != null ) { return result; } } return null; } @Override public <X, Y> X findCurrentFirstWithParameter(Y parameter, BiFunction<T, Y, X> biFunction) { for ( int i = top - 1; i >= 0; i-- ) { final X result = biFunction.apply( (T) elements[i], parameter ); if ( result != null ) { return result; } } return null; } private void grow() { final int oldCapacity = elements.length; final int jump = ( oldCapacity < 64 ) ? ( oldCapacity + 2 ) : ( oldCapacity >> 1 ); final Object[] newElements = Arrays.copyOf( elements, oldCapacity + jump ); // Prevents GC nepotism on the old array elements, see HHH-19047 Arrays.fill( elements, null ); elements = newElements; } }
StandardStack
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/AdviceWithInterceptTest.java
{ "start": 1070, "end": 2015 }
class ____ extends ContextTestSupport { @Test public void testAdviceIntercept() throws Exception { getMockEndpoint("mock:advice").expectedMessageCount(1); AdviceWith.adviceWith(context.getRouteDefinition("main"), context, new AdviceWithRouteBuilder() { @Override public void configure() { weaveAddFirst().to("direct:advice"); } }); template.sendBody("direct:main", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { intercept().log("Intercept ${body}"); from("direct:advice").log("Advice ${body}").to("mock:advice"); from("direct:main").routeId("main").log("Main ${body}"); } }; } }
AdviceWithInterceptTest
java
resilience4j__resilience4j
resilience4j-retry/src/main/java/io/github/resilience4j/retry/internal/RetryImpl.java
{ "start": 11503, "end": 15654 }
class ____ implements Retry.AsyncContext<T> { private final AtomicInteger numOfAttempts = new AtomicInteger(0); private final AtomicReference<Throwable> lastException = new AtomicReference<>(); @Override public void onComplete() { totalAttemptsCounter.increment(); int currentNumOfAttempts = numOfAttempts.get(); if (currentNumOfAttempts > 0 && currentNumOfAttempts < maxAttempts) { succeededAfterRetryCounter.increment(); publishRetryEvent( () -> new RetryOnSuccessEvent(name, currentNumOfAttempts, lastException.get())); } else { if (currentNumOfAttempts >= maxAttempts) { failedAfterRetryCounter.increment(); Throwable throwable = Optional.ofNullable(lastException.get()) .filter(p -> !failAfterMaxAttempts) .orElse(new MaxRetriesExceeded( "max retries is reached out for the result predicate check" )); publishRetryEvent(() -> new RetryOnErrorEvent(name, currentNumOfAttempts, throwable)); if (failAfterMaxAttempts) { throw MaxRetriesExceededException.createMaxRetriesExceededException(RetryImpl.this); } } else { succeededWithoutRetryCounter.increment(); } } } @Override public long onError(Throwable throwable) { totalAttemptsCounter.increment(); // Handle the case if the completable future throw CompletionException wrapping the original exception // where original exception is the one to retry not the CompletionException. if (throwable instanceof CompletionException || throwable instanceof ExecutionException) { Throwable cause = throwable.getCause(); return handleThrowable(cause); } else { return handleThrowable(throwable); } } private long handleThrowable(Throwable throwable) { if (!exceptionPredicate.test(throwable)) { failedWithoutRetryCounter.increment(); publishRetryEvent(() -> new RetryOnIgnoredErrorEvent(getName(), throwable)); return -1; } return handleOnError(throwable); } private long handleOnError(Throwable throwable) { lastException.set(throwable); int attempt = numOfAttempts.incrementAndGet(); if (attempt >= maxAttempts) { failedAfterRetryCounter.increment(); publishRetryEvent(() -> new RetryOnErrorEvent(name, attempt, throwable)); return -1; } long interval = intervalBiFunction.apply(attempt, Either.left(throwable)); if (interval < 0) { publishRetryEvent(() -> new RetryOnErrorEvent(getName(), attempt, throwable)); } else { publishRetryEvent(() -> new RetryOnRetryEvent(getName(), attempt, throwable, interval)); } return interval; } @Override public long onResult(T result) { if (null != resultPredicate && resultPredicate.test(result)) { totalAttemptsCounter.increment(); int currentNumOfAttempts = numOfAttempts.incrementAndGet(); if (currentNumOfAttempts >= maxAttempts) { return -1; } if(consumeResultBeforeRetryAttempt != null){ consumeResultBeforeRetryAttempt.accept(currentNumOfAttempts, result); } Long interval = intervalBiFunction.apply(currentNumOfAttempts, Either.right(result)); publishRetryEvent(() -> new RetryOnRetryEvent(getName(), currentNumOfAttempts, null, interval)); return interval; } return -1; } } public final
AsyncContextImpl
java
apache__camel
components/camel-stub/src/main/java/org/apache/camel/component/stub/StubConsumer.java
{ "start": 994, "end": 1152 }
class ____ extends SedaConsumer { public StubConsumer(SedaEndpoint endpoint, Processor processor) { super(endpoint, processor); } }
StubConsumer
java
junit-team__junit5
junit-vintage-engine/src/test/java/org/junit/vintage/engine/VintageUniqueIdBuilder.java
{ "start": 635, "end": 2400 }
class ____ { public static UniqueId uniqueIdForErrorInClass(Class<?> clazz, Class<?> failingClass) { return uniqueIdForClasses(clazz).append(VintageTestDescriptor.SEGMENT_TYPE_TEST, "initializationError(" + failingClass.getName() + ")"); } public static UniqueId uniqueIdForClass(Class<?> clazz) { return uniqueIdForClasses(clazz); } public static UniqueId uniqueIdForClasses(Class<?> clazz, Class<?>... clazzes) { var uniqueId = uniqueIdForClass(clazz.getName()); for (var each : clazzes) { uniqueId = uniqueId.append(VintageTestDescriptor.SEGMENT_TYPE_TEST, each.getName()); } return uniqueId; } public static UniqueId uniqueIdForClass(String fullyQualifiedClassName) { var containerId = engineId(); return containerId.append(VintageTestDescriptor.SEGMENT_TYPE_RUNNER, fullyQualifiedClassName); } public static UniqueId uniqueIdForMethod(Class<?> testClass, String methodName) { return uniqueIdForClass(testClass).append(VintageTestDescriptor.SEGMENT_TYPE_TEST, methodValue(testClass, methodName)); } private static String methodValue(Class<?> testClass, String methodName) { return methodName + "(" + testClass.getName() + ")"; } public static UniqueId uniqueIdForMethod(Class<?> testClass, String methodName, String index) { return uniqueIdForClass(testClass).append(VintageTestDescriptor.SEGMENT_TYPE_TEST, methodValue(testClass, methodName) + "[" + index + "]"); } public static UniqueId uniqueIdForMethod(UniqueId containerId, Class<?> testClass, String methodName) { return containerId.append(VintageTestDescriptor.SEGMENT_TYPE_TEST, methodValue(testClass, methodName)); } public static UniqueId engineId() { return UniqueId.forEngine(VintageTestDescriptor.ENGINE_ID); } }
VintageUniqueIdBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/instantiation/InstantiationWithCollectionTest.java
{ "start": 5845, "end": 6267 }
class ____ { @GeneratedValue @Id Long id; @ElementCollection Set<String> names; @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST) Set<ChildEntity> children; Entity(String... names) { this.names = Set.of(names); this.children = new HashSet<>(); } Entity() { names = new HashSet<>(); children = new HashSet<>(); } } @jakarta.persistence.Entity(name="ChildEntity") static
Entity
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/jdbc/PrimaryDataSourceTests.java
{ "start": 1752, "end": 2539 }
class ____ { @Primary @Bean DataSource primaryDataSource() { // @formatter:off return new EmbeddedDatabaseBuilder() .generateUniqueName(true) .addScript("classpath:/org/springframework/test/context/jdbc/schema.sql") .build(); // @formatter:on } @Bean DataSource additionalDataSource() { return new EmbeddedDatabaseBuilder().generateUniqueName(true).build(); } } private JdbcTemplate jdbcTemplate; @Autowired void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Test @Sql("data.sql") void dataSourceTest() { assertThatTransaction().isNotActive(); assertThat(JdbcTestUtils.countRowsInTable(this.jdbcTemplate, "user")).as("Number of rows in the 'user' table.").isEqualTo(1); } }
Config
java
elastic__elasticsearch
modules/percolator/src/test/java/org/elasticsearch/percolator/PercolatorMatchedSlotSubFetchPhaseTests.java
{ "start": 1913, "end": 9267 }
class ____ extends ESTestCase { public void testHitsExecute() throws Exception { try (Directory directory = newDirectory()) { // Need a one doc index: try (RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory)) { Document document = new Document(); indexWriter.addDocument(document); } PercolatorMatchedSlotSubFetchPhase phase = new PercolatorMatchedSlotSubFetchPhase(); try (DirectoryReader reader = DirectoryReader.open(directory)) { LeafReaderContext context = reader.leaves().get(0); // A match: { HitContext hit = new HitContext(SearchHit.unpooled(0), context, 0, Map.of(), Source.empty(null), null); PercolateQuery.QueryStore queryStore = ctx -> docId -> new TermQuery(new Term("field", "value")); MemoryIndex memoryIndex = new MemoryIndex(); memoryIndex.addField("field", "value", new WhitespaceAnalyzer()); memoryIndex.addField(new NumericDocValuesField(SeqNoFieldMapper.PRIMARY_TERM_NAME, 0), null); PercolateQuery percolateQuery = new PercolateQuery( "_name", queryStore, Collections.emptyList(), new MatchAllDocsQuery(), memoryIndex.createSearcher(), null, new MatchNoDocsQuery() ); FetchContext sc = mock(FetchContext.class); when(sc.query()).thenReturn(percolateQuery); SearchExecutionContext sec = mock(SearchExecutionContext.class); when(sc.getSearchExecutionContext()).thenReturn(sec); when(sec.indexVersionCreated()).thenReturn(IndexVersion.current()); FetchSubPhaseProcessor processor = phase.getProcessor(sc); assertNotNull(processor); processor.process(hit); assertNotNull(hit.hit().field(PercolatorMatchedSlotSubFetchPhase.FIELD_NAME_PREFIX)); assertEquals(0, (int) hit.hit().field(PercolatorMatchedSlotSubFetchPhase.FIELD_NAME_PREFIX).getValue()); } // No match: { HitContext hit = new HitContext(SearchHit.unpooled(0), context, 0, Map.of(), Source.empty(null), null); PercolateQuery.QueryStore queryStore = ctx -> docId -> new TermQuery(new Term("field", "value")); MemoryIndex memoryIndex = new MemoryIndex(); memoryIndex.addField("field", "value1", new WhitespaceAnalyzer()); memoryIndex.addField(new NumericDocValuesField(SeqNoFieldMapper.PRIMARY_TERM_NAME, 0), null); PercolateQuery percolateQuery = new PercolateQuery( "_name", queryStore, Collections.emptyList(), new MatchAllDocsQuery(), memoryIndex.createSearcher(), null, new MatchNoDocsQuery() ); FetchContext sc = mock(FetchContext.class); when(sc.query()).thenReturn(percolateQuery); SearchExecutionContext sec = mock(SearchExecutionContext.class); when(sc.getSearchExecutionContext()).thenReturn(sec); when(sec.indexVersionCreated()).thenReturn(IndexVersion.current()); FetchSubPhaseProcessor processor = phase.getProcessor(sc); assertNotNull(processor); processor.process(hit); assertNull(hit.hit().field(PercolatorMatchedSlotSubFetchPhase.FIELD_NAME_PREFIX)); } // No query: { HitContext hit = new HitContext(SearchHit.unpooled(0), context, 0, Map.of(), Source.empty(null), null); PercolateQuery.QueryStore queryStore = ctx -> docId -> null; MemoryIndex memoryIndex = new MemoryIndex(); memoryIndex.addField("field", "value", new WhitespaceAnalyzer()); memoryIndex.addField(new NumericDocValuesField(SeqNoFieldMapper.PRIMARY_TERM_NAME, 0), null); PercolateQuery percolateQuery = new PercolateQuery( "_name", queryStore, Collections.emptyList(), new MatchAllDocsQuery(), memoryIndex.createSearcher(), null, new MatchNoDocsQuery() ); FetchContext sc = mock(FetchContext.class); when(sc.query()).thenReturn(percolateQuery); SearchExecutionContext sec = mock(SearchExecutionContext.class); when(sc.getSearchExecutionContext()).thenReturn(sec); when(sec.indexVersionCreated()).thenReturn(IndexVersion.current()); FetchSubPhaseProcessor processor = phase.getProcessor(sc); assertNotNull(processor); processor.process(hit); assertNull(hit.hit().field(PercolatorMatchedSlotSubFetchPhase.FIELD_NAME_PREFIX)); } } } } public void testConvertTopDocsToSlots() { ScoreDoc[] scoreDocs = new ScoreDoc[randomInt(128)]; for (int i = 0; i < scoreDocs.length; i++) { scoreDocs[i] = new ScoreDoc(i, 1f); } TopDocs topDocs = new TopDocs(new TotalHits(scoreDocs.length, TotalHits.Relation.EQUAL_TO), scoreDocs); IntStream stream = PercolatorMatchedSlotSubFetchPhase.convertTopDocsToSlots(topDocs, null); int[] result = stream.toArray(); assertEquals(scoreDocs.length, result.length); for (int i = 0; i < scoreDocs.length; i++) { assertEquals(scoreDocs[i].doc, result[i]); } } public void testConvertTopDocsToSlots_nestedDocs() { ScoreDoc[] scoreDocs = new ScoreDoc[5]; scoreDocs[0] = new ScoreDoc(2, 1f); scoreDocs[1] = new ScoreDoc(5, 1f); scoreDocs[2] = new ScoreDoc(8, 1f); scoreDocs[3] = new ScoreDoc(11, 1f); scoreDocs[4] = new ScoreDoc(14, 1f); TopDocs topDocs = new TopDocs(new TotalHits(scoreDocs.length, TotalHits.Relation.EQUAL_TO), scoreDocs); FixedBitSet bitSet = new FixedBitSet(15); bitSet.set(2); bitSet.set(5); bitSet.set(8); bitSet.set(11); bitSet.set(14); int[] rootDocsBySlot = PercolatorMatchedSlotSubFetchPhase.buildRootDocsSlots(bitSet); int[] result = PercolatorMatchedSlotSubFetchPhase.convertTopDocsToSlots(topDocs, rootDocsBySlot).toArray(); assertEquals(scoreDocs.length, result.length); assertEquals(0, result[0]); assertEquals(1, result[1]); assertEquals(2, result[2]); assertEquals(3, result[3]); assertEquals(4, result[4]); } }
PercolatorMatchedSlotSubFetchPhaseTests
java
google__guava
android/guava/src/com/google/common/graph/EndpointPair.java
{ "start": 1547, "end": 5330 }
class ____<N> implements Iterable<N> { private final N nodeU; private final N nodeV; private EndpointPair(N nodeU, N nodeV) { this.nodeU = checkNotNull(nodeU); this.nodeV = checkNotNull(nodeV); } /** Returns an {@link EndpointPair} representing the endpoints of a directed edge. */ public static <N> EndpointPair<N> ordered(N source, N target) { return new Ordered<>(source, target); } /** Returns an {@link EndpointPair} representing the endpoints of an undirected edge. */ public static <N> EndpointPair<N> unordered(N nodeU, N nodeV) { // Swap nodes on purpose to prevent callers from relying on the "ordering" of an unordered pair. return new Unordered<>(nodeV, nodeU); } /** Returns an {@link EndpointPair} representing the endpoints of an edge in {@code graph}. */ static <N> EndpointPair<N> of(Graph<?> graph, N nodeU, N nodeV) { return graph.isDirected() ? ordered(nodeU, nodeV) : unordered(nodeU, nodeV); } /** Returns an {@link EndpointPair} representing the endpoints of an edge in {@code network}. */ static <N> EndpointPair<N> of(Network<?, ?> network, N nodeU, N nodeV) { return network.isDirected() ? ordered(nodeU, nodeV) : unordered(nodeU, nodeV); } /** * If this {@link EndpointPair} {@link #isOrdered()}, returns the node which is the source. * * @throws UnsupportedOperationException if this {@link EndpointPair} is not ordered */ public abstract N source(); /** * If this {@link EndpointPair} {@link #isOrdered()}, returns the node which is the target. * * @throws UnsupportedOperationException if this {@link EndpointPair} is not ordered */ public abstract N target(); /** * If this {@link EndpointPair} {@link #isOrdered()} returns the {@link #source()}; otherwise, * returns an arbitrary (but consistent) endpoint of the origin edge. */ public final N nodeU() { return nodeU; } /** * Returns the node {@link #adjacentNode(Object) adjacent} to {@link #nodeU()} along the origin * edge. If this {@link EndpointPair} {@link #isOrdered()}, this is equal to {@link #target()}. */ public final N nodeV() { return nodeV; } /** * Returns the node that is adjacent to {@code node} along the origin edge. * * @throws IllegalArgumentException if this {@link EndpointPair} does not contain {@code node} * @since 20.0 (but the argument type was changed from {@code Object} to {@code N} in 31.0) */ public final N adjacentNode(N node) { if (node.equals(nodeU)) { return nodeV; } else if (node.equals(nodeV)) { return nodeU; } else { throw new IllegalArgumentException("EndpointPair " + this + " does not contain node " + node); } } /** * Returns {@code true} if this {@link EndpointPair} is an ordered pair (i.e. represents the * endpoints of a directed edge). */ public abstract boolean isOrdered(); /** Iterates in the order {@link #nodeU()}, {@link #nodeV()}. */ @Override public final UnmodifiableIterator<N> iterator() { return Iterators.forArray(nodeU, nodeV); } /** * Two ordered {@link EndpointPair}s are equal if their {@link #source()} and {@link #target()} * are equal. Two unordered {@link EndpointPair}s are equal if they contain the same nodes. An * ordered {@link EndpointPair} is never equal to an unordered {@link EndpointPair}. */ @Override public abstract boolean equals(@Nullable Object obj); /** * The hashcode of an ordered {@link EndpointPair} is equal to {@code Objects.hash(source(), * target())}. The hashcode of an unordered {@link EndpointPair} is equal to {@code * nodeU().hashCode() + nodeV().hashCode()}. */ @Override public abstract int hashCode(); private static final
EndpointPair
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/proxy/fakedns/FakeDNSServer.java
{ "start": 8270, "end": 13296 }
class ____ extends HashMap<String, String> implements ResourceRecord { private final String domainName; private final RecordType recordType; private final RecordClass recordClass; private final int ttl; public Record(String domainName, RecordType recordType, RecordClass recordClass, int ttl) { this.domainName = domainName; this.recordType = recordType; this.recordClass = recordClass; this.ttl = ttl; } public Record ipAddress(String ipAddress) { return set(DnsAttribute.IP_ADDRESS, ipAddress); } public Record set(String name, Object value) { put(name, "" + value); return this; } @Override public String getDomainName() { return domainName; } @Override public RecordType getRecordType() { return recordType; } @Override public RecordClass getRecordClass() { return recordClass; } @Override public int getTimeToLive() { return ttl; } @Override public String get(String id) { return get((Object) id); } } public FakeDNSServer testLookup4(String ip) { return store(questionRecord -> { Set<ResourceRecord> set = new HashSet<>(); if (questionRecord.getRecordType() == RecordType.A) { set.add(a("vertx.io", 100).ipAddress(ip)); } return set; }); } public FakeDNSServer testLookup6(String ip) { return store(questionRecord -> { Set<ResourceRecord> set = new HashSet<>(); if (questionRecord.getRecordType() == RecordType.AAAA) { set.add(aaaa("vertx.io", 100).ipAddress(ip)); } return set; }); } public FakeDNSServer testLookupNonExisting() { return store(questionRecord -> null); } public FakeDNSServer testReverseLookup(final String ptr) { return store(questionRecord -> Collections.singleton(ptr(ptr, 100) .set(DnsAttribute.DOMAIN_NAME, "vertx.io"))); } public FakeDNSServer testResolveASameServer(final String ipAddress) { return store(A_store(Collections.singletonMap("vertx.io", ipAddress))); } public FakeDNSServer testLookup4CNAME(final String cname, final String ip) { return store(questionRecord -> { // use LinkedHashSet since the order of the result records has to be preserved to make sure the unit test fails Set<ResourceRecord> set = new LinkedHashSet<>(); ResourceRecordModifier rm = new ResourceRecordModifier(); set.add(cname("vertx.io", 100).set(DnsAttribute.DOMAIN_NAME, cname)); set.add(a(cname, 100).ipAddress(ip)); return set; }); } @Override public void start() throws IOException { DnsProtocolHandler handler = new DnsProtocolHandler(this, question -> { RecordStore actual = store; if (actual == null) { return Collections.emptySet(); } else { return actual.getRecords(question); } }) { @Override public void sessionCreated(IoSession session) { // Use our own codec to support AAAA testing if (session.getTransportMetadata().isConnectionless()) { session.getFilterChain().addFirst("codec", new ProtocolCodecFilter(new TestDnsProtocolUdpCodecFactory())); } else { session.getFilterChain().addFirst("codec", new ProtocolCodecFilter(new TestDnsProtocolTcpCodecFactory())); } } @Override public void messageReceived(IoSession session, Object message) { if (message instanceof DnsMessage) { synchronized (FakeDNSServer.this) { currentMessage.add((DnsMessage) message); } } super.messageReceived(session, message); } }; UdpTransport udpTransport = new UdpTransport(ipAddress, port); ((DatagramSessionConfig) udpTransport.getAcceptor().getSessionConfig()).setReuseAddress(true); TcpTransport tcpTransport = new TcpTransport(ipAddress, port); tcpTransport.getAcceptor().getSessionConfig().setReuseAddress(true); setTransports(udpTransport, tcpTransport); for (Transport transport : getTransports()) { IoAcceptor acceptor = transport.getAcceptor(); acceptor.setHandler(handler); // Start the listener acceptor.bind(); } } @Override public void stop() { for (Transport transport : getTransports()) { transport.getAcceptor().dispose(); } } public static
Record
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/spi/cluster/RegistrationListener.java
{ "start": 591, "end": 1330 }
interface ____ { /** * Invoked by the {@link ClusterManager} when messaging handler registrations are added or removed. */ default void registrationsUpdated(RegistrationUpdateEvent event) { } /** * Invoked by the {@link ClusterManager} when some handler registrations have been lost. */ default void registrationsLost() { } /** * Invoked by the {@link ClusterManager} to determine if the node selector wants updates for the given {@code address}. * * @param address the event bus address * @return {@code true} if the node selector wants updates for the given {@code address}, {@code false} otherwise */ default boolean wantsUpdatesFor(String address) { return true; } }
RegistrationListener
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metagen/mappedsuperclass/embeddedid/MappedSuperclassWithEmbeddedIdTest.java
{ "start": 615, "end": 1356 }
class ____ { @Test @JiraKey( value = "HHH-5024" ) public void testStaticMetamodel() { EntityManagerFactory emf = TestingEntityManagerFactoryGenerator.generateEntityManagerFactory( AvailableSettings.LOADED_CLASSES, Arrays.asList( Product.class ) ); try { assertNotNull( Product_.description, "'Product_.description' should not be null)" ); assertNotNull( Product_.id, "'Product_.id' should not be null)" ); assertNotNull( AbstractProduct_.id, "'AbstractProduct_.id' should not be null)" ); assertNotNull( ProductId_.id, "'ProductId_.id' should not be null)" ); assertNotNull( ProductId_.code, "'ProductId_.code' should not be null)" ); } finally { emf.close(); } } }
MappedSuperclassWithEmbeddedIdTest
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java
{ "start": 27496, "end": 27683 }
class ____<T extends AbstractBounded<T>, L extends T> extends MyHomer<T, L> { @Override public void foo(L t) { throw new UnsupportedOperationException(); } } public
YourHomer
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FutureTransformAsyncTest.java
{ "start": 7223, "end": 8304 }
class ____ { private Executor executor; private void throwIfLarge(int unused) throws FileNotFoundException {} ListenableFuture<String> test() { ListenableFuture<String> future = Futures.transformAsync( Futures.immediateFuture(5), value -> { throwIfLarge(value); return Futures.immediateFuture("value: " + value); }, executor); return future; } } """) .doTest(); } @Test public void transformAsync_expressionLambda_methodThrowsCheckedException() { compilationHelper .addSourceLines( "in/Test.java", """ import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.io.FileNotFoundException; import java.util.concurrent.Executor;
Test
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/test/KerberosTestUtils.java
{ "start": 2339, "end": 4779 }
class ____ extends Configuration { private String principal; public KerberosConfiguration(String principal) { this.principal = principal; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { Map<String, String> options = new HashMap<String, String>(); options.put("keyTab", KerberosTestUtils.getKeytabFile()); options.put("principal", principal); options.put("useKeyTab", "true"); options.put("storeKey", "true"); options.put("doNotPrompt", "true"); options.put("useTicketCache", "true"); options.put("renewTGT", "true"); options.put("refreshKrb5Config", "true"); options.put("isInitiator", "true"); String ticketCache = System.getenv("KRB5CCNAME"); if (ticketCache != null) { options.put("ticketCache", ticketCache); } options.put("debug", "true"); return new AppConfigurationEntry[]{ new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options),}; } } public static <T> T doAs(String principal, final Callable<T> callable) throws Exception { LoginContext loginContext = null; try { Set<Principal> principals = new HashSet<Principal>(); principals.add( new KerberosPrincipal(KerberosTestUtils.getClientPrincipal())); Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); loginContext = new LoginContext("", subject, null, new KerberosConfiguration(principal)); loginContext.login(); subject = loginContext.getSubject(); return Subject.doAs(subject, new PrivilegedExceptionAction<T>() { @Override public T run() throws Exception { return callable.call(); } }); } catch (PrivilegedActionException ex) { throw ex.getException(); } finally { if (loginContext != null) { loginContext.logout(); } } } public static <T> T doAsClient(Callable<T> callable) throws Exception { return doAs(getClientPrincipal(), callable); } public static <T> T doAsServer(Callable<T> callable) throws Exception { return doAs(getServerPrincipal(), callable); } }
KerberosConfiguration
java
square__moshi
moshi/src/test/java/com/squareup/moshi/MoshiTest.java
{ "start": 9577, "end": 11036 }
class ____ { adapter.fromJson("null"); fail(); } catch (JsonDataException expected) { assertThat(expected).hasMessageThat().isEqualTo("Expected a double but was NULL at path $"); } try { adapter.toJson(null); fail(); } catch (NullPointerException expected) { } // Non-lenient adapter won't allow values outside of range. adapter = moshi.adapter(double.class); JsonReader reader = newReader("[1E309]"); reader.beginArray(); try { adapter.fromJson(reader); fail(); } catch (IOException expected) { assertThat(expected) .hasMessageThat() .isEqualTo("JSON forbids NaN and infinities: Infinity at path $[0]"); } reader = newReader("[-1E309]"); reader.beginArray(); try { adapter.fromJson(reader); fail(); } catch (IOException expected) { assertThat(expected) .hasMessageThat() .isEqualTo("JSON forbids NaN and infinities: -Infinity at path $[0]"); } } @Test public void DoubleAdapter() throws Exception { Moshi moshi = new Moshi.Builder().build(); JsonAdapter<Double> adapter = moshi.adapter(Double.class).lenient(); assertThat(adapter.fromJson("1.0")).isEqualTo(1.0); assertThat(adapter.fromJson("1")).isEqualTo(1.0); assertThat(adapter.fromJson("1e0")).isEqualTo(1.0); assertThat(adapter.toJson(-2.0)).isEqualTo("-2.0"); // Allow nulls for Double.
try
java
apache__camel
components/camel-xmpp/src/main/java/org/apache/camel/component/xmpp/XmppLogger.java
{ "start": 1001, "end": 1424 }
class ____ implements StanzaListener { private static final Logger LOG = LoggerFactory.getLogger(XmppLogger.class); private String direction; public XmppLogger(String direction) { this.direction = direction; } @Override public void processStanza(Stanza stanza) { if (LOG.isDebugEnabled()) { LOG.debug("{} : {}", direction, stanza.toXML(null)); } } }
XmppLogger
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/tools/protocolPB/GetUserMappingsProtocolPB.java
{ "start": 1518, "end": 1617 }
interface ____ extends GetUserMappingsProtocolService.BlockingInterface { }
GetUserMappingsProtocolPB
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1900/Issue1987.java
{ "start": 248, "end": 1352 }
class ____ extends TestCase { public void test_for_issue() throws Exception { JsonExample example = new JsonExample(); //test1 正确执行, test2, test3 执行出错 com.alibaba.fastjson.JSONException: can not cast to : java.time.LocalDateTime example.setTestLocalDateTime(LocalDateTime.now()); //纳秒数设置为0 ,test1,test2,test3 全部正确执行 //example.setTestLocalDateTime(LocalDateTime.now().withNano(0)); String text = JSON.toJSONString(example, SerializerFeature.PrettyFormat); System.out.println(text); //test1, 全部可以正常执行 JsonExample example1 = JSON.parseObject(text, JsonExample.class); System.out.println(JSON.toJSONString(example1)); //test2 纳秒数为0, 可以正常执行, 不为0则报错 JsonExample example2 = JSONObject.parseObject(text).toJavaObject(JsonExample.class); System.out.println(JSON.toJSONString(example2)); //test3 纳秒数为0, 可以正常执行, 不为0则报错 JsonExample example3 = JSON.parseObject(text).toJavaObject(JsonExample.class); System.out.println(JSON.toJSONString(example3)); } public static
Issue1987
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1300/Issue1306.java
{ "start": 1815, "end": 1964 }
class ____ extends LongEntity{ private static final long serialVersionUID = 7941148286688199390L; } } public static
Property
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/lib/input/TestCombineFileInputFormat.java
{ "start": 6449, "end": 7931 }
class ____ extends RecordReader<Text, Text> { private TaskAttemptContext context; private CombineFileSplit s; private int idx; private boolean used; public DummyRecordReader(CombineFileSplit split, TaskAttemptContext context, Integer i) { this.context = context; this.idx = i; this.s = split; this.used = true; } /** @return a value specified in the context to check whether the * context is properly updated by the initialize() method. */ public String getDummyConfVal() { return this.context.getConfiguration().get(DUMMY_KEY); } public void initialize(InputSplit split, TaskAttemptContext context) { this.context = context; this.s = (CombineFileSplit) split; // By setting used to true in the c'tor, but false in initialize, // we can check that initialize() is always called before use // (e.g., in testReinit()). this.used = false; } public boolean nextKeyValue() { boolean ret = !used; this.used = true; return ret; } public Text getCurrentKey() { return new Text(this.context.getConfiguration().get(DUMMY_KEY)); } public Text getCurrentValue() { return new Text(this.s.getPath(idx).toString()); } public float getProgress() { return used ? 1.0f : 0.0f; } public void close() { } } /** Extend CFIF to use CFRR with DummyRecordReader */ private
DummyRecordReader
java
google__dagger
javatests/dagger/internal/codegen/ComponentProcessorTest.java
{ "start": 17489, "end": 18291 }
interface ____ {}"); CompilerTests.daggerCompiler(rootModule, component) .withProcessingOptions(compilerMode.processorOptions()) .compile(subject -> subject.hasError()); CompilerTests.daggerCompiler(rootModule, component) .withProcessingOptions(compilerMode.processorOptions()) .withProcessingSteps(() -> new GeneratingProcessingStep("test", GENERATED_MODULE)) .compile(subject -> subject.hasErrorCount(0)); } @Test public void generatedModuleInSubcomponent() { Source subcomponent = CompilerTests.javaSource( "test.ChildComponent", "package test;", "", "import dagger.Subcomponent;", "", "@Subcomponent(modules = GeneratedModule.class)", "
TestComponent
java
apache__rocketmq
filter/src/main/java/org/apache/rocketmq/filter/expression/BooleanConstantExpression.java
{ "start": 895, "end": 1550 }
class ____ extends ConstantExpression implements BooleanExpression { public static final BooleanConstantExpression NULL = new BooleanConstantExpression(null); public static final BooleanConstantExpression TRUE = new BooleanConstantExpression(Boolean.TRUE); public static final BooleanConstantExpression FALSE = new BooleanConstantExpression(Boolean.FALSE); public BooleanConstantExpression(Object value) { super(value); } public boolean matches(EvaluationContext context) throws Exception { Object object = evaluate(context); return object != null && object == Boolean.TRUE; } }
BooleanConstantExpression
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/project/MavenProject.java
{ "start": 49200, "end": 49421 }
class ____ hosting the build extensions of this project, may be {@code null}. */ public void setClassRealm(ClassRealm classRealm) { this.classRealm = classRealm; } /** * Gets the project's
realm
java
apache__flink
flink-filesystems/flink-oss-fs-hadoop/src/main/java/org/apache/flink/fs/osshadoop/FlinkOSSFileSystem.java
{ "start": 1649, "end": 3541 }
class ____ extends HadoopFileSystem { // Minimum size of each of or multipart pieces in bytes public static final long MULTIPART_UPLOAD_PART_SIZE_MIN = 10L << 20; // Size of each of or multipart pieces in bytes private long ossUploadPartSize; private int maxConcurrentUploadsPerStream; private final Executor uploadThreadPool; private String localTmpDir; private final FunctionWithException<File, RefCountedFileWithStream, IOException> cachedFileCreator; private OSSAccessor ossAccessor; public FlinkOSSFileSystem( org.apache.hadoop.fs.FileSystem fileSystem, long ossUploadPartSize, int maxConcurrentUploadsPerStream, String localTmpDirectory, OSSAccessor ossAccessor) { super(fileSystem); Preconditions.checkArgument(ossUploadPartSize >= MULTIPART_UPLOAD_PART_SIZE_MIN); this.ossUploadPartSize = ossUploadPartSize; this.maxConcurrentUploadsPerStream = maxConcurrentUploadsPerStream; this.uploadThreadPool = Executors.newCachedThreadPool(); // recoverable writer parameter configuration initialization // Temporary directory for cache data before uploading to OSS this.localTmpDir = Preconditions.checkNotNull(localTmpDirectory); this.cachedFileCreator = RefCountedTmpFileCreator.inDirectories(new File(localTmpDirectory)); this.ossAccessor = ossAccessor; } @Override public RecoverableWriter createRecoverableWriter() throws IOException { return new OSSRecoverableWriter( ossAccessor, ossUploadPartSize, maxConcurrentUploadsPerStream, uploadThreadPool, cachedFileCreator); } public String getLocalTmpDir() { return localTmpDir; } }
FlinkOSSFileSystem
java
apache__flink
flink-core/src/main/java/org/apache/flink/core/fs/AutoCloseableRegistry.java
{ "start": 1267, "end": 1551 }
class ____ to register instances of {@link AutoCloseable}, which are all closed if this * registry is closed. * * <p>Registering to an already closed registry will throw an exception and close the provided * {@link AutoCloseable}. * * <p>Unlike {@link CloseableRegistry} this
allows
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/api/AssertThrowsAssertionsTests.java
{ "start": 9805, "end": 9920 }
class ____ extends RuntimeException { @Serial private static final long serialVersionUID = 1L; } }
LocalException
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialContainsCartesianPointDocValuesAndConstantEvaluator.java
{ "start": 1167, "end": 3640 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(SpatialContainsCartesianPointDocValuesAndConstantEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator left; private final Component2D[] right; private final DriverContext driverContext; private Warnings warnings; public SpatialContainsCartesianPointDocValuesAndConstantEvaluator(Source source, EvalOperator.ExpressionEvaluator left, Component2D[] right, DriverContext driverContext) { this.source = source; this.left = left; this.right = right; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (LongBlock leftBlock = (LongBlock) left.eval(page)) { return eval(page.getPositionCount(), leftBlock); } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += left.baseRamBytesUsed(); return baseRamBytesUsed; } public BooleanBlock eval(int positionCount, LongBlock leftBlock) { try(BooleanBlock.Builder result = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { boolean allBlocksAreNulls = true; if (!leftBlock.isNull(p)) { allBlocksAreNulls = false; } if (allBlocksAreNulls) { result.appendNull(); continue position; } try { SpatialContains.processCartesianPointDocValuesAndConstant(result, p, leftBlock, this.right); } catch (IllegalArgumentException | IOException e) { warnings().registerException(e); result.appendNull(); } } return result.build(); } } @Override public String toString() { return "SpatialContainsCartesianPointDocValuesAndConstantEvaluator[" + "left=" + left + ", right=" + right + "]"; } @Override public void close() { Releasables.closeExpectNoException(left); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
SpatialContainsCartesianPointDocValuesAndConstantEvaluator
java
grpc__grpc-java
okhttp/third_party/okhttp/main/java/io/grpc/okhttp/internal/framed/FrameWriter.java
{ "start": 856, "end": 4379 }
interface ____ extends Closeable { /** HTTP/2 only. */ void connectionPreface() throws IOException; /** Informs the peer that we've applied its latest settings. */ void ackSettings(Settings peerSettings) throws IOException; /** * HTTP/2 only. Send a push promise header block. * <p> * A push promise contains all the headers that pertain to a server-initiated * request, and a {@code promisedStreamId} to which response frames will be * delivered. Push promise frames are sent as a part of the response to * {@code streamId}. The {@code promisedStreamId} has a priority of one * greater than {@code streamId}. * * @param streamId client-initiated stream ID. Must be an odd number. * @param promisedStreamId server-initiated stream ID. Must be an even * number. * @param requestHeaders minimally includes {@code :method}, {@code :scheme}, * {@code :authority}, and {@code :path}. */ void pushPromise(int streamId, int promisedStreamId, List<Header> requestHeaders) throws IOException; /** SPDY/3 only. */ void flush() throws IOException; void synStream(boolean outFinished, boolean inFinished, int streamId, int associatedStreamId, List<Header> headerBlock) throws IOException; void synReply(boolean outFinished, int streamId, List<Header> headerBlock) throws IOException; void headers(int streamId, List<Header> headerBlock) throws IOException; void rstStream(int streamId, ErrorCode errorCode) throws IOException; /** The maximum size of bytes that may be sent in a single call to {@link #data}. */ int maxDataLength(); /** * {@code source.length} may be longer than the max length of the variant's data frame. * Implementations must send multiple frames as necessary. * * @param source the buffer to draw bytes from. May be null if byteCount is 0. * @param byteCount must be between 0 and the minimum of {code source.length} * and {@link #maxDataLength}. */ void data(boolean outFinished, int streamId, Buffer source, int byteCount) throws IOException; /** Write okhttp's settings to the peer. */ void settings(Settings okHttpSettings) throws IOException; /** * Send a connection-level ping to the peer. {@code ack} indicates this is * a reply. Payload parameters are different between SPDY/3 and HTTP/2. * <p> * In SPDY/3, only the first {@code payload1} parameter is sent. If the * sender is a client, it is an unsigned odd number. Likewise, a server * will send an even number. * <p> * In HTTP/2, both {@code payload1} and {@code payload2} parameters are * sent. The data is opaque binary, and there are no rules on the content. */ void ping(boolean ack, int payload1, int payload2) throws IOException; /** * Tell the peer to stop creating streams and that we last processed * {@code lastGoodStreamId}, or zero if no streams were processed. * * @param lastGoodStreamId the last stream ID processed, or zero if no * streams were processed. * @param errorCode reason for closing the connection. * @param debugData only valid for HTTP/2; opaque debug data to send. */ void goAway(int lastGoodStreamId, ErrorCode errorCode, byte[] debugData) throws IOException; /** * Inform peer that an additional {@code windowSizeIncrement} bytes can be * sent on {@code streamId}, or the connection if {@code streamId} is zero. */ void windowUpdate(int streamId, long windowSizeIncrement) throws IOException; }
FrameWriter
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/property/access/internal/PropertyAccessStrategyNoopImpl.java
{ "start": 1091, "end": 1574 }
class ____ implements PropertyAccess { /** * Singleton access */ public static final PropertyAccessNoopImpl INSTANCE = new PropertyAccessNoopImpl(); @Override public PropertyAccessStrategy getPropertyAccessStrategy() { return PropertyAccessStrategyNoopImpl.INSTANCE; } @Override public Getter getGetter() { return GetterImpl.INSTANCE; } @Override public Setter getSetter() { return SetterImpl.INSTANCE; } } private static
PropertyAccessNoopImpl
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobgraph/OperatorID.java
{ "start": 954, "end": 1404 }
class ____ extends AbstractID { private static final long serialVersionUID = 1L; public OperatorID() { super(); } public OperatorID(byte[] bytes) { super(bytes); } public OperatorID(long lowerPart, long upperPart) { super(lowerPart, upperPart); } public static OperatorID fromJobVertexID(JobVertexID id) { return new OperatorID(id.getLowerPart(), id.getUpperPart()); } }
OperatorID
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 84701, "end": 84874 }
class ____ {", " abstract int getBlim();", " abstract String getBlam();", "", " @AutoValue.Builder", " public
Baz
java
google__error-prone
core/src/test/java/com/google/errorprone/refaster/testdata/input/StaticImportClassTokenTemplateExample.java
{ "start": 725, "end": 843 }
class ____ { public void example() { boolean eq = "a" instanceof String; } }
StaticImportClassTokenTemplateExample
java
apache__rocketmq
remoting/src/test/java/org/apache/rocketmq/remoting/protocol/RemotingCommandTest.java
{ "start": 11246, "end": 11392 }
class ____ { @CFNotNull String nullString = null; String nullable = null; @CFNotNull String value = "NotNull"; }
FieldTestClass
java
apache__camel
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/annotation/TestInstancePerClassTest.java
{ "start": 1468, "end": 1698 }
class ____ that a new camel context is created for the entire test class. */ @CamelMainTest(mainClass = MyMainClass.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
ensuring
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/runnerjar/BasicExecutableOutputOutcomeTest.java
{ "start": 201, "end": 1986 }
class ____ extends BootstrapFromOriginalJarTestBase { @Override protected TsArtifact composeApplication() { final TsQuarkusExt coreExt = new TsQuarkusExt("core-ext"); addToExpectedLib(coreExt.getRuntime()); final TsQuarkusExt ext1 = new TsQuarkusExt("ext1"); ext1.addDependency(coreExt); addToExpectedLib(ext1.getRuntime()); final TsQuarkusExt ext2 = new TsQuarkusExt("ext2"); addToExpectedLib(ext2.getRuntime()); final TsArtifact transitiveDep1 = TsArtifact.jar("transitive1"); addToExpectedLib(transitiveDep1); final TsArtifact optionalTransitiveDep = TsArtifact.jar("optional-transitive-dep"); final TsArtifact compileDep = TsArtifact.jar("compile-dep") .addDependency(transitiveDep1) .addDependency(new TsDependency(optionalTransitiveDep, true)); addToExpectedLib(compileDep); final TsArtifact providedDep = TsArtifact.jar("provided-dep"); final TsArtifact optionalDep = TsArtifact.jar("optional-dep"); addToExpectedLib(optionalDep); final TsArtifact directRtDep = TsArtifact.jar("runtime-dep"); addToExpectedLib(directRtDep); final TsArtifact appJar = TsArtifact.jar("app") .addManagedDependency(platformDescriptor()) .addManagedDependency(platformProperties()) .addDependency(ext1) .addDependency(ext2) .addDependency(compileDep) .addDependency(new TsDependency(providedDep, "provided")) .addDependency(new TsDependency(optionalDep, true)) .addDependency(new TsDependency(directRtDep, "runtime")); return appJar; } }
BasicExecutableOutputOutcomeTest
java
elastic__elasticsearch
modules/repository-s3/src/test/java/org/elasticsearch/repositories/s3/S3BlobContainerRetriesTests.java
{ "start": 49807, "end": 52536 }
class ____ extends S3HttpHandler { private static final String THROTTLING_ERROR_CODE = "SlowDown"; private final AtomicInteger throttleTimesBeforeSuccess; private final AtomicInteger numberOfDeleteAttempts; private final AtomicInteger numberOfSuccessfulDeletes; private final IntConsumer onAttemptCallback; private final String errorCode; ThrottlingDeleteHandler(int throttleTimesBeforeSuccess, IntConsumer onAttemptCallback) { this(throttleTimesBeforeSuccess, onAttemptCallback, THROTTLING_ERROR_CODE); } ThrottlingDeleteHandler(int throttleTimesBeforeSuccess, IntConsumer onAttemptCallback, String errorCode) { super("bucket"); this.numberOfDeleteAttempts = new AtomicInteger(); this.numberOfSuccessfulDeletes = new AtomicInteger(); this.throttleTimesBeforeSuccess = new AtomicInteger(throttleTimesBeforeSuccess); this.onAttemptCallback = onAttemptCallback; this.errorCode = errorCode; } @Override public void handle(HttpExchange exchange) throws IOException { if (isMultiDeleteRequest(exchange)) { onAttemptCallback.accept(numberOfDeleteAttempts.get()); numberOfDeleteAttempts.incrementAndGet(); if (throttleTimesBeforeSuccess.getAndDecrement() > 0) { final byte[] responseBytes = Strings.format(""" <?xml version="1.0" encoding="UTF-8"?> <Error> <Code>%s</Code> <Message>This is a throttling message</Message> <Resource>/bucket/</Resource> <RequestId>4442587FB7D0A2F9</RequestId> </Error>""", errorCode).getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(HttpStatus.SC_SERVICE_UNAVAILABLE, responseBytes.length); exchange.getResponseBody().write(responseBytes); exchange.close(); } else { numberOfSuccessfulDeletes.incrementAndGet(); super.handle(exchange); } } else { super.handle(exchange); } } } private Set<OperationPurpose> operationPurposesThatRetryOnDelete() { return Set.of(OperationPurpose.SNAPSHOT_DATA, OperationPurpose.SNAPSHOT_METADATA); } public void testGetRegisterRetries() { final var maxRetries = between(0, 3); final BlobContainer blobContainer = blobContainerBuilder().maxRetries(maxRetries).build();
ThrottlingDeleteHandler
java
apache__maven
impl/maven-core/src/test/java/org/apache/maven/project/DefaultProjectBuilderTest.java
{ "start": 1679, "end": 5090 }
class ____ { /** * Test the extractProjectId method to ensure it properly falls back to rawModel or fileModel * when effectiveModel is null, addressing issue #11292. */ @Test void testExtractProjectIdFallback() throws Exception { // Use reflection to access the private extractProjectId method Method extractProjectIdMethod = DefaultProjectBuilder.class.getDeclaredMethod("extractProjectId", ModelBuilderResult.class); extractProjectIdMethod.setAccessible(true); // Create a mock ModelBuilderResult with null effectiveModel but available rawModel ModelBuilderResult mockResult = new MockModelBuilderResult( null, // effectiveModel is null createMockModel("com.example", "test-project", "1.0.0"), // rawModel is available null // fileModel is null ); String projectId = (String) extractProjectIdMethod.invoke(null, mockResult); assertNotNull(projectId, "Project ID should not be null"); assertEquals( "com.example:test-project:jar:1.0.0", projectId, "Should extract project ID from rawModel when effectiveModel is null"); } /** * Test extractProjectId with fileModel fallback when both effectiveModel and rawModel are null. */ @Test void testExtractProjectIdFileModelFallback() throws Exception { Method extractProjectIdMethod = DefaultProjectBuilder.class.getDeclaredMethod("extractProjectId", ModelBuilderResult.class); extractProjectIdMethod.setAccessible(true); ModelBuilderResult mockResult = new MockModelBuilderResult( null, // effectiveModel is null null, // rawModel is null createMockModel("com.example", "test-project", "1.0.0") // fileModel is available ); String projectId = (String) extractProjectIdMethod.invoke(null, mockResult); assertNotNull(projectId, "Project ID should not be null"); assertEquals( "com.example:test-project:jar:1.0.0", projectId, "Should extract project ID from fileModel when effectiveModel and rawModel are null"); } /** * Test extractProjectId returns empty string when all models are null. */ @Test void testExtractProjectIdAllModelsNull() throws Exception { Method extractProjectIdMethod = DefaultProjectBuilder.class.getDeclaredMethod("extractProjectId", ModelBuilderResult.class); extractProjectIdMethod.setAccessible(true); ModelBuilderResult mockResult = new MockModelBuilderResult(null, null, null); String projectId = (String) extractProjectIdMethod.invoke(null, mockResult); assertNotNull(projectId, "Project ID should not be null"); assertEquals("", projectId, "Should return empty string when all models are null"); } private Model createMockModel(String groupId, String artifactId, String version) { return Model.newBuilder() .groupId(groupId) .artifactId(artifactId) .version(version) .packaging("jar") .build(); } /** * Mock implementation of ModelBuilderResult for testing. */ private static
DefaultProjectBuilderTest
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/RadioButtonsTag.java
{ "start": 6595, "end": 6729 }
class ____ extends AbstractMultiCheckedElementTag { @Override protected String getInputType() { return "radio"; } }
RadioButtonsTag
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/security/authenticator/SaslAuthenticatorFailurePositiveDelayTest.java
{ "start": 863, "end": 1040 }
class ____ extends SaslAuthenticatorFailureDelayTest { public SaslAuthenticatorFailurePositiveDelayTest() { super(200); } }
SaslAuthenticatorFailurePositiveDelayTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/booleanarray/BooleanArrayAssert_isSorted_Test.java
{ "start": 914, "end": 1238 }
class ____ extends BooleanArrayAssertBaseTest { @Override protected BooleanArrayAssert invoke_api_method() { return assertions.isSorted(); } @Override protected void verify_internal_effects() { verify(arrays).assertIsSorted(getInfo(assertions), getActual(assertions)); } }
BooleanArrayAssert_isSorted_Test
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/EqualsBrokenForNullTest.java
{ "start": 4949, "end": 5390 }
class ____ { @Override // BUG: Diagnostic contains: if (other == null) { return false; } public boolean equals(Object other) { if (ObjectGetClassRightOperandDoubleEquals.class == other.getClass()) { return true; } return false; } } private
ObjectGetClassRightOperandDoubleEquals
java
apache__camel
components/camel-disruptor/src/main/java/org/apache/camel/component/disruptor/DisruptorProducer.java
{ "start": 1500, "end": 9649 }
class ____ extends DefaultAsyncProducer { private static final Logger LOG = LoggerFactory.getLogger(DisruptorProducer.class); private final WaitForTaskToComplete waitForTaskToComplete; private final long timeout; private final DisruptorEndpoint endpoint; private final boolean blockWhenFull; public DisruptorProducer(final DisruptorEndpoint endpoint, final WaitForTaskToComplete waitForTaskToComplete, final long timeout, boolean blockWhenFull) { super(endpoint); this.waitForTaskToComplete = waitForTaskToComplete; this.timeout = timeout; this.endpoint = endpoint; this.blockWhenFull = blockWhenFull; } @Override public DisruptorEndpoint getEndpoint() { return endpoint; } @Override protected void doStart() throws Exception { getEndpoint().onStarted(this); } @Override protected void doStop() throws Exception { getEndpoint().onStopped(this); } @Override public boolean process(final Exchange exchange, final AsyncCallback callback) { WaitForTaskToComplete wait = waitForTaskToComplete; if (exchange.getProperty(Exchange.ASYNC_WAIT) != null) { wait = exchange.getProperty(Exchange.ASYNC_WAIT, WaitForTaskToComplete.class); } try { if (wait == WaitForTaskToComplete.Always || wait == WaitForTaskToComplete.IfReplyExpected && ExchangeHelper.isOutCapable(exchange)) { // do not handover the completion as we wait for the copy to complete, and copy its result back when it done final Exchange copy = prepareCopy(exchange, false); // latch that waits until we are complete final CountDownLatch latch = new CountDownLatch(1); // we should wait for the reply so install a on completion so we know when its complete copy.getExchangeExtension().addOnCompletion(newOnCompletion(exchange, latch)); doPublish(copy); if (timeout > 0) { if (LOG.isTraceEnabled()) { LOG.trace("Waiting for task to complete using timeout (ms): {} at [{}]", timeout, endpoint.getEndpointUri()); } // lets see if we can get the task done before the timeout boolean done = false; try { done = latch.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.info("Interrupted while waiting for the task to complete"); Thread.currentThread().interrupt(); } if (!done) { // Remove timed out Exchange from disruptor endpoint. // We can't actually remove a published exchange from an active Disruptor. // Instead we prevent processing of the exchange by setting a Property on the exchange and the value // would be an AtomicBoolean. This is set by the Producer and the Consumer would look up that Property and // check the AtomicBoolean. If the AtomicBoolean says that we are good to proceed, it will process the // exchange. If false, it will simply disregard the exchange. // But since the Property map is a Concurrent one, maybe we don't need the AtomicBoolean. Check with Simon. // Also check the TimeoutHandler of the new Disruptor 3.0.0, consider making the switch to the latest version. exchange.setProperty(DisruptorEndpoint.DISRUPTOR_IGNORE_EXCHANGE, true); exchange.setException(new ExchangeTimedOutException(exchange, timeout)); // count down to indicate timeout latch.countDown(); } } else { if (LOG.isTraceEnabled()) { LOG.trace("Waiting for task to complete (blocking) at [{}]", endpoint.getEndpointUri()); } // no timeout then wait until its done try { latch.await(); } catch (InterruptedException e) { LOG.info("Interrupted while waiting for the task to complete"); Thread.currentThread().interrupt(); } } } else { // no wait, eg its a InOnly then just publish to the ringbuffer and return // handover the completion so its the copy which performs that, as we do not wait final Exchange copy = prepareCopy(exchange, true); doPublish(copy); } } catch (Exception e) { exchange.setException(e); } // we use OnCompletion on the Exchange to callback and wait for the Exchange to be done // so we should just signal the callback we are done synchronously callback.done(true); return true; } private SynchronizationAdapter newOnCompletion(Exchange exchange, CountDownLatch latch) { return new SynchronizationAdapter() { @Override public void onDone(final Exchange response) { // check for timeout, which then already would have invoked the latch if (latch.getCount() == 0) { if (LOG.isTraceEnabled()) { LOG.trace("{}. Timeout occurred so response will be ignored: {}", this, response.getMessage()); } } else { if (LOG.isTraceEnabled()) { LOG.trace("{} with response: {}", this, response.getMessage()); } try { ExchangeHelper.copyResults(exchange, response); } finally { // always ensure latch is triggered latch.countDown(); } } } @Override public boolean allowHandover() { // do not allow handover as we want to seda producer to have its completion triggered // at this point in the routing (at this leg), instead of at the very last (this ensure timeout is honored) return false; } @Override public String toString() { return "onDone at endpoint: " + endpoint; } }; } private void doPublish(Exchange exchange) { LOG.trace("Publishing Exchange to disruptor ringbuffer: {}", exchange); try { if (blockWhenFull) { endpoint.publish(exchange); } else { endpoint.tryPublish(exchange); } } catch (DisruptorNotStartedException e) { throw new IllegalStateException("Disruptor was not started", e); } catch (InsufficientCapacityException e) { throw new IllegalStateException("Disruptors ringbuffer was full", e); } } private Exchange prepareCopy(final Exchange exchange, final boolean copy) throws IOException { // use a new copy of the exchange to route async final Exchange target = ExchangeHelper.createCorrelatedCopy(exchange, copy); // set a new from endpoint to be the disruptor target.getExchangeExtension().setFromEndpoint(endpoint); if (copy) { // if the body is stream caching based we need to make a deep copy if (target.getMessage().getBody() instanceof StreamCache sc) { StreamCache newBody = sc.copy(target); if (newBody != null) { target.getMessage().setBody(newBody); } } } return target; } }
DisruptorProducer
java
google__guice
core/test/com/google/inject/CircularDependencyTest.java
{ "start": 5321, "end": 5378 }
interface ____ { A getA(); int id(); } static
B
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/convert/EnumConverter.java
{ "start": 1038, "end": 1110 }
enum ____ to parse. * @since 2.1 moved from TypeConverters */ public
class
java
micronaut-projects__micronaut-core
http-netty/src/main/java/io/micronaut/http/netty/channel/loom/EventLoopVirtualThreadScheduler.java
{ "start": 1202, "end": 2703 }
interface ____ permits LoomCarrierGroup.IoScheduler, LoomCarrierGroup.Runner, LoomCarrierGroup.StickyScheduler { /** * Get a shared {@link AttributeMap} for this scheduler. * * @return The attribute map */ @NonNull AttributeMap attributeMap(); /** * Get the event loop that runs on this scheduler. * * @return The event loop */ @NonNull EventExecutor eventLoop(); /** * Get the virtual thread scheduler of the current thread, if available. * * @return The current scheduler or {@code null} */ @Nullable static EventLoopVirtualThreadScheduler current() { if (LoomBranchSupport.isSupported()) { if (!LoomSupport.isVirtual(Thread.currentThread())) { return null; } if (LoomBranchSupport.currentScheduler() instanceof EventLoopVirtualThreadScheduler elvts) { return elvts; } else { return null; } } else if (PrivateLoomSupport.isSupported()) { Thread thread = Thread.currentThread(); if (!LoomSupport.isVirtual(thread)) { return null; } if (PrivateLoomSupport.getScheduler(thread) instanceof EventLoopVirtualThreadScheduler elvts) { return elvts; } else { return null; } } else { return null; } } }
EventLoopVirtualThreadScheduler
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng6511OptionalProjectSelectionTest.java
{ "start": 1156, "end": 5023 }
class ____ extends AbstractMavenIntegrationTestCase { private static final String RESOURCE_PATH = "/mng-6511-optional-project-selection"; private final File testDir; public MavenITmng6511OptionalProjectSelectionTest() throws IOException { super(); testDir = extractResources(RESOURCE_PATH); } @Test public void testSelectExistingOptionalProfile() throws VerificationException { Verifier cleaner = newVerifier(testDir.getAbsolutePath()); cleaner.addCliArgument("clean"); cleaner.execute(); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setLogFileName("log-select-existing.txt"); verifier.addCliArgument("-pl"); verifier.addCliArgument("?existing-module"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyFilePresent("existing-module/target/touch.txt"); // existing-module should have been built. } @Test public void testSelectExistingOptionalProfileByArtifactId() throws VerificationException { Verifier cleaner = newVerifier(testDir.getAbsolutePath()); cleaner.addCliArgument("clean"); cleaner.execute(); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setLogFileName("log-select-existing-artifact-id.txt"); verifier.addCliArgument("-pl"); verifier.addCliArgument("?:existing-module"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyFilePresent("existing-module/target/touch.txt"); // existing-module should have been built. } @Test public void testSelectNonExistingOptionalProfile() throws VerificationException { Verifier cleaner = newVerifier(testDir.getAbsolutePath()); cleaner.addCliArgument("clean"); cleaner.execute(); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setLogFileName("log-select-non-existing.txt"); verifier.addCliArgument("-pl"); verifier.addCliArgument("?non-existing-module"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyFilePresent("existing-module/target/touch.txt"); // existing-module should have been built. } @Test public void testDeselectExistingOptionalProfile() throws VerificationException { Verifier cleaner = newVerifier(testDir.getAbsolutePath()); cleaner.addCliArgument("clean"); cleaner.execute(); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setLogFileName("log-deselect-existing.txt"); verifier.addCliArgument("-pl"); verifier.addCliArgument("!?existing-module"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyFileNotPresent( "existing-module/target/touch.txt"); // existing-module should not have been built. } @Test public void testDeselectNonExistingOptionalProfile() throws VerificationException { Verifier cleaner = newVerifier(testDir.getAbsolutePath()); cleaner.addCliArgument("clean"); cleaner.execute(); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setLogFileName("log-deselect-non-existing.txt"); verifier.addCliArgument("-pl"); verifier.addCliArgument("!?non-existing-module"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyFilePresent("existing-module/target/touch.txt"); // existing-module should have been built. } }
MavenITmng6511OptionalProjectSelectionTest
java
quarkusio__quarkus
extensions/grpc/deployment/src/test/java/io/quarkus/grpc/server/interceptors/GlobalAndServiceInterceptorsTest.java
{ "start": 5735, "end": 6151 }
class ____ implements ServerInterceptor { static boolean invoked; @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { invoked = true; return next.startCall(call, headers); } } @ApplicationScoped public static
ServiceBInterceptor
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AuditedPropertiesReader.java
{ "start": 16160, "end": 18191 }
class ____.forEachField( (i, field) -> addFromProperty( field, it -> "field", fieldAccessedPersistentProperties, allClassAudited ) ); classDetails.forEachMethod( (i, method) -> addFromProperty( method, propertyAccessedPersistentProperties::get, propertyAccessedPersistentProperties.keySet(), allClassAudited ) ); if ( isClassHierarchyTraversalNeeded( allClassAudited ) ) { final ClassDetails superclass = classDetails.getSuperClass(); if ( !classDetails.isInterface() && !"java.lang.Object".equals( superclass.getName() ) ) { addPropertiesFromClass( superclass ); } } } protected boolean isClassHierarchyTraversalNeeded(Audited allClassAudited) { return allClassAudited != null || !auditedPropertiesHolder.isEmpty(); } private void addFromProperty( MemberDetails memberDetails, Function<String, String> accessTypeProvider, Set<String> persistentProperties, Audited allClassAudited) { if ( !memberDetails.isPersistable() || memberDetails.hasDirectAnnotationUsage( Transient.class ) ) { return; } final String attributeName = memberDetails.resolveAttributeName(); final String accessType = accessTypeProvider.apply( attributeName ); // If this is not a persistent property, with the same access type as currently checked, // it's not audited as well. // If the property was already defined by the subclass, is ignored by superclasses if ( persistentProperties.contains( attributeName ) && !auditedPropertiesHolder.contains( attributeName ) ) { final Value propertyValue = persistentPropertiesSource.getProperty( attributeName ).getValue(); if ( propertyValue instanceof Component ) { this.addFromComponentProperty( memberDetails, accessType, (Component) propertyValue, allClassAudited ); } else { this.addFromNotComponentProperty( memberDetails, accessType, allClassAudited ); } } else if ( propertiesGroupMapping.containsKey( attributeName ) ) { // Retrieve embedded component name based on
classDetails
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/openshiftai/action/OpenShiftAiActionVisitor.java
{ "start": 824, "end": 928 }
interface ____ methods to create actions for embeddings, reranking and completion models. */ public
defines
java
alibaba__nacos
plugin/control/src/main/java/com/alibaba/nacos/plugin/control/rule/parser/NacosTpsControlRuleParser.java
{ "start": 932, "end": 1232 }
class ____ implements TpsControlRuleParser { @Override public TpsControlRule parseRule(String ruleContent) { return StringUtils.isBlank(ruleContent) ? new TpsControlRule() : JacksonUtils.toObj(ruleContent, TpsControlRule.class); } }
NacosTpsControlRuleParser
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/query/functionscore/ScoreFunctionBuilderTests.java
{ "start": 1192, "end": 5503 }
class ____ extends ESTestCase { public void testIllegalArguments() { expectThrows(IllegalArgumentException.class, () -> new RandomScoreFunctionBuilder().seed(null)); expectThrows(IllegalArgumentException.class, () -> new ScriptScoreFunctionBuilder((Script) null)); expectThrows(IllegalArgumentException.class, () -> new FieldValueFactorFunctionBuilder((String) null)); expectThrows(IllegalArgumentException.class, () -> new FieldValueFactorFunctionBuilder("").modifier(null)); expectThrows(IllegalArgumentException.class, () -> new GaussDecayFunctionBuilder(null, "", "", "")); expectThrows(IllegalArgumentException.class, () -> new GaussDecayFunctionBuilder("", "", null, "")); expectThrows(IllegalArgumentException.class, () -> new GaussDecayFunctionBuilder("", "", null, "", randomDouble())); expectThrows(IllegalArgumentException.class, () -> new LinearDecayFunctionBuilder(null, "", "", "")); expectThrows(IllegalArgumentException.class, () -> new LinearDecayFunctionBuilder("", "", null, "")); expectThrows(IllegalArgumentException.class, () -> new LinearDecayFunctionBuilder("", "", null, "", randomDouble())); expectThrows(IllegalArgumentException.class, () -> new ExponentialDecayFunctionBuilder(null, "", "", "")); expectThrows(IllegalArgumentException.class, () -> new ExponentialDecayFunctionBuilder("", "", null, "")); expectThrows(IllegalArgumentException.class, () -> new ExponentialDecayFunctionBuilder("", "", null, "", randomDouble())); } public void testDecayValues() { expectThrows(IllegalStateException.class, () -> new ExponentialDecayFunctionBuilder("", "", "", "", 0.0)); expectThrows(IllegalStateException.class, () -> new ExponentialDecayFunctionBuilder("", "", "", "", 1.0)); expectThrows(IllegalStateException.class, () -> new GaussDecayFunctionBuilder("", "", "", "", 0.0)); expectThrows(IllegalStateException.class, () -> new GaussDecayFunctionBuilder("", "", "", "", 1.0)); expectThrows(IllegalStateException.class, () -> new LinearDecayFunctionBuilder("", "", "", "", 1.0)); expectThrows(IllegalStateException.class, () -> new LinearDecayFunctionBuilder("", "", "", "", -1.0)); // should not throw since the score formula allows it new LinearDecayFunctionBuilder("", "", "", "", 0.0); } public void testRandomScoreFunctionWithSeedNoField() throws Exception { RandomScoreFunctionBuilder builder = new RandomScoreFunctionBuilder(); builder.seed(42); SearchExecutionContext context = Mockito.mock(SearchExecutionContext.class); IndexSettings settings = new IndexSettings( IndexMetadata.builder("index").settings(indexSettings(IndexVersion.current(), 1, 1)).build(), Settings.EMPTY ); Mockito.when(context.index()).thenReturn(settings.getIndex()); Mockito.when(context.getShardId()).thenReturn(0); Mockito.when(context.getIndexSettings()).thenReturn(settings); Mockito.when(context.getFieldType(IdFieldMapper.NAME)).thenReturn(new KeywordFieldMapper.KeywordFieldType(IdFieldMapper.NAME)); Mockito.when(context.isFieldMapped(IdFieldMapper.NAME)).thenReturn(true); builder.toFunction(context); } public void testRandomScoreFunctionWithSeed() throws Exception { RandomScoreFunctionBuilder builder = new RandomScoreFunctionBuilder(); builder.setField("foo"); builder.seed(42); SearchExecutionContext context = Mockito.mock(SearchExecutionContext.class); IndexSettings settings = new IndexSettings( IndexMetadata.builder("index").settings(indexSettings(IndexVersion.current(), 1, 1)).build(), Settings.EMPTY ); Mockito.when(context.index()).thenReturn(settings.getIndex()); Mockito.when(context.getShardId()).thenReturn(0); Mockito.when(context.getIndexSettings()).thenReturn(settings); MappedFieldType ft = new NumberFieldMapper.NumberFieldType("foo", NumberType.LONG); Mockito.when(context.getFieldType("foo")).thenReturn(ft); Mockito.when(context.isFieldMapped("foo")).thenReturn(true); builder.toFunction(context); } }
ScoreFunctionBuilderTests
java
apache__flink
flink-formats/flink-avro/src/main/java/org/apache/flink/formats/avro/utils/AvroKryoSerializerUtils.java
{ "start": 4087, "end": 5197 }
interface ____ AvroUtils return new AvroTypeInfo(type); } static <T> byte[] avroSerializeToBytes(Schema schema, T o) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null); DatumWriter<T> datumWriter = new GenericDatumWriter<>(schema); datumWriter.write(o, encoder); encoder.flush(); return out.toByteArray(); } static <T> T avroDeserializeFromBytes(Schema schema, byte[] bytes) throws IOException { try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) { BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(in, null); DatumReader<T> datumReader = new GenericDatumReader<>(schema); return datumReader.read(null, decoder); } } /** * Slow serialization approach for Avro schemas. This is only used with {{@link * org.apache.avro.generic.GenericData.Record}} types. Having this serializer, we are able to * handle avro Records. */ public static
of
java
google__dagger
javatests/dagger/functional/assisted/AssistedFactoryBindsTest.java
{ "start": 1032, "end": 1114 }
class ____ { @Component(modules = FooFactoryModule.class)
AssistedFactoryBindsTest
java
apache__dubbo
dubbo-plugin/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java
{ "start": 2100, "end": 2680 }
class ____, cause: test")); given(invoker.invoke(invocation)).willReturn(new AppResponse("success")); given(invoker.getUrl()).willReturn(url); given(invocation.getMethodName()).willReturn("echo1"); given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class}); given(invocation.getArguments()).willReturn(new Object[] {"arg1"}); validationFilter.setValidation(validation); Result result = validationFilter.invoke(invoker, invocation); assertThat(result.getException().getMessage(), is("Not found
test
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/JUnit4ClassUsedInJUnit3.java
{ "start": 2723, "end": 3406 }
class ____ annotation should not appear. if (isType("org.junit.Ignore").matches(tree, state)) { return makeDescription("@Ignore", tree); } if (isType("org.junit.Rule").matches(tree, state)) { return makeDescription("@Rule", tree); } return NO_MATCH; } /** * Returns a {@link Description} of the error based on the rejected JUnit4 construct in the JUnit3 * class. */ private Description makeDescription(String rejectedJUnit4, Tree tree) { Description.Builder builder = buildDescription(tree) .setMessage( String.format( "%s cannot be used inside a JUnit3 class. Convert your
some
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/VariableAware.java
{ "start": 909, "end": 1641 }
interface ____ { /** * Returns a variable by name. * * If the variable is of type {@link org.apache.camel.StreamCache} then the repository should ensure to reset the * stream cache before returning the value, to ensure the content can be read by the Camel end user and would be * re-readable next time. * * @param name the name of the variable * @return the value of the given variable or <tt>null</tt> if there is no variable for the given name */ Object getVariable(String name); /** * Sets a variable * * @param name of the variable * @param value the value of the variable */ void setVariable(String name, Object value); }
VariableAware
java
apache__camel
components/camel-aws/camel-aws-xray/src/test/java/org/apache/camel/component/aws/xray/SpringAwsXRaySimpleRouteTest.java
{ "start": 1525, "end": 3697 }
class ____ extends CamelSpringTestSupport { protected FakeAWSDaemon socketListener = new FakeAWSDaemon(); @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/aws/xray/AwsXRaySimpleRouteTest.xml"); } @Override public void setupResources() { socketListener.before(); } @Override public void cleanupResources() { socketListener.after(); } @Test public void testRoute() throws Exception { NotifyBuilder notify = new NotifyBuilder(context).whenDone(5).create(); for (int i = 0; i < 5; i++) { template.sendBody("seda:dude", "Hello World"); } assertThat("Not all exchanges were fully processed", notify.matches(30, TimeUnit.SECONDS), is(equalTo(true))); List<TestTrace> testData = Arrays.asList( TestDataBuilder.createTrace() .withSegment(TestDataBuilder.createSegment("dude")) .withSegment(TestDataBuilder.createSegment("car")), TestDataBuilder.createTrace() .withSegment(TestDataBuilder.createSegment("dude")) .withSegment(TestDataBuilder.createSegment("car")), TestDataBuilder.createTrace() .withSegment(TestDataBuilder.createSegment("dude")) .withSegment(TestDataBuilder.createSegment("car")), TestDataBuilder.createTrace() .withSegment(TestDataBuilder.createSegment("dude")) .withSegment(TestDataBuilder.createSegment("car")), TestDataBuilder.createTrace() .withSegment(TestDataBuilder.createSegment("dude")) .withSegment(TestDataBuilder.createSegment("car"))); Map<String, TestTrace> receivedData = await().atMost(2, TimeUnit.SECONDS) .until(socketListener::getReceivedData, v -> v.size() == testData.size()); TestUtils.checkData(receivedData, testData); } }
SpringAwsXRaySimpleRouteTest
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/time/DateFormatUtilsTest.java
{ "start": 1586, "end": 11173 }
class ____ extends AbstractLangTest { private void assertFormats(final String expectedValue, final String pattern, final TimeZone timeZone, final Calendar cal) { assertEquals(expectedValue, DateFormatUtils.format(cal.getTime(), pattern, timeZone)); assertEquals(expectedValue, DateFormatUtils.format(cal.getTime().getTime(), pattern, timeZone)); assertEquals(expectedValue, DateFormatUtils.format(cal, pattern, timeZone)); } private Calendar createFebruaryTestDate(final TimeZone timeZone) { final Calendar cal = Calendar.getInstance(timeZone); cal.set(2002, Calendar.FEBRUARY, 23, 9, 11, 12); return cal; } private Calendar createJuneTestDate(final TimeZone timeZone) { final Calendar cal = Calendar.getInstance(timeZone); cal.set(2003, Calendar.JUNE, 8, 10, 11, 12); return cal; } @Test void testConstructor() { assertNotNull(new DateFormatUtils()); final Constructor<?>[] cons = DateFormatUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(DateFormatUtils.class.getModifiers())); assertFalse(Modifier.isFinal(DateFormatUtils.class.getModifiers())); } @Test void testDateISO() { testGmtMinus3("2002-02-23", DateFormatUtils.ISO_DATE_FORMAT.getPattern()); testGmtMinus3("2002-02-23-03:00", DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.getPattern()); testUTC("2002-02-23Z", DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.getPattern()); } @Test void testDateTimeISO() { testGmtMinus3("2002-02-23T09:11:12", DateFormatUtils.ISO_DATETIME_FORMAT.getPattern()); testGmtMinus3("2002-02-23T09:11:12-03:00", DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()); testUTC("2002-02-23T09:11:12Z", DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()); } @Test void testFormat() { final Calendar c = Calendar.getInstance(FastTimeZone.getGmtTimeZone()); c.set(2005, Calendar.JANUARY, 1, 12, 0, 0); c.setTimeZone(TimeZone.getDefault()); final StringBuilder buffer = new StringBuilder (); final int year = c.get(Calendar.YEAR); final int month = c.get(Calendar.MONTH) + 1; final int day = c.get(Calendar.DAY_OF_MONTH); final int hour = c.get(Calendar.HOUR_OF_DAY); buffer.append (year); buffer.append(month); buffer.append(day); buffer.append(hour); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH")); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime().getTime(), "yyyyMdH")); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH", Locale.US)); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime().getTime(), "yyyyMdH", Locale.US)); } @Test void testFormatCalendar() { final Calendar c = Calendar.getInstance(FastTimeZone.getGmtTimeZone()); c.set(2005, Calendar.JANUARY, 1, 12, 0, 0); c.setTimeZone(TimeZone.getDefault()); final StringBuilder buffer = new StringBuilder (); final int year = c.get(Calendar.YEAR); final int month = c.get(Calendar.MONTH) + 1; final int day = c.get(Calendar.DAY_OF_MONTH); final int hour = c.get(Calendar.HOUR_OF_DAY); buffer.append (year); buffer.append(month); buffer.append(day); buffer.append(hour); assertEquals(buffer.toString(), DateFormatUtils.format(c, "yyyyMdH")); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH")); assertEquals(buffer.toString(), DateFormatUtils.format(c, "yyyyMdH", Locale.US)); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH", Locale.US)); } @Test void testFormatUTC() { final Calendar c = Calendar.getInstance(FastTimeZone.getGmtTimeZone()); c.set(2005, Calendar.JANUARY, 1, 12, 0, 0); assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern())); assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime().getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern())); assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern(), Locale.US)); assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime().getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern(), Locale.US)); } private void testGmtMinus3(final String expectedValue, final String pattern) { final TimeZone timeZone = TimeZones.getTimeZone("GMT-3"); assertFormats(expectedValue, pattern, timeZone, createFebruaryTestDate(timeZone)); } @Test void testLANG1000() throws Exception { final String date = "2013-11-18T12:48:05Z"; DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(date); } @Test void testLANG1462() { final TimeZone timeZone = TimeZones.getTimeZone("GMT-3"); final Calendar calendar = createJuneTestDate(timeZone); assertEquals("20030608101112", DateFormatUtils.format(calendar, "yyyyMMddHHmmss")); calendar.setTimeZone(TimeZones.getTimeZone("JST")); assertEquals("20030608221112", DateFormatUtils.format(calendar, "yyyyMMddHHmmss")); } @DefaultTimeZone("UTC") @Test void testLang530() throws ParseException { final Date d = new Date(); final String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d); final Date d2 = DateUtils.parseDate(isoDateStr, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()); // the format loses milliseconds so have to reintroduce them assertEquals(d.getTime(), d2.getTime() + d.getTime() % 1000, "Date not equal to itself ISO formatted and parsed"); } /** * According to LANG-916 (https://issues.apache.org/jira/browse/LANG-916), * the format method did contain a bug: it did not use the TimeZone data. * * This method test that the bug is fixed. */ @Test void testLang916() { final Calendar cal = Calendar.getInstance(TimeZones.getTimeZone("Europe/Paris")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); // Long. { final String value = DateFormatUtils.format(cal.getTimeInMillis(), DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern(), TimeZones.getTimeZone("Europe/Paris")); assertEquals("2009-10-16T08:42:16+02:00", value, "long"); } { final String value = DateFormatUtils.format(cal.getTimeInMillis(), DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern(), TimeZones.getTimeZone("Asia/Kolkata")); assertEquals("2009-10-16T12:12:16+05:30", value, "long"); } { final String value = DateFormatUtils.format(cal.getTimeInMillis(), DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern(), TimeZones.getTimeZone("Europe/London")); assertEquals("2009-10-16T07:42:16+01:00", value, "long"); } // Calendar. { final String value = DateFormatUtils.format(cal, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern(), TimeZones.getTimeZone("Europe/Paris")); assertEquals("2009-10-16T08:42:16+02:00", value, "calendar"); } { final String value = DateFormatUtils.format(cal, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern(), TimeZones.getTimeZone("Asia/Kolkata")); assertEquals("2009-10-16T12:12:16+05:30", value, "calendar"); } { final String value = DateFormatUtils.format(cal, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern(), TimeZones.getTimeZone("Europe/London")); assertEquals("2009-10-16T07:42:16+01:00", value, "calendar"); } } @DefaultLocale(language = "en") @Test void testSMTP() { TimeZone timeZone = TimeZones.getTimeZone("GMT-3"); Calendar june = createJuneTestDate(timeZone); assertFormats("Sun, 08 Jun 2003 10:11:12 -0300", DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(), timeZone, june); timeZone = FastTimeZone.getGmtTimeZone(); june = createJuneTestDate(timeZone); assertFormats("Sun, 08 Jun 2003 10:11:12 +0000", DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(), timeZone, june); } @Test void testTimeISO() { testGmtMinus3("T09:11:12", DateFormatUtils.ISO_TIME_FORMAT.getPattern()); testGmtMinus3("T09:11:12-03:00", DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT.getPattern()); testUTC("T09:11:12Z", DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT.getPattern()); } @Test void testTimeNoTISO() { testGmtMinus3("09:11:12", DateFormatUtils.ISO_TIME_NO_T_FORMAT.getPattern()); testGmtMinus3("09:11:12-03:00", DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.getPattern()); testUTC("09:11:12Z", DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.getPattern()); } private void testUTC(final String expectedValue, final String pattern) { final TimeZone timeZone = FastTimeZone.getGmtTimeZone(); assertFormats(expectedValue, pattern, timeZone, createFebruaryTestDate(timeZone)); } }
DateFormatUtilsTest
java
apache__maven
compat/maven-compat/src/main/java/org/apache/maven/project/artifact/MavenMetadataCache.java
{ "start": 1092, "end": 1583 }
interface ____ { ResolutionGroup get( Artifact artifact, boolean resolveManagedVersions, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories); void put( Artifact artifact, boolean resolveManagedVersions, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories, ResolutionGroup result); void flush(); }
MavenMetadataCache
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/ValueBindJpaCriteriaParameter.java
{ "start": 679, "end": 3018 }
class ____<T> extends JpaCriteriaParameter<T> { private final @Nullable T value; public ValueBindJpaCriteriaParameter(@Nullable BindableType<? super T> type, @Nullable T value, NodeBuilder nodeBuilder) { super( null, type, false, nodeBuilder ); assert value == null || type == null || ( type instanceof SqmBindableType<? super T> bindable // TODO: why does SqmExpressible.getJavaType() return an apparently-wrong type? ? bindable.getExpressibleJavaType().isInstance( value ) : type.getJavaType().isInstance( value ) ); this.value = value; } private ValueBindJpaCriteriaParameter(ValueBindJpaCriteriaParameter<T> original) { super( original ); this.value = original.value; } @Override public ValueBindJpaCriteriaParameter<T> copy(SqmCopyContext context) { final ValueBindJpaCriteriaParameter<T> existing = context.getCopy( this ); return existing != null ? existing : context.registerCopy( this, new ValueBindJpaCriteriaParameter<>( this ) ); } public @Nullable T getValue() { return value; } @Override public void appendHqlString(StringBuilder hql, SqmRenderContext context) { SqmLiteral.appendHqlString( hql, getJavaTypeDescriptor(), value ); } // For caching purposes, any two ValueBindJpaCriteriaParameter objects are compatible as ensured by the parent impl, // but for equals/hashCode, use equals/hashCode of the underlying value, if available, from the nodes JavaType @Override public final boolean equals(@Nullable Object o) { if ( this == o ) { return true; } if ( o instanceof ValueBindJpaCriteriaParameter<?> that ) { if ( value == null ) { return that.value == null && Objects.equals( getNodeType(), that.getNodeType() ); } final var javaType = getJavaTypeDescriptor(); if ( that.value != null ) { if ( javaType != null ) { //noinspection unchecked return javaType.equals( that.getJavaTypeDescriptor() ) && javaType.areEqual( value, (T) that.value ); } else { return that.getJavaTypeDescriptor() == null && value.equals( that.value ); } } } return false; } @Override public int hashCode() { if ( value == null ) { return 0; } final var javaType = getJavaTypeDescriptor(); return javaType == null ? value.hashCode() : javaType.extractHashCode( value ); } }
ValueBindJpaCriteriaParameter
java
apache__camel
components/camel-aws/camel-aws-xray/src/test/java/org/apache/camel/component/aws/xray/TwoServiceWithExcludeTest.java
{ "start": 1262, "end": 2692 }
class ____ extends CamelAwsXRayTestSupport { public TwoServiceWithExcludeTest() { super( TestDataBuilder.createTrace().inRandomOrder() .withSegment(TestDataBuilder.createSegment("ServiceA") .withSubsegment(TestDataBuilder.createSubsegment("direct:ServiceB")))); } @Override protected Set<String> getExcludePatterns() { return Collections.singleton("ServiceB"); } @Test public void testRoute() { NotifyBuilder notify = new NotifyBuilder(context).whenDone(1).create(); template.requestBody("direct:ServiceA", "Hello"); assertThat("Not all exchanges were fully processed", notify.matches(10, TimeUnit.SECONDS), is(equalTo(true))); verify(); } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:ServiceA").routeId("ServiceA") .log("ServiceA has been called") .delay(simple("${random(1000,2000)}")) .to("direct:ServiceB"); from("direct:ServiceB").routeId("ServiceB") .log("ServiceB has been called") .delay(simple("${random(0,500)}")); } }; } }
TwoServiceWithExcludeTest
java
apache__flink
flink-formats/flink-csv/src/main/java/org/apache/flink/formats/csv/CsvRowSchemaConverter.java
{ "start": 2219, "end": 2383 }
class ____ to be kept in sync with the corresponding runtime classes * {@link CsvRowDeserializationSchema} and {@link CsvRowSerializationSchema}. */ public final
need
java
apache__camel
components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/integration/CustomSerializerIT.java
{ "start": 2817, "end": 3148 }
class ____ implements GooglePubsubSerializer { @Override public byte[] serialize(Object payload) { // Append 'custom serialized' to the payload String serialized = payload + " custom serialized"; return serialized.getBytes(StandardCharsets.UTF_8); } } }
CustomSerializer
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/main/java/io/quarkus/opentelemetry/deployment/scheduler/OpenTelemetrySchedulerProcessor.java
{ "start": 482, "end": 854 }
class ____ { @BuildStep(onlyIf = OpenTelemetryEnabled.class) void registerJobInstrumenter(Capabilities capabilities, BuildProducer<AdditionalBeanBuildItem> beans) { if (capabilities.isPresent(Capability.SCHEDULER)) { beans.produce(new AdditionalBeanBuildItem(OpenTelemetryJobInstrumenter.class)); } } }
OpenTelemetrySchedulerProcessor
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/jmx/support/JmxUtils.java
{ "start": 9076, "end": 9297 }
class ____ expose * @see org.springframework.util.ClassUtils#getUserClass(Object) */ public static Class<?> getClassToExpose(Object managedBean) { return ClassUtils.getUserClass(managedBean); } /** * Return the
to
java
spring-projects__spring-boot
module/spring-boot-r2dbc/src/main/java/org/springframework/boot/r2dbc/autoconfigure/ProxyConnectionFactoryCustomizer.java
{ "start": 752, "end": 890 }
interface ____ can be used to customize a {@link Builder}. * * @author Tadaya Tsuyukubo * @since 4.0.0 */ @FunctionalInterface public
that
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/StatelessQueryScrollingTest.java
{ "start": 6862, "end": 7692 }
class ____ { @Id private Integer id; private String name; @OneToMany(mappedBy = "vendor", fetch = FetchType.LAZY) private Set<Product> products = new HashSet<>(); public Vendor() { } public Vendor(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Product> getProducts() { return products; } public void setProducts(Set<Product> products) { this.products = products; } } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Entity fetch scrolling @Entity(name = "Resource") @Table(name = "resources") public static
Vendor
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppender2767Test.java
{ "start": 1380, "end": 2478 }
class ____ { private static final String CONFIG = "log4j-routing-2767.xml"; private static final String ACTIVITY_LOG_FILE = "target/routing1/routingtest-Service.log"; private final LoggerContextRule loggerContextRule = new LoggerContextRule(CONFIG); @Rule public RuleChain rules = loggerContextRule.withCleanFilesRule(ACTIVITY_LOG_FILE); @Before public void setUp() {} @After public void tearDown() { this.loggerContextRule.getLoggerContext().stop(); } @Test public void routingTest() throws Exception { final StructuredDataMessage msg = new StructuredDataMessage("Test", "This is a test", "Service"); EventLogger.logEvent(msg); final File file = new File(ACTIVITY_LOG_FILE); assertTrue("Activity file was not created", file.exists()); final List<String> lines = Files.lines(file.toPath()).collect(Collectors.toList()); assertEquals("Incorrect number of lines", 1, lines.size()); assertTrue("Incorrect content", lines.get(0).contains("This is a test")); } }
RoutingAppender2767Test
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedClassIntegrationTests.java
{ "start": 56127, "end": 56419 }
class ____ { @Parameter(0) int i; @Parameter(1) String s; @org.junit.jupiter.api.Test void test() { fail("should not be called"); } } @ParameterizedClass @CsvSource({ "unused1, foo, unused2, bar", "unused4, baz, unused5, qux" }) static
NotEnoughArgumentsForFieldsTestCase
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/path/RestApplicationPathTestCase.java
{ "start": 341, "end": 1201 }
class ____ { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .withConfigurationResource("empty.properties") .overrideConfigKey("quarkus.rest.path", "/foo") .overrideConfigKey("quarkus.http.root-path", "/app") .withApplicationRoot((jar) -> jar .addClasses(HelloResource.class, BarApp.class, BaseApplication.class)); /** * Using @ApplicationPath will overlay/replace `quarkus.rest.path`. * Per spec: * <quote> * Identifies the application path that serves as the base URI for all resource * URIs provided by Path. May only be applied to a subclass of Application. * </quote> * * This path will also be relative to the configured HTTP root */ @ApplicationPath("/bar") public static
RestApplicationPathTestCase
java
apache__hadoop
hadoop-tools/hadoop-aliyun/src/main/java/org/apache/hadoop/fs/aliyun/oss/OSSDataBlocks.java
{ "start": 13620, "end": 14104 }
class ____ extends MemoryBlockFactory { ArrayBlockFactory(AliyunOSSFileSystem owner) { super(owner); } @Override DataBlock create(long index, int limit, BlockOutputStreamStatistics statistics) throws IOException { try { return new ByteArrayBlock(index, limit, statistics); } catch (MemoryLimitException e) { LOG.debug(e.getMessage() + ", index " + index); return null; } } static
ArrayBlockFactory
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/string/EndsWithTests.java
{ "start": 1009, "end": 4484 }
class ____ extends AbstractScalarFunctionTestCase { public EndsWithTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) { this.testCase = testCaseSupplier.get(); } @ParametersFactory public static Iterable<Object[]> parameters() { List<TestCaseSupplier> suppliers = new LinkedList<>(); for (DataType strType : DataType.stringTypes()) { for (DataType suffixType : DataType.stringTypes()) { suppliers.add( new TestCaseSupplier( "<" + strType + ">, empty <" + suffixType + ">", List.of(strType, suffixType), () -> testCase(strType, suffixType, randomAlphaOfLength(5), "", equalTo(true)) ) ); suppliers.add( new TestCaseSupplier( "empty <" + strType + ">, <" + suffixType + ">", List.of(strType, suffixType), () -> testCase(strType, suffixType, "", randomAlphaOfLength(5), equalTo(false)) ) ); suppliers.add( new TestCaseSupplier("<" + strType + ">, one char <" + suffixType + "> matches", List.of(strType, suffixType), () -> { String str = randomAlphaOfLength(5); String suffix = randomAlphaOfLength(1); str = str + suffix; return testCase(strType, suffixType, str, suffix, equalTo(true)); }) ); suppliers.add( new TestCaseSupplier("<" + strType + ">, one char <" + suffixType + "> differs", List.of(strType, suffixType), () -> { String str = randomAlphaOfLength(5); String suffix = randomAlphaOfLength(1); str = str + randomValueOtherThan(suffix, () -> randomAlphaOfLength(1)); return testCase(strType, suffixType, str, suffix, equalTo(false)); }) ); suppliers.add( new TestCaseSupplier("random <" + strType + ">, random <" + suffixType + ">", List.of(strType, suffixType), () -> { String str = randomAlphaOfLength(5); String suffix = randomAlphaOfLength(3); return testCase(strType, suffixType, str, suffix, equalTo(str.endsWith(suffix))); }) ); } } return parameterSuppliersFromTypedDataWithDefaultChecks(true, suppliers); } private static TestCaseSupplier.TestCase testCase( DataType strType, DataType suffixType, String str, String suffix, Matcher<Boolean> matcher ) { return new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(new BytesRef(str), strType, "str"), new TestCaseSupplier.TypedData(new BytesRef(suffix), suffixType, "suffix") ), "EndsWithEvaluator[str=Attribute[channel=0], suffix=Attribute[channel=1]]", DataType.BOOLEAN, matcher ); } @Override protected Expression build(Source source, List<Expression> args) { return new EndsWith(source, args.get(0), args.get(1)); } }
EndsWithTests
java
apache__camel
components/camel-platform-http/src/test/java/org/apache/camel/component/platform/http/PlatformHttpConsumesPlusSignTest.java
{ "start": 1067, "end": 2480 }
class ____ extends AbstractPlatformHttpTest { @Test void testConsumesPlusSign() { given() .header("Accept", "application/fhir+json") .header("User-Agent", "User-Agent-Camel") .port(port) .expect() .statusCode(200) .header("Accept", (String) null) .header("User-Agent", (String) null) .when() .get("/get"); PlatformHttpEndpoint phe = (PlatformHttpEndpoint) getContext().getEndpoints().iterator().next(); Assertions.assertEquals("application/fhir+json,text/plain", phe.getConsumes()); } @Override protected RouteBuilder routes() { return new RouteBuilder() { @Override public void configure() { from("platform-http:/get?consumes=application/fhir+json, text/plain") .process(e -> { Assertions.assertEquals("application/fhir+json", e.getMessage().getHeader("Accept")); Assertions.assertEquals("User-Agent-Camel", e.getMessage().getHeader("User-Agent")); Assertions.assertNull(e.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)); }) .setBody().constant(""); } }; } }
PlatformHttpConsumesPlusSignTest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-links/deployment/src/test/java/io/quarkus/resteasy/reactive/links/deployment/TestRecordWithPersistenceIdAndRestLinkId.java
{ "start": 187, "end": 1095 }
class ____ { @RestLinkId private int restLinkId; @Id private int persistenceId; private String name; public TestRecordWithPersistenceIdAndRestLinkId() { } public TestRecordWithPersistenceIdAndRestLinkId(int restLinkId, int persistenceId, String name) { this.restLinkId = restLinkId; this.persistenceId = persistenceId; this.name = name; } public int getRestLinkId() { return restLinkId; } public void setRestLinkId(int restLinkId) { this.restLinkId = restLinkId; } public int getPersistenceId() { return persistenceId; } public void setPersistenceId(int persistenceId) { this.persistenceId = persistenceId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
TestRecordWithPersistenceIdAndRestLinkId
java
mockito__mockito
mockito-integration-tests/extensions-tests/src/test/java/org/mockitousage/plugins/switcher/MyMockMaker.java
{ "start": 336, "end": 1100 }
class ____ extends SubclassByteBuddyMockMaker { static ThreadLocal<Object> explosive = new ThreadLocal<Object>(); public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) { if (explosive.get() != null) { throw new RuntimeException(MyMockMaker.class.getName()); } return super.createMock(settings, handler); } public MockHandler getHandler(Object mock) { return super.getHandler(mock); } public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) { super.resetMock(mock, newHandler, settings); } @Override public TypeMockability isTypeMockable(Class<?> type) { return super.isTypeMockable(type); } }
MyMockMaker
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/diskbalancer/TestDiskBalancerWithMockMover.java
{ "start": 14928, "end": 16062 }
class ____ { private DiskBalancer balancer; private NodePlan plan; private TestMover blockMover; public DiskBalancer getBalancer() { return balancer; } public NodePlan getPlan() { return plan; } public TestMover getBlockMover() { return blockMover; } public MockMoverHelper invoke() throws Exception { Configuration conf = new HdfsConfiguration(); conf.setBoolean(DFSConfigKeys.DFS_DISK_BALANCER_ENABLED, true); restartDataNode(); blockMover = new TestMover(dataNode.getFSDataset()); blockMover.setRunnable(); balancer = new DiskBalancerBuilder(conf) .setMover(blockMover) .setNodeID(nodeID) .build(); DiskBalancerCluster diskBalancerCluster = new DiskBalancerClusterBuilder() .setClusterSource("/diskBalancer/data-cluster-3node-3disk.json") .build(); plan = new PlanBuilder(diskBalancerCluster, nodeID) .setPathMap(sourceName, destName) .setUUIDMap(sourceUUID, destUUID) .build(); return this; } } private static
MockMoverHelper