language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sortpartition/SortPartitionOperator.java
{ "start": 3217, "end": 12678 }
class ____<INPUT> extends AbstractStreamOperator<INPUT> implements OneInputStreamOperator<INPUT, INPUT>, BoundedOneInput { /** The type information of input records. */ protected final TypeInformation<INPUT> inputType; /** The selector to create the sort key for records, which will be null if it's not used. */ protected final KeySelector<INPUT, ?> sortFieldSelector; /** The order to sort records. */ private final Order sortOrder; /** * The string field to indicate the sort key for records with tuple or pojo type, which will be * null if it's not used. */ private final String stringSortField; /** * The int field to indicate the sort key for records with tuple type, which will be -1 if it's * not used. */ private final int positionSortField; /** The sorter to sort record if the record is not sorted by {@link KeySelector}. */ private PushSorter<INPUT> recordSorter = null; /** The sorter to sort record if the record is sorted by {@link KeySelector}. */ private PushSorter<Tuple2<?, INPUT>> recordSorterForKeySelector = null; public SortPartitionOperator( TypeInformation<INPUT> inputType, int positionSortField, Order sortOrder) { this.inputType = inputType; ensureFieldSortable(positionSortField); this.positionSortField = positionSortField; this.stringSortField = null; this.sortFieldSelector = null; this.sortOrder = sortOrder; } public SortPartitionOperator( TypeInformation<INPUT> inputType, String stringSortField, Order sortOrder) { this.inputType = inputType; ensureFieldSortable(stringSortField); this.positionSortField = -1; this.stringSortField = stringSortField; this.sortFieldSelector = null; this.sortOrder = sortOrder; } public <K> SortPartitionOperator( TypeInformation<INPUT> inputType, KeySelector<INPUT, K> sortFieldSelector, Order sortOrder) { this.inputType = inputType; ensureFieldSortable(sortFieldSelector); this.positionSortField = -1; this.stringSortField = null; this.sortFieldSelector = sortFieldSelector; this.sortOrder = sortOrder; } @Override protected void setup( StreamTask<?, ?> containingTask, StreamConfig config, Output<StreamRecord<INPUT>> output) { super.setup(containingTask, config, output); ExecutionConfig executionConfig = containingTask.getEnvironment().getExecutionConfig(); if (sortFieldSelector != null) { TypeInformation<Tuple2<?, INPUT>> sortTypeInfo = Types.TUPLE( TypeExtractor.getKeySelectorTypes(sortFieldSelector, inputType), inputType); recordSorterForKeySelector = getSorter( sortTypeInfo.createSerializer(executionConfig.getSerializerConfig()), ((CompositeType<Tuple2<?, INPUT>>) sortTypeInfo) .createComparator( getSortFieldIndex(), getSortOrderIndicator(), 0, executionConfig), containingTask); } else { recordSorter = getSorter( inputType.createSerializer(executionConfig.getSerializerConfig()), ((CompositeType<INPUT>) inputType) .createComparator( getSortFieldIndex(), getSortOrderIndicator(), 0, executionConfig), containingTask); } } @Override public void processElement(StreamRecord<INPUT> element) throws Exception { if (sortFieldSelector != null) { recordSorterForKeySelector.writeRecord( Tuple2.of(sortFieldSelector.getKey(element.getValue()), element.getValue())); } else { recordSorter.writeRecord(element.getValue()); } } @Override public void endInput() throws Exception { TimestampedCollector<INPUT> outputCollector = new TimestampedCollector<>(output); if (sortFieldSelector != null) { recordSorterForKeySelector.finishReading(); MutableObjectIterator<Tuple2<?, INPUT>> dataIterator = recordSorterForKeySelector.getIterator(); Tuple2<?, INPUT> record = dataIterator.next(); while (record != null) { outputCollector.collect(record.f1); record = dataIterator.next(); } recordSorterForKeySelector.close(); } else { recordSorter.finishReading(); MutableObjectIterator<INPUT> dataIterator = recordSorter.getIterator(); INPUT record = dataIterator.next(); while (record != null) { outputCollector.collect(record); record = dataIterator.next(); } recordSorter.close(); } } @Override public OperatorAttributes getOperatorAttributes() { return new OperatorAttributesBuilder().setOutputOnlyAfterEndOfStream(true).build(); } /** * Get the sort field index for the sorted data. * * @return the sort field index. */ private int[] getSortFieldIndex() { int[] sortFieldIndex = new int[1]; if (positionSortField != -1) { sortFieldIndex[0] = new Keys.ExpressionKeys<>(positionSortField, inputType) .computeLogicalKeyPositions()[0]; } else if (stringSortField != null) { sortFieldIndex[0] = new Keys.ExpressionKeys<>(stringSortField, inputType) .computeLogicalKeyPositions()[0]; } return sortFieldIndex; } /** * Get the indicator for the sort order. * * @return sort order indicator. */ private boolean[] getSortOrderIndicator() { boolean[] sortOrderIndicator = new boolean[1]; sortOrderIndicator[0] = this.sortOrder == Order.ASCENDING; return sortOrderIndicator; } private void ensureFieldSortable(int field) throws InvalidProgramException { if (!Keys.ExpressionKeys.isSortKey(field, inputType)) { throw new InvalidProgramException( "The field " + field + " of input type " + inputType + " is not sortable."); } } private void ensureFieldSortable(String field) throws InvalidProgramException { if (!Keys.ExpressionKeys.isSortKey(field, inputType)) { throw new InvalidProgramException( "The field " + field + " of input type " + inputType + " is not sortable."); } } private <K> void ensureFieldSortable(KeySelector<INPUT, K> keySelector) { TypeInformation<K> keyType = TypeExtractor.getKeySelectorTypes(keySelector, inputType); Keys.SelectorFunctionKeys<INPUT, K> sortKey = new Keys.SelectorFunctionKeys<>(keySelector, inputType, keyType); if (!sortKey.getKeyType().isSortKeyType()) { throw new InvalidProgramException("The key type " + keyType + " is not sortable."); } } private <TYPE> PushSorter<TYPE> getSorter( TypeSerializer<TYPE> typeSerializer, TypeComparator<TYPE> typeComparator, StreamTask<?, ?> streamTask) { ClassLoader userCodeClassLoader = streamTask.getUserCodeClassLoader(); Configuration jobConfiguration = streamTask.getEnvironment().getJobConfiguration(); double managedMemoryFraction = config.getManagedMemoryFractionOperatorUseCaseOfSlot( ManagedMemoryUseCase.OPERATOR, streamTask.getEnvironment().getJobConfiguration(), streamTask.getEnvironment().getTaskConfiguration(), userCodeClassLoader); try { return ExternalSorter.newBuilder( streamTask.getEnvironment().getMemoryManager(), streamTask, typeSerializer, typeComparator, streamTask.getExecutionConfig()) .memoryFraction(managedMemoryFraction) .enableSpilling( streamTask.getEnvironment().getIOManager(), jobConfiguration.get(AlgorithmOptions.SORT_SPILLING_THRESHOLD)) .maxNumFileHandles(jobConfiguration.get(AlgorithmOptions.SPILLING_MAX_FAN)) .objectReuse(streamTask.getExecutionConfig().isObjectReuseEnabled()) .largeRecords(jobConfiguration.get(AlgorithmOptions.USE_LARGE_RECORDS_HANDLER)) .build(); } catch (MemoryAllocationException e) { throw new RuntimeException(e); } } }
SortPartitionOperator
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/serializers/ServerVertxBufferMessageBodyWriter.java
{ "start": 708, "end": 1843 }
class ____ implements ServerMessageBodyWriter<Buffer> { public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return true; } public void writeTo(Buffer buffer, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write(buffer.getBytes()); } @Override public boolean isWriteable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo target, MediaType mediaType) { return true; } @Override public void writeResponse(Buffer buffer, Type genericType, ServerRequestContext context) throws WebApplicationException { var serverHttpResponse = context.serverResponse(); if (serverHttpResponse instanceof final VertxResteasyReactiveRequestContext resteasyContext) { resteasyContext.end(buffer); } else { context.serverResponse().end(buffer.getBytes()); } } }
ServerVertxBufferMessageBodyWriter
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/CompatibleWithMisuseTest.java
{ "start": 1276, "end": 1917 }
class ____<X> { static final String CONSTANT = "X"; void doSomething(@CompatibleWith("X") Object ok) {} void doSomethingWithConstant(@CompatibleWith(CONSTANT) Object ok) {} <Y extends String> void doSomethingElse(@CompatibleWith("Y") Object ok) {} <X, Z> void doSomethingTwice(@CompatibleWith("X") Object ok) {} } """) .doTest(); } @Test public void bad() { compilationHelper .addSourceLines( "Test.java", """ import com.google.errorprone.annotations.CompatibleWith;
Test
java
spring-projects__spring-security
oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java
{ "start": 2562, "end": 15140 }
class ____ { // @formatter:off private static final String DEFAULT_RESPONSE_TEMPLATE = "{\n" + " \"issuer\": \"%s\", \n" + " \"jwks_uri\": \"%s/.well-known/jwks.json\" \n" + "}"; // @formatter:on private static final String JWK_SET = "{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"one\",\"n\":\"3FlqJr5TRskIQIgdE3Dd7D9lboWdcTUT8a-fJR7MAvQm7XXNoYkm3v7MQL1NYtDvL2l8CAnc0WdSTINU6IRvc5Kqo2Q4csNX9SHOmEfzoROjQqahEcve1jBXluoCXdYuYpx4_1tfRgG6ii4Uhxh6iI8qNMJQX-fLfqhbfYfxBQVRPywBkAbIP4x1EAsbC6FSNmkhCxiMNqEgxaIpY8C2kJdJ_ZIV-WW4noDdzpKqHcwmB8FsrumlVY_DNVvUSDIipiq9PbP4H99TXN1o746oRaNa07rq1hoCgMSSy-85SagCoxlmyE-D-of9SsMY8Ol9t0rdzpobBuhyJ_o5dfvjKw\"}]}"; private String jwt = jwt("iss", "trusted"); private String evil = jwt("iss", "\""); private String noIssuer = jwt("sub", "sub"); @Test public void resolveWhenUsingFromTrustedIssuersThenReturnsAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { String issuer = server.url("").toString(); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(JWK_SET)); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(JWK_SET)); JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver .fromTrustedIssuers(issuer); ReactiveAuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null).block(); assertThat(authenticationManager).isNotNull(); BearerTokenAuthenticationToken token = withBearerToken(jws.serialize()); Authentication authentication = authenticationManager.authenticate(token).block(); assertThat(authentication).isNotNull(); assertThat(authentication.isAuthenticated()).isTrue(); } } @Test public void resolveWhenUsingFromTrustedIssuersPredicateThenReturnsAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { String issuer = server.url("").toString(); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(JWK_SET)); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(JWK_SET)); JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver .fromTrustedIssuers(issuer::equals); ReactiveAuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null).block(); assertThat(authenticationManager).isNotNull(); BearerTokenAuthenticationToken token = withBearerToken(jws.serialize()); Authentication authentication = authenticationManager.authenticate(token).block(); assertThat(authentication).isNotNull(); assertThat(authentication.isAuthenticated()).isTrue(); } } // gh-10444 @Test public void resolveWhednUsingTrustedIssuerThenReturnsAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { String issuer = server.url("").toString(); // @formatter:off server.enqueue(new MockResponse().setResponseCode(500).setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(JWK_SET)); // @formatter:on JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver .fromTrustedIssuers(issuer); ReactiveAuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null).block(); assertThat(authenticationManager).isNotNull(); Authentication token = withBearerToken(jws.serialize()); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> authenticationManager.authenticate(token).block()); Authentication authentication = authenticationManager.authenticate(token).block(); assertThat(authentication.isAuthenticated()).isTrue(); } } @Test public void resolveWhenUsingSameIssuerThenReturnsSameAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { String issuer = server.url("").toString(); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(JWK_SET)); TrustedIssuerJwtAuthenticationManagerResolver resolver = new TrustedIssuerJwtAuthenticationManagerResolver( (iss) -> iss.equals(issuer)); ReactiveAuthenticationManager authenticationManager = resolver.resolve(issuer).block(); ReactiveAuthenticationManager cachedAuthenticationManager = resolver.resolve(issuer).block(); assertThat(authenticationManager).isSameAs(cachedAuthenticationManager); } } @Test public void resolveWhenUsingUntrustedIssuerThenException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver .fromTrustedIssuers("other", "issuers"); Authentication token = withBearerToken(this.jwt); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((authenticationManager) -> authenticationManager.authenticate(token)) .block()) .withMessageContaining("Invalid issuer"); // @formatter:on } @Test public void resolveWhenUsingCustomIssuerAuthenticationManagerResolverThenUses() { Authentication token = withBearerToken(this.jwt); ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class); given(authenticationManager.authenticate(token)).willReturn(Mono.empty()); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( (issuer) -> Mono.just(authenticationManager)); authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block(); verify(authenticationManager).authenticate(any()); } @Test public void resolveWhenUsingExternalSourceThenRespondsToChanges() { Authentication token = withBearerToken(this.jwt); Map<String, ReactiveAuthenticationManager> authenticationManagers = new HashMap<>(); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( (issuer) -> Mono.justOrEmpty(authenticationManagers.get(issuer))); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((manager) -> manager.authenticate(token)) .block()) .withMessageContaining("Invalid issuer"); ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class); given(authenticationManager.authenticate(token)).willReturn(Mono.empty()); authenticationManagers.put("trusted", authenticationManager); authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block(); verify(authenticationManager).authenticate(token); authenticationManagers.clear(); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((manager) -> manager.authenticate(token)) .block()) .withMessageContaining("Invalid issuer"); // @formatter:on } @Test public void resolveWhenBearerTokenMalformedThenException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver .fromTrustedIssuers("trusted"); Authentication token = withBearerToken("jwt"); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((manager) -> manager.authenticate(token)) .block()) .withMessageNotContaining("Invalid issuer"); // @formatter:on } @Test public void resolveWhenBearerTokenNoIssuerThenException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver .fromTrustedIssuers("trusted"); Authentication token = withBearerToken(this.noIssuer); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((manager) -> manager.authenticate(token)) .block()) .withMessageContaining("Missing issuer"); } @Test public void resolveWhenBearerTokenEvilThenGenericException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver .fromTrustedIssuers("trusted"); Authentication token = withBearerToken(this.evil); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((manager) -> manager.authenticate(token)) .block()) .withMessage("Invalid token"); // @formatter:on } @Test public void resolveWhenAuthenticationExceptionThenAuthenticationRequestIsIncluded() { Authentication authentication = new BearerTokenAuthenticationToken(this.jwt); AuthenticationException ex = new InvalidBearerTokenException(""); ReactiveAuthenticationManager manager = mock(ReactiveAuthenticationManager.class); given(manager.authenticate(any())).willReturn(Mono.error(ex)); JwtIssuerReactiveAuthenticationManagerResolver resolver = new JwtIssuerReactiveAuthenticationManagerResolver( (issuer) -> Mono.just(manager)); StepVerifier.create(resolver.resolve(null).block().authenticate(authentication)) .expectError(InvalidBearerTokenException.class) .verify(); assertThat(ex.getAuthenticationRequest()).isEqualTo(authentication); } @Test public void factoryWhenNullOrEmptyIssuersThenException() { assertThatIllegalArgumentException().isThrownBy( () -> JwtIssuerReactiveAuthenticationManagerResolver.fromTrustedIssuers((Predicate<String>) null)); assertThatIllegalArgumentException().isThrownBy( () -> JwtIssuerReactiveAuthenticationManagerResolver.fromTrustedIssuers((Collection<String>) null)); assertThatIllegalArgumentException().isThrownBy( () -> JwtIssuerReactiveAuthenticationManagerResolver.fromTrustedIssuers(Collections.emptyList())); } @Test public void constructorWhenNullAuthenticationManagerResolverThenException() { assertThatIllegalArgumentException().isThrownBy( () -> new JwtIssuerReactiveAuthenticationManagerResolver((ReactiveAuthenticationManagerResolver) null)); } private String jwt(String claim, String value) { PlainJWT jwt = new PlainJWT(new JWTClaimsSet.Builder().claim(claim, value).build()); return jwt.serialize(); } private BearerTokenAuthenticationToken withBearerToken(String token) { return new BearerTokenAuthenticationToken(token); } }
JwtIssuerReactiveAuthenticationManagerResolverTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/NaturalIdInUninitializedProxyTest.java
{ "start": 1715, "end": 3106 }
class ____ { @Test public void testImmutableNaturalId(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityImmutableNaturalId e = session.getReference( EntityImmutableNaturalId.class, 1 ); assertFalse( Hibernate.isInitialized( e ) ); } ); scope.inTransaction( session -> { final EntityImmutableNaturalId e = session.get( EntityImmutableNaturalId.class, 1 ); assertEquals( "name", e.name ); } ); } @Test public void testMutableNaturalId(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityMutableNaturalId e = session.getReference( EntityMutableNaturalId.class, 1 ); assertFalse( Hibernate.isInitialized( e ) ); } ); scope.inTransaction( session -> { final EntityMutableNaturalId e = session.get( EntityMutableNaturalId.class, 1 ); assertEquals( "name", e.name ); } ); } @BeforeEach public void prepareTestData(SessionFactoryScope scope) { scope.inTransaction( session -> { session.persist( new EntityMutableNaturalId( 1, "name" ) ); session.persist( new EntityImmutableNaturalId( 1, "name" ) ); } ); } @AfterEach public void cleanUpTestData(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Entity(name = "EntityMutableNaturalId") public static
NaturalIdInUninitializedProxyTest
java
netty__netty
handler/src/test/java/io/netty/handler/ssl/ConscryptJdkSslEngineInteropTest.java
{ "start": 1018, "end": 3410 }
class ____ extends SSLEngineTest { public ConscryptJdkSslEngineInteropTest() { super(false); } static boolean checkConscryptDisabled() { return !Conscrypt.isAvailable(); } @Override protected SslProvider sslClientProvider() { return SslProvider.JDK; } @Override protected SslProvider sslServerProvider() { return SslProvider.JDK; } @Override protected Provider clientSslContextProvider() { return Java8SslTestUtils.conscryptProvider(); } @MethodSource("newTestParams") @ParameterizedTest @Disabled /* Does the JDK support a "max certificate chain length"? */ @Override public void testMutualAuthValidClientCertChainTooLongFailOptionalClientAuth(SSLEngineTestParam param) throws Exception { } @MethodSource("newTestParams") @ParameterizedTest @Disabled /* Does the JDK support a "max certificate chain length"? */ @Override public void testMutualAuthValidClientCertChainTooLongFailRequireClientAuth(SSLEngineTestParam param) throws Exception { } @MethodSource("newTestParams") @ParameterizedTest @Override protected boolean mySetupMutualAuthServerIsValidServerException(Throwable cause) { // TODO(scott): work around for a JDK issue. The exception should be SSLHandshakeException. return super.mySetupMutualAuthServerIsValidServerException(cause) || causedBySSLException(cause); } @Override protected void invalidateSessionsAndAssert(SSLSessionContext context) { // Not supported by conscrypt } @MethodSource("newTestParams") @ParameterizedTest @Disabled("Disabled due a conscrypt bug") @Override public void testInvalidSNIIsIgnoredAndNotThrow(SSLEngineTestParam param) throws Exception { super.testInvalidSNIIsIgnoredAndNotThrow(param); } @Test @Disabled("Disabled due a conscrypt bug") @Override public void testTLSv13DisabledIfNoValidCipherSuiteConfigured() throws Exception { super.testTLSv13DisabledIfNoValidCipherSuiteConfigured(); } @Disabled("Disabled due a conscrypt bug") @Override public void mustCallResumeTrustedOnSessionResumption(SSLEngineTestParam param) throws Exception { super.mustCallResumeTrustedOnSessionResumption(param); } }
ConscryptJdkSslEngineInteropTest
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/groupwindow/internal/MergingWindowProcessFunction.java
{ "start": 1825, "end": 5875 }
class ____<K, W extends Window> extends InternalWindowProcessFunction<K, W> { private static final long serialVersionUID = -2866771637946397223L; private final MergingWindowAssigner<W> windowAssigner; private final TypeSerializer<W> windowSerializer; private transient MergingWindowSet<W> mergingWindows; private transient MergingFunctionImpl mergingFunction; private List<W> reuseActualWindows; public MergingWindowProcessFunction( MergingWindowAssigner<W> windowAssigner, NamespaceAggsHandleFunctionBase<W> windowAggregator, TypeSerializer<W> windowSerializer, long allowedLateness) { super(windowAssigner, windowAggregator, allowedLateness); this.windowAssigner = windowAssigner; this.windowSerializer = windowSerializer; } @Override public void open(Context<K, W> ctx) throws Exception { checkArgument(ctx instanceof MergingContext); super.open(ctx); MapStateDescriptor<W, W> mappingStateDescriptor = new MapStateDescriptor<>( "session-window-mapping", windowSerializer, windowSerializer); MapState<W, W> windowMapping = ctx.getPartitionedState(mappingStateDescriptor); this.mergingWindows = new MergingWindowSet<>(windowAssigner, windowMapping); this.mergingFunction = new MergingFunctionImpl(((MergingContext) ctx).getWindowStateMergingConsumer()); } @Override public Collection<W> assignStateNamespace(RowData inputRow, long timestamp) throws Exception { Collection<W> elementWindows = windowAssigner.assignWindows(inputRow, timestamp); mergingWindows.initializeCache(ctx.currentKey()); reuseActualWindows = new ArrayList<>(1); for (W window : elementWindows) { // adding the new window might result in a merge, in that case the actualWindow // is the merged window and we work with that. If we don't merge then // actualWindow == window W actualWindow = mergingWindows.addWindow(window, mergingFunction); // drop if the window is already late if (isWindowLate(actualWindow)) { mergingWindows.retireWindow(actualWindow); } else { reuseActualWindows.add(actualWindow); } } List<W> affectedWindows = new ArrayList<>(reuseActualWindows.size()); for (W actual : reuseActualWindows) { affectedWindows.add(mergingWindows.getStateWindow(actual)); } return affectedWindows; } @Override public Collection<W> assignActualWindows(RowData inputRow, long timestamp) throws Exception { // the actual windows is calculated in assignStateNamespace return reuseActualWindows; } @Override public void prepareAggregateAccumulatorForEmit(W window) throws Exception { W stateWindow = mergingWindows.getStateWindow(window); RowData acc = ctx.getWindowAccumulators(stateWindow); if (acc == null) { acc = windowAggregator.createAccumulators(); } windowAggregator.setAccumulators(stateWindow, acc); } @Override public void cleanWindowIfNeeded(W window, long currentTime) throws Exception { if (isCleanupTime(window, currentTime)) { ctx.clearTrigger(window); W stateWindow = mergingWindows.getStateWindow(window); ctx.clearWindowState(stateWindow); // retire expired window mergingWindows.initializeCache(ctx.currentKey()); mergingWindows.retireWindow(window); // do not need to clear previous state, previous state is disabled in session window } } /** Get the state window as the namespace stored acc in the data about this actual window. */ public W getStateWindow(W window) throws Exception { return mergingWindows.getStateWindow(window); } private
MergingWindowProcessFunction
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorter.java
{ "start": 18211, "end": 18687 }
class ____ extends AbstractPagedOutputView { SingleSegmentOutputView(int segmentSize) { super(segmentSize, 0); } void set(MemorySegment segment) { seekOutput(segment, 0); } @Override protected MemorySegment nextSegment(MemorySegment current, int positionInCurrent) throws IOException { throw new EOFException(); } } private static final
SingleSegmentOutputView
java
apache__flink
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/parser/SqlCommandParser.java
{ "start": 1050, "end": 1473 }
interface ____ { /** * Parses given statement. * * @param statement the sql client input to evaluate. * @return the optional value of {@link Command} parsed. It would be empty when the statement is * "" or ";". * @throws SqlExecutionException if any error happen while parsing or validating the statement. */ Optional<Command> parseStatement(String statement); }
SqlCommandParser
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/AbstractStepTestCase.java
{ "start": 1083, "end": 3808 }
class ____<T extends Step> extends ESTestCase { protected Client client; protected ProjectClient projectClient; protected AdminClient adminClient; protected IndicesAdminClient indicesClient; @Before public void setupClient() { client = Mockito.mock(Client.class); adminClient = Mockito.mock(AdminClient.class); indicesClient = Mockito.mock(IndicesAdminClient.class); projectClient = Mockito.mock(ProjectClient.class); Mockito.when(client.projectClient(Mockito.any())).thenReturn(projectClient); Mockito.when(projectClient.admin()).thenReturn(adminClient); Mockito.when(adminClient.indices()).thenReturn(indicesClient); } protected static final int NUMBER_OF_TEST_RUNS = 20; protected static final TimeValue MASTER_TIMEOUT = TimeValue.timeValueSeconds(30); protected abstract T createRandomInstance(); protected abstract T mutateInstance(T instance); protected abstract T copyInstance(T instance); public void testHashcodeAndEquals() { for (int runs = 0; runs < NUMBER_OF_TEST_RUNS; runs++) { EqualsHashCodeTestUtils.checkEqualsAndHashCode(createRandomInstance(), this::copyInstance, this::mutateInstance); } } public static StepKey randomStepKey() { String randomPhase = randomAlphaOfLength(10); String randomAction = randomAlphaOfLength(10); String randomStepName = randomAlphaOfLength(10); return new StepKey(randomPhase, randomAction, randomStepName); } public void testStepNameNotError() { T instance = createRandomInstance(); StepKey stepKey = instance.getKey(); assertFalse(ErrorStep.NAME.equals(stepKey.name())); StepKey nextStepKey = instance.getKey(); assertFalse(ErrorStep.NAME.equals(nextStepKey.name())); } protected void performActionAndWait( AsyncActionStep step, IndexMetadata indexMetadata, ProjectState currentState, ClusterStateObserver observer ) throws Exception { final var future = new PlainActionFuture<Void>(); step.performAction(indexMetadata, currentState, observer, future); try { future.get(SAFE_AWAIT_TIMEOUT.millis(), TimeUnit.MILLISECONDS); } catch (ExecutionException e) { if (e.getCause() instanceof Exception exception) { throw exception; } else { fail(e, "unexpected"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); fail(e, "unexpected"); } catch (Exception e) { fail(e, "unexpected"); } } }
AbstractStepTestCase
java
apache__camel
components/camel-smb/src/test/java/org/apache/camel/component/smb/SmbComponentConnectionIT.java
{ "start": 1623, "end": 6641 }
class ____ extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(SmbComponentIT.class); @RegisterExtension public static SmbService service = SmbServiceFactory.createSingletonService(); @EndpointInject("mock:result") protected MockEndpoint mockResultEndpoint; @Test public void testSmbRead() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(100); mock.assertIsSatisfied(); } @Test public void testSendReceive() throws Exception { MockEndpoint mock = getMockEndpoint("mock:received_send"); mock.expectedMessageCount(1); template.sendBodyAndHeader("seda:send", "Hello World", Exchange.FILE_NAME, "file_send.doc"); mock.assertIsSatisfied(); SmbFile file = mock.getExchanges().get(0).getIn().getBody(SmbFile.class); Assertions.assertEquals("Hello World", new String((byte[]) file.getBody(), StandardCharsets.UTF_8)); } @Test public void testDefaultIgnore() throws Exception { MockEndpoint mock = getMockEndpoint("mock:received_ignore"); mock.expectedMessageCount(1); template.sendBodyAndHeader("seda:send", "Hello World", Exchange.FILE_NAME, "file_ignore.doc"); template.sendBodyAndHeaders("seda:send", "Good Bye", Map.of(Exchange.FILE_NAME, "file_ignore.doc", SmbConstants.SMB_FILE_EXISTS, GenericFileExist.Ignore.name())); mock.assertIsSatisfied(); SmbFile file = mock.getExchanges().get(0).getIn().getBody(SmbFile.class); Assertions.assertEquals("Hello World", new String((byte[]) file.getBody(), StandardCharsets.UTF_8)); } @Test public void testOverride() throws Exception { MockEndpoint mock = getMockEndpoint("mock:received_override"); mock.expectedMessageCount(1); template.sendBodyAndHeader("seda:send", "Hello World22", Exchange.FILE_NAME, "file_override.doc"); template.sendBodyAndHeaders("seda:send", "Good Bye", Map.of(Exchange.FILE_NAME, "file_override.doc", SmbConstants.SMB_FILE_EXISTS, GenericFileExist.Override.name())); mock.assertIsSatisfied(); SmbFile file = mock.getExchanges().get(0).getIn().getBody(SmbFile.class); Assertions.assertEquals("Good Bye", new String((byte[]) file.getBody(), StandardCharsets.UTF_8)); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { private void process(Exchange exchange) throws IOException { final SmbFile data = exchange.getMessage().getBody(SmbFile.class); final String name = exchange.getMessage().getHeader(Exchange.FILE_NAME, String.class); new String((byte[]) data.getBody(), StandardCharsets.UTF_8); LOG.debug("Read exchange name {} at {} with contents: {} (bytes {})", name, data.getAbsoluteFilePath(), new String((byte[]) data.getBody(), StandardCharsets.UTF_8), data.getFileLength()); } public void configure() { SmbConfig config = SmbConfig.builder() .withTimeout(120, TimeUnit.SECONDS) // Timeout sets Read, Write, and Transact timeouts (default is 60 seconds) .withSoTimeout(180, TimeUnit.SECONDS) // Socket Timeout (default is 0 seconds, blocks forever) .build(); context.getRegistry().bind("smbConfig", config); fromF("smb:%s/%s?username=%s&password=%s&smbConfig=#smbConfig", service.address(), service.shareName(), service.userName(), service.password()) .to("seda:intermediate"); from("seda:intermediate?concurrentConsumers=4") .process(this::process) .to("mock:result"); from("seda:send") .toF("smb:%s/%s?username=%s&password=%s", service.address(), service.shareName(), service.userName(), service.password()); fromF("smb:%s/%s?username=%s&password=%s&searchPattern=*_override.doc", service.address(), service.shareName(), service.userName(), service.password()) .to("mock:received_override"); fromF("smb:%s/%s?username=%s&password=%s&searchPattern=*_ignore.doc", service.address(), service.shareName(), service.userName(), service.password()) .to("mock:received_ignore"); fromF("smb:%s/%s?username=%s&password=%s&searchPattern=*_send.doc", service.address(), service.shareName(), service.userName(), service.password()) .to("mock:received_send"); } }; } }
SmbComponentConnectionIT
java
google__dagger
javatests/dagger/android/support/functional/UsesGeneratedModulesApplication.java
{ "start": 1551, "end": 3403 }
class ____ { @Provides @IntoSet static Class<?> addToComponentHierarchy() { return ApplicationComponent.class; } @ActivityScope @ContributesAndroidInjector(modules = ActivityScopedModule.class) abstract TestActivityWithScope contributeTestActivityWithScopeInjector(); @ContributesAndroidInjector(modules = DummyActivitySubcomponent.AddToHierarchy.class) abstract TestActivity contributeTestActivityInjector(); @ContributesAndroidInjector(modules = DummyInnerActivitySubcomponent.AddToHierarchy.class) abstract OuterClass.TestInnerClassActivity contributeInnerActivityInjector(); @ContributesAndroidInjector(modules = DummyParentFragmentSubcomponent.AddToHierarchy.class) abstract TestParentFragment contributeTestParentFragmentInjector(); @ContributesAndroidInjector(modules = DummyChildFragmentSubcomponent.AddToHierarchy.class) abstract TestChildFragment contributeTestChildFragmentInjector(); @ContributesAndroidInjector(modules = DummyDialogFragmentSubcomponent.AddToHierarchy.class) abstract TestDialogFragment contributeTestDialogFragmentInjector(); @ContributesAndroidInjector(modules = DummyServiceSubcomponent.AddToHierarchy.class) abstract TestService contributeTestServiceInjector(); @ContributesAndroidInjector(modules = DummyIntentServiceSubcomponent.AddToHierarchy.class) abstract TestIntentService contributeTestIntentServiceInjector(); @ContributesAndroidInjector(modules = DummyBroadcastReceiverSubcomponent.AddToHierarchy.class) abstract TestBroadcastReceiver contributeTestBroadcastReceiverInjector(); @ContributesAndroidInjector(modules = DummyContentProviderSubcomponent.AddToHierarchy.class) abstract TestContentProvider contributeTestContentProviderInjector(); } @Retention(RUNTIME) @Scope @
ApplicationModule
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/idgen/enhanced/sequence/HiLoSequenceMismatchStrategyTest.java
{ "start": 1775, "end": 3906 }
class ____ { public final static String sequenceName = "ID_SEQ_HILO_SEQ"; @BeforeEach public void dropDatabaseSequence(SessionFactoryScope scope) { final Dialect dialect = scope.getSessionFactory().getJdbcServices().getDialect(); final String[] dropSequenceStatements = dialect.getSequenceSupport().getDropSequenceStrings( sequenceName ); final String[] createSequenceStatements = dialect.getSequenceSupport().getCreateSequenceStrings( sequenceName, 1, 1 ); scope.inSession(session -> session.doWork( connection -> { try ( Statement statement = connection.createStatement() ) { for ( String dropSequenceStatement : dropSequenceStatements ) { try { statement.execute( dropSequenceStatement ); } catch (SQLException e) { System.out.printf( "TEST DEBUG : dropping sequence failed [`%s`] - %s", dropSequenceStatement, e.getMessage() ); System.out.println(); e.printStackTrace( System.out ); // ignore } } // Commit in between because CockroachDB fails to drop and commit schema objects in the same transaction connection.commit(); for ( String createSequenceStatement : createSequenceStatements ) { statement.execute( createSequenceStatement ); } connection.commit(); } catch (SQLException e) { Assertions.fail( e.getMessage() ); } } ) ); } @Test public void testSequenceMismatchStrategyNotApplied(SessionFactoryScope scope) { final EntityPersister persister = scope.getSessionFactory() .getMappingMetamodel() .getEntityDescriptor(TestEntity.class.getName()); assertThat( persister.getGenerator() ).isInstanceOf( SequenceStyleGenerator.class ); final SequenceStyleGenerator generator = (SequenceStyleGenerator) persister.getGenerator(); final Optimizer optimizer = generator.getOptimizer(); assertThat( optimizer ).isInstanceOf( HiLoOptimizer.class ); assertThat( optimizer.getIncrementSize() ).isNotEqualTo( 1 ); assertThat( generator.getDatabaseStructure().getPhysicalName().render() ).isEqualTo( sequenceName ); } @Entity(name = "TestEntity") public static
HiLoSequenceMismatchStrategyTest
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/view/UrlBasedViewResolver.java
{ "start": 2913, "end": 3917 }
class ____ not support localized resolution, i.e. resolving * a symbolic view name to different resources depending on the current locale. * * <p><b>Note:</b> When chaining ViewResolvers, a UrlBasedViewResolver will check whether * the {@linkplain AbstractUrlBasedView#checkResource specified resource actually exists}. * However, with {@link InternalResourceView}, it is not generally possible to * determine the existence of the target resource upfront. In such a scenario, * a UrlBasedViewResolver will always return a View for any given view name; * as a consequence, it should be configured as the last ViewResolver in the chain. * * @author Juergen Hoeller * @author Rob Harrop * @author Sam Brannen * @since 13.12.2003 * @see #setViewClass * @see #setPrefix * @see #setSuffix * @see #setRequestContextAttribute * @see #REDIRECT_URL_PREFIX * @see AbstractUrlBasedView * @see InternalResourceView * @see org.springframework.web.servlet.view.freemarker.FreeMarkerView */ public
does
java
apache__camel
components/camel-reactor/src/test/java/org/apache/camel/component/reactor/engine/ReactorStreamsServiceTest.java
{ "start": 1885, "end": 2182 }
class ____ extends ReactorStreamsServiceTestSupport { // ************************************************ // Setup // ************************************************ @BindToRegistry("hello") private SampleBean bean = new SampleBean(); public static
ReactorStreamsServiceTest
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverter.java
{ "start": 1994, "end": 3528 }
class ____ extends AbstractJackson2HttpMessageConverter { private static final List<MediaType> problemDetailMediaTypes = Collections.singletonList(MediaType.APPLICATION_PROBLEM_XML); /** * Construct a new {@code MappingJackson2XmlHttpMessageConverter} using default configuration * provided by {@code Jackson2ObjectMapperBuilder}. */ public MappingJackson2XmlHttpMessageConverter() { this(Jackson2ObjectMapperBuilder.xml().build()); } /** * Construct a new {@code MappingJackson2XmlHttpMessageConverter} with a custom {@link ObjectMapper} * (must be a {@link XmlMapper} instance). * You can use {@link Jackson2ObjectMapperBuilder} to build it easily. * @see Jackson2ObjectMapperBuilder#xml() */ public MappingJackson2XmlHttpMessageConverter(ObjectMapper objectMapper) { super(objectMapper, new MediaType("application", "xml", StandardCharsets.UTF_8), new MediaType("text", "xml", StandardCharsets.UTF_8), new MediaType("application", "*+xml", StandardCharsets.UTF_8)); Assert.isInstanceOf(XmlMapper.class, objectMapper, "XmlMapper required"); } /** * {@inheritDoc} * <p>The {@code ObjectMapper} parameter must be an {@link XmlMapper} instance. */ @Override public void setObjectMapper(ObjectMapper objectMapper) { Assert.isInstanceOf(XmlMapper.class, objectMapper, "XmlMapper required"); super.setObjectMapper(objectMapper); } @Override protected List<MediaType> getMediaTypesForProblemDetail() { return problemDetailMediaTypes; } }
MappingJackson2XmlHttpMessageConverter
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/health/HealthCheckResultBuilder.java
{ "start": 1101, "end": 4361 }
class ____ implements Builder<HealthCheck.Result> { private final HealthCheck check; private String message; private Throwable error; private Map<String, Object> details; private HealthCheck.State state; private HealthCheckResultBuilder(HealthCheck check) { this.check = check; } public String message() { return this.message; } public HealthCheckResultBuilder message(String message) { this.message = message; return this; } public Throwable error() { return this.error; } public HealthCheckResultBuilder error(Throwable error) { this.error = error; return this; } public Object detail(String key) { return this.details != null ? this.details.get(key) : null; } public HealthCheckResultBuilder detail(String key, Object value) { if (this.details == null) { this.details = new HashMap<>(); } this.details.put(key, value); return this; } public HealthCheckResultBuilder details(Map<String, Object> details) { if (ObjectHelper.isNotEmpty(details)) { details.forEach(this::detail); } return this; } public HealthCheck.State state() { return this.state; } public HealthCheckResultBuilder state(HealthCheck.State state) { this.state = state; return this; } public HealthCheckResultBuilder up() { return state(HealthCheck.State.UP); } public HealthCheckResultBuilder down() { return state(HealthCheck.State.DOWN); } public HealthCheckResultBuilder unknown() { return state(HealthCheck.State.UNKNOWN); } @Override public HealthCheck.Result build() { // Validation ObjectHelper.notNull(this.state, "Response State"); final HealthCheck.State responseState = this.state; final Optional<String> responseMessage = Optional.ofNullable(this.message); final Optional<Throwable> responseError = Optional.ofNullable(this.error); final Map<String, Object> responseDetails = ObjectHelper.isNotEmpty(this.details) ? Collections.unmodifiableMap(new HashMap<>(this.details)) : Collections.emptyMap(); return new HealthCheck.Result() { @Override public HealthCheck getCheck() { return check; } @Override public HealthCheck.State getState() { return responseState; } @Override public Optional<String> getMessage() { return responseMessage; } @Override public Optional<Throwable> getError() { return responseError; } @Override public Map<String, Object> getDetails() { return responseDetails; } }; } public static HealthCheckResultBuilder on(HealthCheck check) { return new HealthCheckResultBuilder(check); } @Override public String toString() { return "HealthCheck[" + check.getGroup() + "/" + check.getId() + "]"; } }
HealthCheckResultBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/BytecodeEnhancedLazyLoadingOnDeletedEntityTest.java
{ "start": 3908, "end": 4367 }
class ____ { @Id Integer id; @ManyToMany(mappedBy = "nonOwners", fetch = FetchType.LAZY) List<AssociationOwner> owners = new ArrayList<>(); AssociationNonOwner() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public List<AssociationOwner> getOwners() { return owners; } public void setOwners(List<AssociationOwner> owners) { this.owners = owners; } } }
AssociationNonOwner
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/config/ProducerTemplateMixedAutoRegisterTwoCamelContextsTest.java
{ "start": 1389, "end": 2780 }
class ____ extends SpringRunWithTestSupport { @Resource(name = "camel1") private CamelContext context1; @Resource(name = "camel2") private CamelContext context2; @Test public void testHasTemplateCamel1() { DefaultProducerTemplate lookup = context1.getRegistry().lookupByNameAndType("template1", DefaultProducerTemplate.class); assertNotNull(lookup, "Should lookup producer template"); assertEquals("camel1", lookup.getCamelContext().getName()); } @Test public void testHasTemplateCamel2() { DefaultProducerTemplate lookup = context1.getRegistry().lookupByNameAndType("template2", DefaultProducerTemplate.class); assertNotNull(lookup, "Should lookup producer template"); assertEquals("camel2", lookup.getCamelContext().getName()); } @Test public void testHasNoConsumerTemplateCamel1() { ConsumerTemplate lookup = context1.getRegistry().lookupByNameAndType("consumerTemplate", ConsumerTemplate.class); assertNull(lookup, "Should NOT lookup consumer template"); } @Test public void testHasNoConsumerTemplateCamel2() { ConsumerTemplate lookup = context2.getRegistry().lookupByNameAndType("consumerTemplate", ConsumerTemplate.class); assertNull(lookup, "Should NOT lookup consumer template"); } }
ProducerTemplateMixedAutoRegisterTwoCamelContextsTest
java
greenrobot__greendao
tests/DaoTestEntityAnnotation/src/main/java/org/greenrobot/greendao/test/entityannotation/Customer.java
{ "start": 609, "end": 4114 }
class ____ { @Id(autoincrement = true) private Long id; @NotNull @Unique private String name; /** Used to resolve relations */ @Generated(hash = 2040040024) private transient DaoSession daoSession; /** Used for active entity operations. */ @Generated(hash = 1697251196) private transient CustomerDao myDao; @ToMany(joinProperties = { @JoinProperty(name = "id", referencedName = "customerId") }) @OrderBy("date ASC") private List<Order> orders; @Generated(hash = 60841032) public Customer() { } public Customer(Long id) { this.id = id; } @Generated(hash = 969486800) public Customer(Long id, @NotNull String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @NotNull public String getName() { return name; } /** Not-null value; ensure this value is available before it is saved to the database. */ public void setName(@NotNull String name) { this.name = name; } /** * To-many relationship, resolved on first access (and after reset). * Changes to to-many relations are not persisted, make changes to the target entity. */ @Generated(hash = 1084217201) public List<Order> getOrders() { if (orders == null) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } OrderDao targetDao = daoSession.getOrderDao(); List<Order> ordersNew = targetDao._queryCustomer_Orders(id); synchronized (this) { if (orders == null) { orders = ordersNew; } } } return orders; } /** Resets a to-many relationship, making the next get call to query for a fresh result. */ @Generated(hash = 1446109810) public synchronized void resetOrders() { orders = null; } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 128553479) public void delete() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.delete(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 713229351) public void update() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.update(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 1942392019) public void refresh() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.refresh(this); } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 462117449) public void __setDaoSession(DaoSession daoSession) { this.daoSession = daoSession; myDao = daoSession != null ? daoSession.getCustomerDao() : null; } }
Customer
java
apache__logging-log4j2
log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4AdditionalFieldsIT.java
{ "start": 1559, "end": 3660 }
class ____ { @Test void test(final LoggerContext ctx, final MongoClient mongoClient) { final Logger logger = ctx.getLogger(MongoDb4AdditionalFieldsIT.class); logger.info("Hello log 1"); logger.info("Hello log 2", new RuntimeException("Hello ex 2")); final MongoDatabase database = mongoClient.getDatabase(MongoDb4TestConstants.DATABASE_NAME); assertNotNull(database); final MongoCollection<Document> collection = database.getCollection(getClass().getSimpleName()); assertNotNull(collection); final FindIterable<Document> found = collection.find(); final Document first = found.first(); assertNotNull(first, "first"); assertEquals("Hello log 1", first.getString("message"), first.toJson()); assertEquals("INFO", first.getString("level"), first.toJson()); // Document list; final String envPath = System.getenv("PATH"); // list = first.get("additionalFields", Document.class); assertEquals("1", list.getString("A"), first.toJson()); assertEquals("2", list.getString("B"), first.toJson()); assertEquals(envPath, list.getString("env1"), first.toJson()); assertEquals(envPath, list.getString("env2"), first.toJson()); // found.skip(1); final Document second = found.first(); assertNotNull(second); assertEquals("Hello log 2", second.getString("message"), second.toJson()); assertEquals("INFO", second.getString("level"), second.toJson()); final Document thrown = second.get("thrown", Document.class); assertEquals("Hello ex 2", thrown.getString("message"), thrown.toJson()); // list = second.get("additionalFields", Document.class); assertEquals("1", list.getString("A"), first.toJson()); assertEquals("2", list.getString("B"), first.toJson()); assertEquals(envPath, list.getString("env1"), first.toJson()); assertEquals(envPath, list.getString("env2"), first.toJson()); } }
MongoDb4AdditionalFieldsIT
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/SchemaBuilder.java
{ "start": 20208, "end": 20932 }
class ____<R> extends PrimitiveBuilder<R, StringBldr<R>> { private StringBldr(Completion<R> context, NameContext names) { super(context, names, Schema.Type.STRING); } private static <R> StringBldr<R> create(Completion<R> context, NameContext names) { return new StringBldr<>(context, names); } @Override protected StringBldr<R> self() { return this; } /** complete building this type, return control to context **/ public R endString() { return super.end(); } } /** * Builds an Avro bytes type with optional properties. Set properties with * {@link #prop(String, String)}, and finalize with {@link #endBytes()} **/ public static final
StringBldr
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/metadata/MetadataSerializer.java
{ "start": 1231, "end": 1459 }
interface ____ extends Versioned { /** * Deserializes a savepoint from an input stream. * * @param dis Input stream to deserialize savepoint from * @param userCodeClassLoader the user code
MetadataSerializer
java
quarkusio__quarkus
integration-tests/mongodb-client/src/main/java/io/quarkus/it/mongodb/discriminator/Vehicle.java
{ "start": 155, "end": 621 }
class ____ { private String type; private String name; public Vehicle() { } public Vehicle(String type, String name) { this.type = type; this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Vehicle
java
quarkusio__quarkus
extensions/web-dependency-locator/deployment/src/main/java/io/quarkus/webdependency/locator/deployment/devui/WebDependencyLibrariesBuildItem.java
{ "start": 145, "end": 720 }
class ____ extends MultiBuildItem { private final String provider; private final List<WebDependencyLibrary> webDependencyLibraries; public WebDependencyLibrariesBuildItem(String provider, List<WebDependencyLibrary> webDependencyLibraries) { this.provider = provider; this.webDependencyLibraries = webDependencyLibraries; } public List<WebDependencyLibrary> getWebDependencyLibraries() { return this.webDependencyLibraries; } public String getProvider() { return this.provider; } }
WebDependencyLibrariesBuildItem
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/shortarrays/ShortArrays_assertContainsOnly_Test.java
{ "start": 1742, "end": 7095 }
class ____ extends ShortArraysBaseTest { @Test void should_pass_if_actual_contains_given_values_only() { arrays.assertContainsOnly(someInfo(), actual, arrayOf(6, 8, 10)); } @Test void should_pass_if_actual_contains_given_values_only_in_different_order() { arrays.assertContainsOnly(someInfo(), actual, arrayOf(10, 8, 6)); } @Test void should_pass_if_actual_contains_given_values_only_more_than_once() { actual = arrayOf(6, 8, 10, 8, 8, 8); arrays.assertContainsOnly(someInfo(), actual, arrayOf(6, 8, 10)); } @Test void should_pass_if_actual_contains_given_values_only_even_if_duplicated() { arrays.assertContainsOnly(someInfo(), actual, arrayOf(6, 8, 10, 6, 8, 10)); } @Test void should_pass_if_actual_and_given_values_are_empty() { actual = emptyArray(); arrays.assertContainsOnly(someInfo(), actual, emptyArray()); } @Test void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContainsOnly(someInfo(), actual, emptyArray())); } @Test void should_throw_error_if_array_of_values_to_look_for_is_null() { assertThatNullPointerException().isThrownBy(() -> arrays.assertContainsOnly(someInfo(), actual, null)) .withMessage(valuesToLookForIsNull()); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContainsOnly(someInfo(), null, arrayOf(8))) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_does_not_contain_given_values_only() { AssertionInfo info = someInfo(); short[] expected = { 6, 8, 20 }; Throwable error = catchThrowable(() -> arrays.assertContainsOnly(info, actual, expected)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldContainOnly(actual, expected, newArrayList((short) 20), newArrayList((short) 10))); } @Test void should_pass_if_actual_contains_given_values_only_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, arrayOf(6, -8, 10)); } @Test void should_pass_if_actual_contains_given_values_only_in_different_order_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, arrayOf(10, -8, 6)); } @Test void should_pass_if_actual_contains_given_values_only_more_than_once_according_to_custom_comparison_strategy() { actual = arrayOf(6, -8, 10, -8, 10, -8); arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, arrayOf(6, 8, -10)); } @Test void should_pass_if_actual_contains_given_values_only_even_if_duplicated_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, arrayOf(6, 8, 10, 6, -8, 10)); } @Test void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, emptyArray())); } @Test void should_throw_error_if_array_of_values_to_look_for_is_null_whatever_custom_comparison_strategy_is() { assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, null)) .withMessage(valuesToLookForIsNull()); } @Test void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), null, arrayOf(-8))) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_does_not_contain_given_values_only_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); short[] expected = { 6, -8, 20 }; Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertContainsOnly(info, actual, expected)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldContainOnly(actual, expected, newArrayList((short) 20), newArrayList((short) 10), absValueComparisonStrategy)); } }
ShortArrays_assertContainsOnly_Test
java
apache__camel
components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/multimap/HazelcastMultimapComponent.java
{ "start": 1198, "end": 1711 }
class ____ extends HazelcastDefaultComponent { public HazelcastMultimapComponent() { } public HazelcastMultimapComponent(final CamelContext context) { super(context); } @Override protected HazelcastDefaultEndpoint doCreateEndpoint( String uri, String remaining, Map<String, Object> parameters, HazelcastInstance hzInstance) throws Exception { return new HazelcastMultimapEndpoint(hzInstance, uri, remaining, this); } }
HazelcastMultimapComponent
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingIntegrationTests.java
{ "start": 6698, "end": 7108 }
class ____ implements Predicate<HandlerMethod> { private final AtomicInteger invocationCount = new AtomicInteger(); @Override public boolean test(HandlerMethod handlerMethod) { this.invocationCount.incrementAndGet(); Class<?> returnType = handlerMethod.getReturnType().getParameterType(); return (ReactiveAdapterRegistry.getSharedInstance().getAdapter(returnType) == null); } } }
TestPredicate
java
google__truth
core/src/main/java/com/google/common/truth/OptionalLongSubject.java
{ "start": 968, "end": 3198 }
class ____ extends Subject { private final @Nullable OptionalLong actual; private OptionalLongSubject(FailureMetadata failureMetadata, @Nullable OptionalLong actual) { super(failureMetadata, actual); this.actual = actual; } /** Checks that the actual {@link OptionalLong} contains a value. */ public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } } /** Checks that the actual {@link OptionalLong} does not contain a value. */ public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected empty optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be empty"), fact("but was present with value", actual.getAsLong())); } } /** * Checks that the actual {@link OptionalLong} contains the given value. More sophisticated * comparisons can be done using {@code assertThat(optional.getAsLong())…}. */ public void hasValue(long expected) { if (actual == null) { failWithActual("expected an optional with value", expected); } else if (!actual.isPresent()) { failWithoutActual(fact("expected to have value", expected), simpleFact("but was absent")); } else { checkNoNeedToDisplayBothValues("getAsLong()").that(actual.getAsLong()).isEqualTo(expected); } } /** * Obsolete factory instance. This factory was previously necessary for assertions like {@code * assertWithMessage(...).about(optionalLongs()).that(optional)....}. Now, you can perform * assertions like that without the {@code about(...)} call. * * @deprecated Instead of {@code about(optionalLongs()).that(...)}, use just {@code that(...)}. * Similarly, instead of {@code assertAbout(optionalLongs()).that(...)}, use just {@code * assertThat(...)}. */ @Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalLongSubject, OptionalLong> optionalLongs() { return OptionalLongSubject::new; } }
OptionalLongSubject
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java
{ "start": 34351, "end": 34674 }
class ____ { public void test() { Integer a = 1; a.hashCode(); a = null; a = 2; } } """) .addOutputLines( "Test.java", """ package unusedvars; public
Test
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/net/JksOptions.java
{ "start": 901, "end": 2390 }
class ____ extends KeyStoreOptionsBase { /** * Default constructor */ public JksOptions() { super(); setType("JKS"); } /** * Copy constructor * * @param other the options to copy */ public JksOptions(JksOptions other) { super(other); } /** * Create options from JSON * * @param json the JSON */ public JksOptions(JsonObject json) { this(); JksOptionsConverter.fromJson(json, this); } @Override public JksOptions setPassword(String password) { return (JksOptions) super.setPassword(password); } @Override public JksOptions setPath(String path) { return (JksOptions) super.setPath(path); } /** * Set the key store as a buffer * * @param value the key store as a buffer * @return a reference to this, so the API can be used fluently */ @Override public JksOptions setValue(Buffer value) { return (JksOptions) super.setValue(value); } @Override public JksOptions setAlias(String alias) { return (JksOptions) super.setAlias(alias); } @Override public JksOptions setAliasPassword(String aliasPassword) { return (JksOptions) super.setAliasPassword(aliasPassword); } @Override public JksOptions copy() { return new JksOptions(this); } /** * Convert to JSON * * @return the JSON */ public JsonObject toJson() { JsonObject json = new JsonObject(); JksOptionsConverter.toJson(this, json); return json; } }
JksOptions
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/EnhancerImpl.java
{ "start": 7401, "end": 21388 }
class ____ AnnotationDescription.Loadable<EnhancementInfo> infoAnnotation = managedCtClass.getDeclaredAnnotations().ofType( EnhancementInfo.class ); if ( infoAnnotation != null ) { // throws an exception if there is a mismatch... verifyReEnhancement( managedCtClass, infoAnnotation.load(), enhancementContext ); } // verification succeeded (or not done) - we can simply skip the enhancement ENHANCEMENT_LOGGER.skippingAlreadyAnnotated( managedCtClass.getName() ); return null; } // can't effectively enhance interfaces if ( managedCtClass.isInterface() ) { ENHANCEMENT_LOGGER.skippingInterface( managedCtClass.getName() ); return null; } // can't effectively enhance records if ( managedCtClass.isRecord() ) { ENHANCEMENT_LOGGER.skippingRecord( managedCtClass.getName() ); return null; } if ( enhancementContext.isEntityClass( managedCtClass ) ) { if ( checkUnsupportedAttributeNaming( managedCtClass, enhancementContext ) ) { // do not enhance classes with mismatched names for PROPERTY-access persistent attributes return null; } ENHANCEMENT_LOGGER.enhancingAsEntity( managedCtClass.getName() ); DynamicType.Builder<?> builder = builderSupplier.get(); builder = builder .implement( constants.INTERFACES_for_ManagedEntity ) .defineMethod( EnhancerConstants.ENTITY_INSTANCE_GETTER_NAME, constants.TypeObject, constants.modifierPUBLIC ) .intercept( FixedValue.self() ); builder = addFieldWithGetterAndSetter( builder, constants.TypeEntityEntry, EnhancerConstants.ENTITY_ENTRY_FIELD_NAME, EnhancerConstants.ENTITY_ENTRY_GETTER_NAME, EnhancerConstants.ENTITY_ENTRY_SETTER_NAME ); builder = addFieldWithGetterAndSetter( builder, constants.TypeManagedEntity, EnhancerConstants.PREVIOUS_FIELD_NAME, EnhancerConstants.PREVIOUS_GETTER_NAME, EnhancerConstants.PREVIOUS_SETTER_NAME ); builder = addFieldWithGetterAndSetter( builder, constants.TypeManagedEntity, EnhancerConstants.NEXT_FIELD_NAME, EnhancerConstants.NEXT_GETTER_NAME, EnhancerConstants.NEXT_SETTER_NAME ); builder = addFieldWithGetterAndSetter( builder, constants.TypeBooleanPrimitive, EnhancerConstants.USE_TRACKER_FIELD_NAME, EnhancerConstants.USE_TRACKER_GETTER_NAME, EnhancerConstants.USE_TRACKER_SETTER_NAME ); builder = addFieldWithGetterAndSetter( builder, constants.TypeIntegerPrimitive, EnhancerConstants.INSTANCE_ID_FIELD_NAME, EnhancerConstants.INSTANCE_ID_GETTER_NAME, EnhancerConstants.INSTANCE_ID_SETTER_NAME ); builder = addSetPersistenceInfoMethod( builder, constants.TypeEntityEntry, constants.TypeManagedEntity, constants.TypeIntegerPrimitive ); builder = addInterceptorHandling( builder, managedCtClass ); if ( enhancementContext.doDirtyCheckingInline() ) { List<AnnotatedFieldDescription> collectionFields = collectCollectionFields( managedCtClass ); if ( collectionFields.isEmpty() ) { builder = builder.implement( constants.INTERFACES_for_SelfDirtinessTracker ) .defineField( EnhancerConstants.TRACKER_FIELD_NAME, constants.DirtyTrackerTypeDescription, constants.modifierPRIVATE_TRANSIENT ) .annotateField( constants.TRANSIENT_ANNOTATION ) .defineMethod( EnhancerConstants.TRACKER_CHANGER_NAME, constants.TypeVoid, constants.modifierPUBLIC ) .withParameter( constants.TypeString ) .intercept( constants.implementationTrackChange ) .defineMethod( EnhancerConstants.TRACKER_GET_NAME, constants.Type_Array_String, constants.modifierPUBLIC ) .intercept( constants.implementationGetDirtyAttributesWithoutCollections ) .defineMethod( EnhancerConstants.TRACKER_HAS_CHANGED_NAME, constants.TypeBooleanPrimitive, constants.modifierPUBLIC ) .intercept( constants.implementationAreFieldsDirtyWithoutCollections ) .defineMethod( EnhancerConstants.TRACKER_CLEAR_NAME, constants.TypeVoid, constants.modifierPUBLIC ) .intercept( constants.implementationClearDirtyAttributesWithoutCollections ) .defineMethod( EnhancerConstants.TRACKER_SUSPEND_NAME, constants.TypeVoid, constants.modifierPUBLIC ) .withParameter( constants.TypeBooleanPrimitive ) .intercept( constants.implementationSuspendDirtyTracking ) .defineMethod( EnhancerConstants.TRACKER_COLLECTION_GET_NAME, constants.TypeCollectionTracker, constants.modifierPUBLIC ) .intercept( constants.implementationGetCollectionTrackerWithoutCollections ); } else { //TODO es.enableInterfaceExtendedSelfDirtinessTracker ? Careful with consequences.. builder = builder.implement( constants.INTERFACES_for_ExtendedSelfDirtinessTracker ) .defineField( EnhancerConstants.TRACKER_FIELD_NAME, constants.DirtyTrackerTypeDescription, constants.modifierPRIVATE_TRANSIENT ) .annotateField( constants.TRANSIENT_ANNOTATION ) .defineField( EnhancerConstants.TRACKER_COLLECTION_NAME, constants.TypeCollectionTracker, constants.modifierPRIVATE_TRANSIENT ) .annotateField( constants.TRANSIENT_ANNOTATION ) .defineMethod( EnhancerConstants.TRACKER_CHANGER_NAME, constants.TypeVoid, constants.modifierPUBLIC ) .withParameter( constants.TypeString ) .intercept( constants.implementationTrackChange ) .defineMethod( EnhancerConstants.TRACKER_GET_NAME, constants.Type_Array_String, constants.modifierPUBLIC ) .intercept( constants.implementationGetDirtyAttributes ) .defineMethod( EnhancerConstants.TRACKER_HAS_CHANGED_NAME, constants.TypeBooleanPrimitive, constants.modifierPUBLIC ) .intercept( constants.implementationAreFieldsDirty ) .defineMethod( EnhancerConstants.TRACKER_CLEAR_NAME, constants.TypeVoid, constants.modifierPUBLIC ) .intercept( constants.implementationClearDirtyAttributes ) .defineMethod( EnhancerConstants.TRACKER_SUSPEND_NAME, constants.TypeVoid, constants.modifierPUBLIC ) .withParameter( constants.TypeBooleanPrimitive ) .intercept( constants.implementationSuspendDirtyTracking ) .defineMethod( EnhancerConstants.TRACKER_COLLECTION_GET_NAME, constants.TypeCollectionTracker, constants.modifierPUBLIC ) .intercept( FieldAccessor.ofField( EnhancerConstants.TRACKER_COLLECTION_NAME ) ); Implementation isDirty = StubMethod.INSTANCE, getDirtyNames = StubMethod.INSTANCE, clearDirtyNames = StubMethod.INSTANCE; for ( AnnotatedFieldDescription collectionField : collectionFields ) { String collectionFieldName = collectionField.getName(); Class adviceIsDirty; Class adviceGetDirtyNames; Class adviceClearDirtyNames; if ( collectionField.getType().asErasure().isAssignableTo( Map.class ) ) { adviceIsDirty = CodeTemplates.MapAreCollectionFieldsDirty.class; adviceGetDirtyNames = CodeTemplates.MapGetCollectionFieldDirtyNames.class; adviceClearDirtyNames = CodeTemplates.MapGetCollectionClearDirtyNames.class; } else { adviceIsDirty = CodeTemplates.CollectionAreCollectionFieldsDirty.class; adviceGetDirtyNames = CodeTemplates.CollectionGetCollectionFieldDirtyNames.class; adviceClearDirtyNames = CodeTemplates.CollectionGetCollectionClearDirtyNames.class; } if ( collectionField.isVisibleTo( managedCtClass ) ) { FieldDescription fieldDescription = collectionField.getFieldDescription(); isDirty = Advice.withCustomMapping() .bind( CodeTemplates.FieldName.class, collectionFieldName ) .bind( CodeTemplates.FieldValue.class, fieldDescription ) .to( adviceIsDirty, constants.adviceLocator ) .wrap( isDirty ); getDirtyNames = Advice.withCustomMapping() .bind( CodeTemplates.FieldName.class, collectionFieldName ) .bind( CodeTemplates.FieldValue.class, fieldDescription ) .to( adviceGetDirtyNames, constants.adviceLocator ) .wrap( getDirtyNames ); clearDirtyNames = Advice.withCustomMapping() .bind( CodeTemplates.FieldName.class, collectionFieldName ) .bind( CodeTemplates.FieldValue.class, fieldDescription ) .to( adviceClearDirtyNames, constants.adviceLocator ) .wrap( clearDirtyNames ); } else { CodeTemplates.GetterMapping getterMapping = new CodeTemplates.GetterMapping( collectionField.getFieldDescription() ); isDirty = Advice.withCustomMapping() .bind( CodeTemplates.FieldName.class, collectionFieldName ) .bind( CodeTemplates.FieldValue.class, getterMapping ) .to( adviceIsDirty, constants.adviceLocator ) .wrap( isDirty ); getDirtyNames = Advice.withCustomMapping() .bind( CodeTemplates.FieldName.class, collectionFieldName ) .bind( CodeTemplates.FieldValue.class, getterMapping ) .to( adviceGetDirtyNames, constants.adviceLocator ) .wrap( getDirtyNames ); clearDirtyNames = Advice.withCustomMapping() .bind( CodeTemplates.FieldName.class, collectionFieldName ) .bind( CodeTemplates.FieldValue.class, getterMapping ) .to( adviceClearDirtyNames, constants.adviceLocator ) .wrap( clearDirtyNames ); } } if ( enhancementContext.hasLazyLoadableAttributes( managedCtClass ) ) { clearDirtyNames = constants.adviceInitializeLazyAttributeLoadingInterceptor.wrap( clearDirtyNames ); } builder = builder.defineMethod( EnhancerConstants.TRACKER_COLLECTION_CHANGED_NAME, constants.TypeBooleanPrimitive, constants.modifierPUBLIC ) .intercept( isDirty ) .defineMethod( EnhancerConstants.TRACKER_COLLECTION_CHANGED_FIELD_NAME, constants.TypeVoid, constants.modifierPUBLIC ) .withParameter( constants.DirtyTrackerTypeDescription ) .intercept( getDirtyNames ) .defineMethod( EnhancerConstants.TRACKER_COLLECTION_CLEAR_NAME, constants.TypeVoid, constants.modifierPUBLIC ) .intercept( Advice.withCustomMapping() .to( CodeTemplates.ClearDirtyCollectionNames.class, constants.adviceLocator ) .wrap( StubMethod.INSTANCE ) ) .defineMethod( ExtendedSelfDirtinessTracker.REMOVE_DIRTY_FIELDS_NAME, constants.TypeVoid, constants.modifierPUBLIC ) .withParameter( constants.TypeLazyAttributeLoadingInterceptor ) .intercept( clearDirtyNames ); } } return createTransformer( managedCtClass ).applyTo( builder ); } else if ( enhancementContext.isCompositeClass( managedCtClass ) ) { if ( checkUnsupportedAttributeNaming( managedCtClass, enhancementContext ) ) { // do not enhance classes with mismatched names for PROPERTY-access persistent attributes return null; } ENHANCEMENT_LOGGER.enhancingAsComposite( managedCtClass.getName() ); DynamicType.Builder<?> builder = builderSupplier.get(); builder = builder.implement( constants.INTERFACES_for_ManagedComposite ); builder = addInterceptorHandling( builder, managedCtClass ); if ( enhancementContext.doDirtyCheckingInline() ) { builder = builder.implement( constants.INTERFACES_for_CompositeTracker ) .defineField( EnhancerConstants.TRACKER_COMPOSITE_FIELD_NAME, constants.TypeCompositeOwnerTracker, constants.modifierPRIVATE_TRANSIENT ) .annotateField( constants.TRANSIENT_ANNOTATION ) .defineMethod( EnhancerConstants.TRACKER_COMPOSITE_SET_OWNER, constants.TypeVoid, constants.modifierPUBLIC ) .withParameters( String.class, CompositeOwner.class ) .intercept( constants.implementationSetOwner ) .defineMethod( EnhancerConstants.TRACKER_COMPOSITE_CLEAR_OWNER, constants.TypeVoid, constants.modifierPUBLIC ) .withParameter( constants.TypeString ) .intercept( constants.implementationClearOwner ); } return createTransformer( managedCtClass ).applyTo( builder ); } else if ( enhancementContext.isMappedSuperclassClass( managedCtClass ) ) { // Check for HHH-16572 (PROPERTY attributes with mismatched field and method names) if ( checkUnsupportedAttributeNaming( managedCtClass, enhancementContext ) ) { return null; } else { ENHANCEMENT_LOGGER.enhancingAsMappedSuperclass( managedCtClass.getName() ); DynamicType.Builder<?> builder = builderSupplier.get(); builder.implement( constants.INTERFACES_for_ManagedMappedSuperclass ); return createTransformer( managedCtClass ).applyTo( builder ); } } else if ( enhancementContext.doExtendedEnhancement() ) { ENHANCEMENT_LOGGER.extendedEnhancement( managedCtClass.getName() ); return createTransformer( managedCtClass ).applyExtended( builderSupplier.get() ); } else { ENHANCEMENT_LOGGER.skippingNotEntityOrComposite( managedCtClass.getName() ); return null; } } private void verifyReEnhancement( TypeDescription managedCtClass, EnhancementInfo existingInfo, ByteBuddyEnhancementContext enhancementContext) { // first, make sure versions match final String enhancementVersion = existingInfo.version(); if ( "ignore".equals( enhancementVersion ) ) { // for testing ENHANCEMENT_LOGGER.skippingReEnhancementVersionCheck( managedCtClass.getName() ); } else if ( !Version.getVersionString().equals( enhancementVersion ) ) { throw new VersionMismatchException( managedCtClass, enhancementVersion, Version.getVersionString() ); } FeatureMismatchException.checkFeatureEnablement( managedCtClass, DIRTY_CHECK, enhancementContext.doDirtyCheckingInline(), existingInfo.includesDirtyChecking() ); FeatureMismatchException.checkFeatureEnablement( managedCtClass, ASSOCIATION_MANAGEMENT, enhancementContext.doBiDirectionalAssociationManagement(), existingInfo.includesAssociationManagement() ); } /** * Utility that determines the access-type of a mapped
final
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/metamodel/CompositeIdAttributeAccessTests.java
{ "start": 4754, "end": 4928 }
class ____ implements Serializable { Long basicEntity; Long key2; } } @Entity(name = "NestedIdClassEntity") @IdClass( NestedIdClassEntity.PK.class ) public static
PK
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/SnappyTest.java
{ "start": 1134, "end": 2400 }
class ____ { private static final String TEST_STR; static { StringBuilder builder = new StringBuilder(); int charNum = 1000000; for (int i = 0; i < charNum; i++) { builder.append("a"); } TEST_STR = builder.toString(); } @ValueSource(strings = {"snappy"}) @ParameterizedTest void compression(String compressorName) { Compressor compressor = ApplicationModel.defaultModel() .getDefaultModule() .getExtensionLoader(Compressor.class) .getExtension(compressorName); String loadByStatic = Compressor.getCompressor(new FrameworkModel(), compressorName).getMessageEncoding(); Assertions.assertEquals(loadByStatic, compressor.getMessageEncoding()); byte[] compressedByteArr = compressor.compress(TEST_STR.getBytes()); DeCompressor deCompressor = ApplicationModel.defaultModel() .getDefaultModule() .getExtensionLoader(DeCompressor.class) .getExtension(compressorName); byte[] decompressedByteArr = deCompressor.decompress(compressedByteArr); Assertions.assertEquals(new String(decompressedByteArr), TEST_STR); } }
SnappyTest
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/sort/SortLimitOperator.java
{ "start": 1634, "end": 4211 }
class ____ extends TableStreamOperator<RowData> implements OneInputStreamOperator<RowData, RowData>, BoundedOneInput { private final boolean isGlobal; private final long limitStart; private final long limitEnd; private GeneratedRecordComparator genComparator; private transient PriorityQueue<RowData> heap; private transient Collector<RowData> collector; private transient RecordComparator comparator; private transient AbstractRowDataSerializer<RowData> inputSer; public SortLimitOperator( boolean isGlobal, long limitStart, long limitEnd, GeneratedRecordComparator genComparator) { this.isGlobal = isGlobal; this.limitStart = limitStart; this.limitEnd = limitEnd; this.genComparator = genComparator; } @Override public void open() throws Exception { super.open(); inputSer = (AbstractRowDataSerializer) getOperatorConfig().getTypeSerializerIn1(getUserCodeClassloader()); comparator = genComparator.newInstance(getUserCodeClassloader()); genComparator = null; // reverse the comparison. heap = new PriorityQueue<>((int) limitEnd, (o1, o2) -> comparator.compare(o2, o1)); this.collector = new StreamRecordCollector<>(output); } @Override public void processElement(StreamRecord<RowData> element) throws Exception { RowData record = element.getValue(); // Need copy element, because we will store record in heap. if (heap.size() >= limitEnd) { RowData peek = heap.peek(); if (comparator.compare(peek, record) > 0) { heap.poll(); heap.add(inputSer.copy(record)); } // else fail, this record don't need insert to the heap. } else { heap.add(inputSer.copy(record)); } } @Override public void endInput() throws Exception { if (isGlobal) { // Global sort, we need sort the results and pick records in limitStart to limitEnd. List<RowData> list = new ArrayList<>(heap); list.sort((o1, o2) -> comparator.compare(o1, o2)); int maxIndex = (int) Math.min(limitEnd, list.size()); for (int i = (int) limitStart; i < maxIndex; i++) { collector.collect(list.get(i)); } } else { for (RowData row : heap) { collector.collect(row); } } } }
SortLimitOperator
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/enhancer/HibernateEntityEnhancerFinalFieldTest.java
{ "start": 7682, "end": 8682 }
class ____ implements Serializable { private final String id; // For Hibernate ORM protected EmbeddableId() { this.id = null; } private EmbeddableId(String id) { this.id = id; } public static EmbeddableId of(String string) { return new EmbeddableId(string); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof EmbeddableId)) { return false; } EmbeddableId embeddableIdType = (EmbeddableId) o; return Objects.equals(id, embeddableIdType.id); } @Override public int hashCode() { return Objects.hash(id); } } } @Entity(name = "embwithfinal") public static
EmbeddableId
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/cli/CLITestHelper.java
{ "start": 9615, "end": 12561 }
class ____ run its compare method comparatorClass = Class.forName("org.apache.hadoop.cli.util." + comparatorType); ComparatorBase comp = (ComparatorBase) comparatorClass.newInstance(); compareOutput = comp.compare(cmdResult.getCommandOutput(), expandCommand(compdata.getExpectedOutput())); } catch (Exception e) { LOG.info("Error in instantiating the comparator" + e); } } return compareOutput; } private boolean compareTextExitCode(ComparatorData compdata, Result cmdResult) { return compdata.getExitCode() == cmdResult.getExitCode(); } /*********************************** ************* TESTS RUNNER *********************************/ public void testAll() { assertTrue(testsFromConfigFile.size() > 0, "Number of tests has to be greater then zero"); LOG.info("TestAll"); // Run the tests defined in the testConf.xml config file. for (int index = 0; index < testsFromConfigFile.size(); index++) { CLITestData testdata = testsFromConfigFile.get(index); // Execute the test commands ArrayList<CLICommand> testCommands = testdata.getTestCommands(); Result cmdResult = null; for (CLICommand cmd : testCommands) { try { cmdResult = execute(cmd); } catch (Exception e) { fail(StringUtils.stringifyException(e)); } } boolean overallTCResult = true; // Run comparators ArrayList<ComparatorData> compdata = testdata.getComparatorData(); for (ComparatorData cd : compdata) { final String comptype = cd.getComparatorType(); boolean compareOutput = false; boolean compareExitCode = false; if (! comptype.equalsIgnoreCase("none")) { compareOutput = compareTestOutput(cd, cmdResult); if (cd.getExitCode() == -1) { // No need to check exit code if not specified compareExitCode = true; } else { compareExitCode = compareTextExitCode(cd, cmdResult); } overallTCResult &= (compareOutput & compareExitCode); } cd.setExitCode(cmdResult.getExitCode()); cd.setActualOutput(cmdResult.getCommandOutput()); cd.setTestResult(compareOutput); } testdata.setTestResult(overallTCResult); // Execute the cleanup commands ArrayList<CLICommand> cleanupCommands = testdata.getCleanupCommands(); for (CLICommand cmd : cleanupCommands) { try { execute(cmd); } catch (Exception e) { fail(StringUtils.stringifyException(e)); } } } } /** * this method has to be overridden by an ancestor */ protected CommandExecutor.Result execute(CLICommand cmd) throws Exception { throw new Exception("Unknown type of test command:"+ cmd.getType()); } /* * Parser
and
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/MySQLStorageEngine.java
{ "start": 138, "end": 274 }
interface ____ how various MySQL storage engines behave in regard to Hibernate functionality. * * @author Vlad Mihalcea */ public
defines
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/RuntimeStrSubstitutor.java
{ "start": 1037, "end": 1631 }
class ____ extends StrSubstitutor { public RuntimeStrSubstitutor() {} public RuntimeStrSubstitutor(final Map<String, String> valueMap) { super(valueMap); } public RuntimeStrSubstitutor(final Properties properties) { super(properties); } public RuntimeStrSubstitutor(final StrLookup lookup) { super(lookup); } public RuntimeStrSubstitutor(final StrSubstitutor other) { super(other); } @Override public String toString() { return "RuntimeStrSubstitutor{" + super.toString() + "}"; } }
RuntimeStrSubstitutor
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxEmpty.java
{ "start": 1152, "end": 2058 }
class ____ extends Flux<Object> implements Fuseable.ScalarCallable<Object>, SourceProducer<Object> { private static final Flux<Object> INSTANCE = new FluxEmpty(); private FluxEmpty() { // deliberately no op } @Override public void subscribe(CoreSubscriber<? super Object> actual) { Operators.complete(actual); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return SourceProducer.super.scanUnsafe(key); } /** * Returns a properly parametrized instance of this empty Publisher. * * @param <T> the output type * @return a properly parametrized instance of this empty Publisher */ @SuppressWarnings("unchecked") public static <T> Flux<T> instance() { return (Flux<T>) INSTANCE; } @Override public @Nullable Object call() throws Exception { return null; /* Scalar optimizations on empty */ } }
FluxEmpty
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/inference/action/InferenceAction.java
{ "start": 16214, "end": 19069 }
class ____ extends ActionResponse implements ChunkedToXContentObject { private final InferenceServiceResults results; private final boolean isStreaming; private final Flow.Publisher<InferenceServiceResults.Result> publisher; public Response(InferenceServiceResults results) { this.results = results; this.isStreaming = false; this.publisher = null; } public Response(InferenceServiceResults results, Flow.Publisher<InferenceServiceResults.Result> publisher) { this.results = results; this.isStreaming = true; this.publisher = publisher; } public Response(StreamInput in) throws IOException { this.results = in.readNamedWriteable(InferenceServiceResults.class); // streaming isn't supported via Writeable yet this.isStreaming = false; this.publisher = null; } public InferenceServiceResults getResults() { return results; } /** * Returns {@code true} if these results are streamed as chunks, or {@code false} if these results contain the entire payload. * Currently set to false while it is being implemented. */ public boolean isStreaming() { return isStreaming; } /** * When {@link #isStreaming()} is {@code true}, the RestHandler will subscribe to this publisher. * When the RestResponse is finished with the current chunk, it will request the next chunk using the subscription. * If the RestResponse is closed, it will cancel the subscription. */ public Flow.Publisher<InferenceServiceResults.Result> publisher() { assert isStreaming() : "this should only be called after isStreaming() verifies this object is non-null"; return publisher; } @Override public void writeTo(StreamOutput out) throws IOException { // streaming isn't supported via Writeable yet out.writeNamedWriteable(results); } @Override public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params params) { return Iterators.concat( ChunkedToXContentHelper.startObject(), results.toXContentChunked(params), ChunkedToXContentHelper.endObject() ); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Response response = (Response) o; return Objects.equals(results, response.results); } @Override public int hashCode() { return Objects.hash(results); } } }
Response
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/EnhancedHeadroom.java
{ "start": 1175, "end": 2672 }
class ____ { public static EnhancedHeadroom newInstance(int totalPendingCount, int totalActiveCores) { EnhancedHeadroom enhancedHeadroom = Records.newRecord(EnhancedHeadroom.class); enhancedHeadroom.setTotalPendingCount(totalPendingCount); enhancedHeadroom.setTotalActiveCores(totalActiveCores); return enhancedHeadroom; } /** * Set total pending container count. * @param totalPendingCount the pending container count */ public abstract void setTotalPendingCount(int totalPendingCount); /** * Get total pending container count. * @return the pending container count */ public abstract int getTotalPendingCount(); /** * Set total active cores for the cluster. * @param totalActiveCores the total active cores for the cluster */ public abstract void setTotalActiveCores(int totalActiveCores); /** * Get total active cores for the cluster. * @return totalActiveCores the total active cores for the cluster */ public abstract int getTotalActiveCores(); @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("<pendingCount:").append(this.getTotalPendingCount()); sb.append(", activeCores:").append(this.getTotalActiveCores()); sb.append(">"); return sb.toString(); } public double getNormalizedPendingCount(long multiplier) { int totalPendingCount = getTotalPendingCount(); return (double) totalPendingCount * multiplier; } }
EnhancedHeadroom
java
spring-projects__spring-boot
module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoader.java
{ "start": 1309, "end": 5415 }
class ____ extends URLClassLoader implements SmartClassLoader { private final ClassLoaderFileRepository updatedFiles; /** * Create a new {@link RestartClassLoader} instance. * @param parent the parent classloader * @param urls the urls managed by the classloader */ public RestartClassLoader(ClassLoader parent, URL[] urls) { this(parent, urls, ClassLoaderFileRepository.NONE); } /** * Create a new {@link RestartClassLoader} instance. * @param parent the parent classloader * @param updatedFiles any files that have been updated since the JARs referenced in * URLs were created. * @param urls the urls managed by the classloader */ public RestartClassLoader(ClassLoader parent, URL[] urls, ClassLoaderFileRepository updatedFiles) { super(urls, parent); Assert.notNull(parent, "'parent' must not be null"); Assert.notNull(updatedFiles, "'updatedFiles' must not be null"); this.updatedFiles = updatedFiles; } @Override public Enumeration<URL> getResources(String name) throws IOException { // Use the parent since we're shadowing resource and we don't want duplicates Enumeration<URL> resources = getParent().getResources(name); ClassLoaderFile file = this.updatedFiles.getFile(name); if (file != null) { // Assume that we're replacing just the first item if (resources.hasMoreElements()) { resources.nextElement(); } if (file.getKind() != Kind.DELETED) { return new CompoundEnumeration<>(createFileUrl(name, file), resources); } } return resources; } @Override public @Nullable URL getResource(String name) { ClassLoaderFile file = this.updatedFiles.getFile(name); if (file != null && file.getKind() == Kind.DELETED) { return null; } URL resource = findResource(name); if (resource != null) { return resource; } return getParent().getResource(name); } @Override public @Nullable URL findResource(String name) { final ClassLoaderFile file = this.updatedFiles.getFile(name); if (file == null) { return super.findResource(name); } if (file.getKind() == Kind.DELETED) { return null; } return createFileUrl(name, file); } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { String path = name.replace('.', '/').concat(".class"); ClassLoaderFile file = this.updatedFiles.getFile(path); if (file != null && file.getKind() == Kind.DELETED) { throw new ClassNotFoundException(name); } synchronized (getClassLoadingLock(name)) { Class<?> loadedClass = findLoadedClass(name); if (loadedClass == null) { try { loadedClass = findClass(name); } catch (ClassNotFoundException ex) { loadedClass = Class.forName(name, false, getParent()); } } if (resolve) { resolveClass(loadedClass); } return loadedClass; } } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { String path = name.replace('.', '/').concat(".class"); final ClassLoaderFile file = this.updatedFiles.getFile(path); if (file == null) { return super.findClass(name); } if (file.getKind() == Kind.DELETED) { throw new ClassNotFoundException(name); } byte[] bytes = file.getContents(); Assert.state(bytes != null, "'bytes' must not be null"); return defineClass(name, bytes, 0, bytes.length); } @Override public Class<?> publicDefineClass(String name, byte[] b, @Nullable ProtectionDomain protectionDomain) { return defineClass(name, b, 0, b.length, protectionDomain); } @Override public ClassLoader getOriginalClassLoader() { return getParent(); } private URL createFileUrl(String name, ClassLoaderFile file) { try { return new URL("reloaded", null, -1, "/" + name, new ClassLoaderFileURLStreamHandler(file)); } catch (MalformedURLException ex) { throw new IllegalStateException(ex); } } @Override public boolean isClassReloadable(Class<?> classType) { return (classType.getClassLoader() instanceof RestartClassLoader); } /** * Compound {@link Enumeration} that adds an item to the front. */ private static
RestartClassLoader
java
apache__dubbo
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PenetrateAttachmentSelector.java
{ "start": 915, "end": 1508 }
interface ____ { /** * Select some attachments to pass to next hop. * These attachments can fetch from {@link RpcContext#getServerAttachment()} or user defined. * * @return attachment pass to next hop */ Map<String, Object> select( Invocation invocation, RpcContextAttachment clientAttachment, RpcContextAttachment serverAttachment); Map<String, Object> selectReverse( Invocation invocation, RpcContextAttachment clientResponseContext, RpcContextAttachment serverResponseContext); }
PenetrateAttachmentSelector
java
elastic__elasticsearch
x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/saml/idp/SamlMetadataGeneratorTests.java
{ "start": 1432, "end": 8073 }
class ____ extends IdpSamlTestCase { public void testGenerateMetadata() throws Exception { SamlServiceProvider sp = mock(SamlServiceProvider.class); when(sp.getEntityId()).thenReturn("https://sp.org"); when(sp.shouldSignAuthnRequests()).thenReturn(true); SamlIdentityProvider idp = mock(SamlIdentityProvider.class); when(idp.getEntityId()).thenReturn("https://idp.org"); when(idp.getMetadataSigningCredential()).thenReturn(null); when(idp.getSigningCredential()).thenReturn(readCredentials("RSA", 2048)); when(idp.getSingleSignOnEndpoint(SAML2_REDIRECT_BINDING_URI)).thenReturn(new URL("https://idp.org/sso/redirect")); when(idp.getSingleLogoutEndpoint(SAML2_POST_BINDING_URI)).thenReturn(new URL("https://idp.org/slo/post")); mockRegisteredServiceProvider(idp, "https://sp.org", sp); SamlFactory factory = new SamlFactory(); SamlMetadataGenerator generator = new SamlMetadataGenerator(factory, idp); PlainActionFuture<SamlMetadataResponse> future = new PlainActionFuture<>(); generator.generateMetadata("https://sp.org", null, future); SamlMetadataResponse response = future.actionGet(); final String xml = response.getXmlString(); // RSA_2048 final String signingCertificate = joinCertificateLines( "MIIDYzCCAkugAwIBAgIVAITQVqXYYUT0w04Z2gWAZ6pv7gwbMA0GCSqGSIb3DQEBCwUAMDQxMjAw", "BgNVBAMTKUVsYXN0aWMgQ2VydGlmaWNhdGUgVG9vbCBBdXRvZ2VuZXJhdGVkIENBMCAXDTIwMDEy", "ODA2MzczNloYDzIxNjgxMDE5MDYzNzM2WjBRMRMwEQYKCZImiZPyLGQBGRYDb3JnMR0wGwYKCZIm", "iZPyLGQBGRYNZWxhc3RpY3NlYXJjaDEMMAoGA1UECxMDaWRwMQ0wCwYDVQQDEwR0ZXN0MIIBIjAN", "BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAujk+mVzI+qmf4gSJZdVVDdhFTi06kikb7FxG5JPu", "+gmU9Ke0LVEpP7Jp3gmhwsa18JUuvaepL1jnKmbbepKkEsvqUj4FuI/gImvFwb7X+xUwzNTYZAEv", "nZ4n16k0sBPuDuDibF0MGniVeLG3bD2VF3crFQrphFr+GZSXbVk5zIcSf6D6nSDcKmCNpVAK3jX9", "iV0nkr8cPtHOgprv1Y7mZgk5jwli9to0QD7r7OG5Db34R06JTMGTji+RULPISH1bc8FHdurRASkG", "msei5GlJqPSuKdViuaKPmDrvKR8OK6gMzUd3pikJgD8veLxEuZ640FHPndPlvwJrSLwhitRgPQID", "AQABo00wSzAdBgNVHQ4EFgQUD87H31WVQNfCc85/H2qhpzs3XfowHwYDVR0jBBgwFoAUVenAN+T0", "6rqNDxjMcvgimnTw+FgwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAIvHYxT30cvoHWUE2", "saDVJ4qs/e0G3WusDyem3e4HkqwLEah06RDSgVCaOfW3ey5Q6CIQW3HHGUYqO0nU8JVCWdAk3+bU", "YJJOeLnwD+SbDxxKBhxLdx+BjWata85lfJTR9+dXs0RXAAN8dSiIaj9NSgnwiJqQQZf7i66S7XB5", "8TDTdZlV3d26STLy5h7Uy6vyCka8Xu8HFQ4hH2qf2L6EhBbzVTB6tuyPQOQwrlLE65nhUNkfBbjZ", "lre45UMc9GuxzHkbvd3HEQaroMHZxnu+/n/JDlgsrCYUEXnZnOXvgUPupPynoRdDN1F6r95TLyU9", "pYjDf/6zNPE854VF6y1TqQ==" ); final String expectedXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\"https://idp.org\">" + " <md:IDPSSODescriptor" + " WantAuthnRequestsSigned=\"true\"" + " protocolSupportEnumeration=\"urn:oasis:names:tc:SAML:2.0:protocol\">" + " <md:KeyDescriptor use=\"signing\">" + " <ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">" + " <ds:X509Data>" + " <ds:X509Certificate>%(signingCertificate)</ds:X509Certificate>" + " </ds:X509Data>" + " </ds:KeyInfo>" + " </md:KeyDescriptor>" + " <md:SingleLogoutService" + " Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\"" + " Location=\"https://idp.org/slo/post\"/>" + " <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat>" + " <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</md:NameIDFormat>" + " <md:SingleSignOnService" + " Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\"" + " Location=\"https://idp.org/sso/redirect\"/>" + " </md:IDPSSODescriptor>" + "</md:EntityDescriptor>"; final Map<String, Object> replacements = Map.of("signingCertificate", signingCertificate); final String expectedXmlWithCertificate = NamedFormatter.format(expectedXml, replacements); assertThat(xml, Matchers.equalTo(normaliseXml(expectedXmlWithCertificate))); assertValidXml(xml); } public void testGenerateAndSignMetadata() throws Exception { SamlServiceProvider sp = mock(SamlServiceProvider.class); when(sp.getEntityId()).thenReturn("https://sp.org"); when(sp.shouldSignAuthnRequests()).thenReturn(true); SamlIdentityProvider idp = mock(SamlIdentityProvider.class); when(idp.getEntityId()).thenReturn("https://idp.org"); when(idp.getMetadataSigningCredential()).thenReturn(readCredentials("RSA", 4096)); when(idp.getSigningCredential()).thenReturn(readCredentials("RSA", 2048)); when(idp.getSingleSignOnEndpoint(SAML2_REDIRECT_BINDING_URI)).thenReturn(new URL("https://idp.org/sso/redirect")); when(idp.getSingleLogoutEndpoint(SAML2_POST_BINDING_URI)).thenReturn(new URL("https://idp.org/slo/post")); mockRegisteredServiceProvider(idp, "https://sp.org", sp); X509Credential signingCredential = readCredentials("RSA", 4096); SamlFactory factory = new SamlFactory(); SamlMetadataGenerator generator = new SamlMetadataGenerator(factory, idp); Element element = generator.possiblySignDescriptor(generator.buildEntityDescriptor(sp), signingCredential); EntityDescriptor descriptor = SamlFactory.buildXmlObject(element, EntityDescriptor.class); Signature signature = descriptor.getSignature(); assertNotNull(signature); SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); profileValidator.validate(signature); SignatureValidator.validate(signature, signingCredential); // no exception thrown SignatureException e = expectThrows( SignatureException.class, () -> SignatureValidator.validate(signature, readCredentials("RSA", 2048)) ); if (inFipsJvm()) { assertThat(e.getMessage(), containsString("Signature cryptographic validation not successful")); } else { assertThat(e.getMessage(), containsString("Unable to evaluate key against signature")); } } }
SamlMetadataGeneratorTests
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DataSetTestEndpointBuilderFactory.java
{ "start": 1510, "end": 1644 }
interface ____ { /** * Builder for endpoint for the DataSet Test component. */ public
DataSetTestEndpointBuilderFactory
java
elastic__elasticsearch
x-pack/plugin/ilm/src/main/java/org/elasticsearch/xpack/ilm/action/TransportPutLifecycleAction.java
{ "start": 1500, "end": 3108 }
class ____ extends TransportMasterNodeAction<PutLifecycleRequest, AcknowledgedResponse> { private final PutLifecycleMetadataService putLifecycleMetadataService; @Inject public TransportPutLifecycleAction( TransportService transportService, ClusterService clusterService, ThreadPool threadPool, ActionFilters actionFilters, PutLifecycleMetadataService putLifecycleMetadataService ) { super( ILMActions.PUT.name(), transportService, clusterService, threadPool, actionFilters, PutLifecycleRequest::new, AcknowledgedResponse::readFrom, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.putLifecycleMetadataService = putLifecycleMetadataService; } @Override protected void masterOperation( Task task, PutLifecycleRequest request, ClusterState state, ActionListener<AcknowledgedResponse> listener ) { putLifecycleMetadataService.addLifecycle(request, state, listener); } @Override protected ClusterBlockException checkBlock(PutLifecycleRequest request, ClusterState state) { return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE); } @Override public Optional<String> reservedStateHandlerName() { return Optional.of(ReservedLifecycleAction.NAME); } @Override public Set<String> modifiedKeys(PutLifecycleRequest request) { return Set.of(request.getPolicy().getName()); } }
TransportPutLifecycleAction
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/TrainedModelDefinition.java
{ "start": 1718, "end": 6752 }
class ____ implements ToXContentObject, Writeable, Accountable { private static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(TrainedModelDefinition.class); public static final String NAME = "trained_model_definition"; public static final ParseField TRAINED_MODEL = new ParseField("trained_model"); public static final ParseField PREPROCESSORS = new ParseField("preprocessors"); // These parsers follow the pattern that metadata is parsed leniently (to allow for enhancements), whilst config is parsed strictly public static final ObjectParser<TrainedModelDefinition.Builder, Void> LENIENT_PARSER = createParser(true); public static final ObjectParser<TrainedModelDefinition.Builder, Void> STRICT_PARSER = createParser(false); private static ObjectParser<TrainedModelDefinition.Builder, Void> createParser(boolean ignoreUnknownFields) { ObjectParser<TrainedModelDefinition.Builder, Void> parser = new ObjectParser<>( NAME, ignoreUnknownFields, TrainedModelDefinition.Builder::builderForParser ); parser.declareNamedObject( TrainedModelDefinition.Builder::setTrainedModel, (p, c, n) -> ignoreUnknownFields ? p.namedObject(LenientlyParsedTrainedModel.class, n, null) : p.namedObject(StrictlyParsedTrainedModel.class, n, null), TRAINED_MODEL ); parser.declareNamedObjects( TrainedModelDefinition.Builder::setPreProcessors, (p, c, n) -> ignoreUnknownFields ? p.namedObject(LenientlyParsedPreProcessor.class, n, PreProcessor.PreProcessorParseContext.DEFAULT) : p.namedObject(StrictlyParsedPreProcessor.class, n, PreProcessor.PreProcessorParseContext.DEFAULT), (trainedModelDefBuilder) -> trainedModelDefBuilder.setProcessorsInOrder(true), PREPROCESSORS ); return parser; } public static TrainedModelDefinition.Builder fromXContent(XContentParser parser, boolean lenient) throws IOException { return lenient ? LENIENT_PARSER.parse(parser, null) : STRICT_PARSER.parse(parser, null); } private final TrainedModel trainedModel; private final List<PreProcessor> preProcessors; private TrainedModelDefinition(TrainedModel trainedModel, List<PreProcessor> preProcessors) { this.trainedModel = ExceptionsHelper.requireNonNull(trainedModel, TRAINED_MODEL); this.preProcessors = preProcessors == null ? Collections.emptyList() : Collections.unmodifiableList(preProcessors); } public TrainedModelDefinition(StreamInput in) throws IOException { this.trainedModel = in.readNamedWriteable(TrainedModel.class); this.preProcessors = in.readNamedWriteableCollectionAsList(PreProcessor.class); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeNamedWriteable(trainedModel); out.writeNamedWriteableCollection(preProcessors); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); NamedXContentObjectHelper.writeNamedObjects( builder, params, false, TRAINED_MODEL.getPreferredName(), Collections.singletonList(trainedModel) ); NamedXContentObjectHelper.writeNamedObjects(builder, params, true, PREPROCESSORS.getPreferredName(), preProcessors); builder.endObject(); return builder; } public TrainedModel getTrainedModel() { return trainedModel; } public List<PreProcessor> getPreProcessors() { return preProcessors; } @Override public String toString() { return Strings.toString(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrainedModelDefinition that = (TrainedModelDefinition) o; return Objects.equals(trainedModel, that.trainedModel) && Objects.equals(preProcessors, that.preProcessors); } @Override public int hashCode() { return Objects.hash(trainedModel, preProcessors); } @Override public long ramBytesUsed() { long size = SHALLOW_SIZE; size += RamUsageEstimator.sizeOf(trainedModel); size += RamUsageEstimator.sizeOfCollection(preProcessors); return size; } @Override public Collection<Accountable> getChildResources() { List<Accountable> accountables = new ArrayList<>(preProcessors.size() + 2); accountables.add(Accountables.namedAccountable("trained_model", trainedModel)); for (PreProcessor preProcessor : preProcessors) { accountables.add(Accountables.namedAccountable("pre_processor_" + preProcessor.getName(), preProcessor)); } return accountables; } public static
TrainedModelDefinition
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/ConvertedBasicArrayType.java
{ "start": 859, "end": 3468 }
class ____<T,S,E> extends AbstractSingleColumnStandardBasicType<T> implements AdjustableBasicType<T>, BasicPluralType<T, E> { private final BasicType<E> baseDescriptor; private final String name; private final BasicValueConverter<T, S> converter; private final ValueExtractor<T> jdbcValueExtractor; private final ValueBinder<T> jdbcValueBinder; private final JdbcLiteralFormatter<T> jdbcLiteralFormatter; @SuppressWarnings("unchecked") public ConvertedBasicArrayType( BasicType<E> baseDescriptor, JdbcType arrayJdbcType, JavaType<T> arrayTypeDescriptor, BasicValueConverter<T, S> converter) { super( arrayJdbcType, arrayTypeDescriptor ); this.converter = converter; //TODO: these type casts look completely bogus (T==E[] and S are distinct array types) this.jdbcValueBinder = (ValueBinder<T>) arrayJdbcType.getBinder( converter.getRelationalJavaType() ); this.jdbcValueExtractor = (ValueExtractor<T>) arrayJdbcType.getExtractor( converter.getRelationalJavaType() ); this.jdbcLiteralFormatter = (JdbcLiteralFormatter<T>) arrayJdbcType.getJdbcLiteralFormatter( converter.getRelationalJavaType() ); this.baseDescriptor = baseDescriptor; this.name = determineArrayTypeName( baseDescriptor ); } @Override public BasicType<E> getElementType() { return baseDescriptor; } @Override public String getName() { return name; } @Override protected boolean registerUnderJavaType() { return true; } @Override public <X> BasicType<X> resolveIndicatedType(JdbcTypeIndicators indicators, JavaType<X> domainJtd) { // TODO: maybe fallback to some encoding by default if the DB doesn't support arrays natively? // also, maybe move that logic into the ArrayJdbcType //noinspection unchecked return (BasicType<X>) this; } @Override public BasicValueConverter<T, ?> getValueConverter() { return converter; } @Override public JavaType<?> getJdbcJavaType() { return converter.getRelationalJavaType(); } @Override public ValueExtractor<T> getJdbcValueExtractor() { return jdbcValueExtractor; } @Override public ValueBinder<T> getJdbcValueBinder() { return jdbcValueBinder; } @Override public JdbcLiteralFormatter<T> getJdbcLiteralFormatter() { return jdbcLiteralFormatter; } @Override public boolean equals(Object o) { return o == this || super.equals( o ) && o instanceof ConvertedBasicArrayType<?, ?, ?> that && Objects.equals( converter, that.converter ); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + converter.hashCode(); return result; } }
ConvertedBasicArrayType
java
google__guice
core/test/com/google/inject/spi/InjectionPointTest.java
{ "start": 12574, "end": 13530 }
class ____ { @Inject public static void staticMethod(@Named("a") String a) {} @Inject @Named("c") public static String staticField; @Inject @Named("c") public static String staticField2; @Inject public void instanceMethod(@Named("d") String d) {} @Inject @Named("f") public String instanceField; @Inject @Named("f") public String instanceField2; } public void testAddForParameterizedInjections() { TypeLiteral<?> type = new TypeLiteral<ParameterizedInjections<String>>() {}; InjectionPoint constructor = InjectionPoint.forConstructorOf(type); assertEquals( new Key<Map<String, String>>() {}, getOnlyElement(constructor.getDependencies()).getKey()); InjectionPoint field = getOnlyElement(InjectionPoint.forInstanceMethodsAndFields(type)); assertEquals(new Key<Set<String>>() {}, getOnlyElement(field.getDependencies()).getKey()); } static
HasInjections
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AmbiguousMethodReferenceTest.java
{ "start": 1260, "end": 1680 }
interface ____ {} // BUG: Diagnostic contains: c(A, D) B c(D d) { return null; } static B c(A a, D d) { return null; } } """) .doTest(); } @Test public void moreThan1PublicMethod() { testHelper .addSourceLines( "A.java", """ public
D
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/Lazy.java
{ "start": 966, "end": 3448 }
class ____ or indirectly annotated with {@link * org.springframework.stereotype.Component @Component} or on methods annotated with * {@link Bean @Bean}. * * <p>If this annotation is not present on a {@code @Component} or {@code @Bean} definition, * eager initialization will occur. If present and set to {@code true}, the {@code @Bean} or * {@code @Component} will not be initialized until referenced by another bean or explicitly * retrieved from the enclosing {@link org.springframework.beans.factory.BeanFactory * BeanFactory}. If present and set to {@code false}, the bean will be instantiated on * startup by bean factories that perform eager initialization of singletons. * * <p>If Lazy is present on a {@link Configuration @Configuration} class, this * indicates that all {@code @Bean} methods within that {@code @Configuration} * should be lazily initialized. If {@code @Lazy} is present and {@code false} on a {@code @Bean} * method within a {@code @Lazy}-annotated {@code @Configuration} class, this indicates * overriding the 'default lazy' behavior and that the bean should be eagerly initialized. * * <p>In addition to its role for component initialization, this annotation may also be placed * on injection points marked with {@link org.springframework.beans.factory.annotation.Autowired} * or {@link jakarta.inject.Inject}: In that context, it leads to the creation of a * lazy-resolution proxy for the affected dependency, caching it on first access in case of * a singleton or re-resolving it on every access otherwise. This is an alternative to using * {@link org.springframework.beans.factory.ObjectFactory} or {@link jakarta.inject.Provider}. * Please note that such a lazy-resolution proxy will always be injected; if the target * dependency does not exist, you will only be able to find out through an exception on * invocation. As a consequence, such an injection point results in unintuitive behavior * for optional dependencies. For a programmatic equivalent, allowing for lazy references * with more sophistication, consider {@link org.springframework.beans.factory.ObjectProvider}. * * @author Chris Beams * @author Juergen Hoeller * @since 3.0 * @see Primary * @see Bean * @see Configuration * @see org.springframework.stereotype.Component */ @Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @
directly
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/lookup/LookupAmbiguousTest.java
{ "start": 1685, "end": 1843 }
class ____ implements MyDependency { @Override public int getId() { return 1; } } @Singleton static
MyDependency1
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/service/MasterService.java
{ "start": 32776, "end": 37323 }
class ____ { private final ContextPreservingAckListener contextPreservingAckListener; private final TimeValue ackTimeout; private final CountDown countDown; private final DiscoveryNode masterNode; private final ThreadPool threadPool; private final long clusterStateVersion; private volatile Scheduler.Cancellable ackTimeoutCallback; private Exception lastFailure; TaskAckListener( ContextPreservingAckListener contextPreservingAckListener, long clusterStateVersion, DiscoveryNodes nodes, ThreadPool threadPool ) { this.contextPreservingAckListener = contextPreservingAckListener; this.ackTimeout = Objects.requireNonNull(contextPreservingAckListener.ackTimeout()); this.clusterStateVersion = clusterStateVersion; this.threadPool = threadPool; this.masterNode = nodes.getMasterNode(); int countDown = 0; for (DiscoveryNode node : nodes) { // we always wait for at least the master node if (node.equals(masterNode) || contextPreservingAckListener.mustAck(node)) { countDown++; } } logger.trace("expecting {} acknowledgements for cluster_state update (version: {})", countDown, clusterStateVersion); this.countDown = new CountDown(countDown + 1); // we also wait for onCommit to be called } public void onCommit(TimeValue commitTime) { if (ackTimeout.millis() < 0) { if (countDown.countDown()) { finish(); } return; } final TimeValue timeLeft = TimeValue.timeValueNanos(Math.max(0, ackTimeout.nanos() - commitTime.nanos())); if (timeLeft.nanos() == 0L) { onTimeout(); } else if (countDown.countDown()) { finish(); } else { this.ackTimeoutCallback = threadPool.schedule(this::onTimeout, timeLeft, threadPool.generic()); // re-check if onNodeAck has not completed while we were scheduling the timeout if (countDown.isCountedDown()) { ackTimeoutCallback.cancel(); } } } public void onNodeAck(DiscoveryNode node, @Nullable Exception e) { if (node.equals(masterNode) == false && contextPreservingAckListener.mustAck(node) == false) { return; } if (e == null) { logger.trace("ack received from node [{}], cluster_state update (version: {})", node, clusterStateVersion); } else { this.lastFailure = e; logger.debug(() -> format("ack received from node [%s], cluster_state update (version: %s)", node, clusterStateVersion), e); } if (countDown.countDown()) { finish(); } } private void finish() { logger.trace("all expected nodes acknowledged cluster_state update (version: {})", clusterStateVersion); if (ackTimeoutCallback != null) { ackTimeoutCallback.cancel(); } final var failure = lastFailure; if (failure == null) { contextPreservingAckListener.onAckSuccess(); } else { contextPreservingAckListener.onAckFailure(failure); } } public void onTimeout() { if (countDown.fastForward()) { logger.trace("timeout waiting for acknowledgement for cluster_state update (version: {})", clusterStateVersion); contextPreservingAckListener.onAckTimeout(); } } } /** * A wrapper around the collection of {@link TaskAckListener}s for a publication. */ private record CompositeTaskAckListener(List<TaskAckListener> listeners) implements ClusterStatePublisher.AckListener { @Override public void onCommit(TimeValue commitTime) { for (TaskAckListener listener : listeners) { listener.onCommit(commitTime); } } @Override public void onNodeAck(DiscoveryNode node, @Nullable Exception e) { for (TaskAckListener listener : listeners) { listener.onNodeAck(node, e); } } } private static
TaskAckListener
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/language/spel/SpelResourceTest.java
{ "start": 988, "end": 1649 }
class ____ extends ContextTestSupport { @Test public void testSpelResource() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived(7); template.sendBody("direct:start", 3); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .transform().spel("resource:classpath:myspel.txt") .to("mock:result"); } }; } }
SpelResourceTest
java
apache__kafka
clients/clients-integration-tests/src/test/java/org/apache/kafka/clients/consumer/ShareConsumerTest.java
{ "start": 218040, "end": 225674 }
class ____<K, V> implements Runnable { public static final int POLL_TIMEOUT_MS = 15000; public static final int MAX_DELIVERY_COUNT = ShareGroupConfig.SHARE_GROUP_DELIVERY_COUNT_LIMIT_DEFAULT; private final String topicName; private final Map<String, Object> configs = new HashMap<>(); private final ClientState state = new ClientState(); private final Predicate<ConsumerRecords<K, V>> exitCriteria; private final BiConsumer<ShareConsumer<K, V>, ConsumerRecord<K, V>> processFunc; ComplexShareConsumer( String bootstrapServers, String topicName, String groupId, Map<String, Object> additionalProperties ) { this( bootstrapServers, topicName, groupId, additionalProperties, records -> records.count() == 0, (consumer, record) -> { short deliveryCountBeforeAccept = (short) ((record.offset() + record.offset() / (MAX_DELIVERY_COUNT + 2)) % (MAX_DELIVERY_COUNT + 2)); if (deliveryCountBeforeAccept == 0) { consumer.acknowledge(record, AcknowledgeType.REJECT); } else if (record.deliveryCount().get() == deliveryCountBeforeAccept) { consumer.acknowledge(record, AcknowledgeType.ACCEPT); } else { consumer.acknowledge(record, AcknowledgeType.RELEASE); } } ); } ComplexShareConsumer( String bootstrapServers, String topicName, String groupId, Map<String, Object> additionalProperties, Predicate<ConsumerRecords<K, V>> exitCriteria, BiConsumer<ShareConsumer<K, V>, ConsumerRecord<K, V>> processFunc ) { this.exitCriteria = Objects.requireNonNull(exitCriteria); this.processFunc = Objects.requireNonNull(processFunc); this.topicName = topicName; this.configs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); this.configs.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); this.configs.putAll(additionalProperties); this.configs.putIfAbsent(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class); this.configs.putIfAbsent(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class); } @Override public void run() { try (ShareConsumer<K, V> consumer = new KafkaShareConsumer<>(configs)) { consumer.subscribe(Set.of(this.topicName)); while (!state.done().get()) { ConsumerRecords<K, V> records = consumer.poll(Duration.ofMillis(POLL_TIMEOUT_MS)); state.count().addAndGet(records.count()); if (exitCriteria.test(records)) { state.done().set(true); } records.forEach(record -> processFunc.accept(consumer, record)); } } } boolean isDone() { return state.done().get(); } int recordsRead() { return state.count().get(); } } private void shutdownExecutorService(ExecutorService service) { service.shutdown(); try { if (!service.awaitTermination(5L, TimeUnit.SECONDS)) { service.shutdownNow(); } } catch (Exception e) { service.shutdownNow(); Thread.currentThread().interrupt(); } } private ConsumerRecords<byte[], byte[]> waitedPoll( ShareConsumer<byte[], byte[]> shareConsumer, long pollMs, int recordCount ) { return waitedPoll(shareConsumer, pollMs, recordCount, false, "", List.of()); } private ConsumerRecords<byte[], byte[]> waitedPoll( ShareConsumer<byte[], byte[]> shareConsumer, long pollMs, int recordCount, boolean checkAssignment, String groupId, List<TopicPartition> tps ) { AtomicReference<ConsumerRecords<byte[], byte[]>> recordsAtomic = new AtomicReference<>(); try { waitForCondition(() -> { ConsumerRecords<byte[], byte[]> recs = shareConsumer.poll(Duration.ofMillis(pollMs)); recordsAtomic.set(recs); if (checkAssignment) { waitForAssignment(groupId, tps); } return recs.count() == recordCount; }, DEFAULT_MAX_WAIT_MS, 500L, () -> "failed to get records" ); return recordsAtomic.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } } private void validateExpectedRecordsInEachPollAndRelease( ShareConsumer<byte[], byte[]> shareConsumer, int startOffset, int lastOffset, int expectedRecordsInEachPoll ) { validateExpectedRecordsInEachPollAndAcknowledge(shareConsumer, startOffset, lastOffset, expectedRecordsInEachPoll, AcknowledgeType.RELEASE); } private void validateExpectedRecordsInEachPollAndAcknowledge( ShareConsumer<byte[], byte[]> shareConsumer, int startOffset, int lastOffset, int expectedRecordsInEachPoll, AcknowledgeType acknowledgeType ) { for (int i = startOffset; i < lastOffset; i = i + expectedRecordsInEachPoll) { ConsumerRecords<byte[], byte[]> records = waitedPoll(shareConsumer, 2500L, expectedRecordsInEachPoll); assertEquals(expectedRecordsInEachPoll, records.count()); // Verify the first offset of the fetched records. assertEquals(i, records.iterator().next().offset()); records.forEach(record -> shareConsumer.acknowledge(record, acknowledgeType)); Map<TopicIdPartition, Optional<KafkaException>> result = shareConsumer.commitSync(); assertEquals(1, result.size()); assertEquals(Optional.empty(), result.get(new TopicIdPartition(tpId, tp.partition(), tp.topic()))); } } private void waitForAssignment(String groupId, List<TopicPartition> tps) { try { waitForCondition(() -> { try (Admin admin = createAdminClient()) { Collection<ShareMemberDescription> members = admin.describeShareGroups(List.of(groupId), new DescribeShareGroupsOptions().includeAuthorizedOperations(true) ).describedGroups().get(groupId).get().members(); Set<TopicPartition> assigned = new HashSet<>(); members.forEach(desc -> { if (desc.assignment() != null) { assigned.addAll(desc.assignment().topicPartitions()); } }); return assigned.containsAll(tps); } catch (Exception e) { throw new RuntimeException(e); } }, DEFAULT_MAX_WAIT_MS, 1000L, () -> "tps not assigned to members" ); } catch (Exception e) { throw new RuntimeException(e); } } public static
ComplexShareConsumer
java
spring-projects__spring-security
access/src/main/java/org/springframework/security/access/expression/method/PreInvocationExpressionAttribute.java
{ "start": 1133, "end": 2458 }
class ____ extends AbstractExpressionBasedMethodConfigAttribute implements PreInvocationAttribute { private final String filterTarget; PreInvocationExpressionAttribute(String filterExpression, String filterTarget, String authorizeExpression) throws ParseException { super(filterExpression, authorizeExpression); this.filterTarget = filterTarget; } PreInvocationExpressionAttribute(@Nullable Expression filterExpression, String filterTarget, Expression authorizeExpression) throws ParseException { super(filterExpression, authorizeExpression); this.filterTarget = filterTarget; } /** * The parameter name of the target argument (must be a Collection) to which filtering * will be applied. * @return the method parameter name */ String getFilterTarget() { return this.filterTarget; } @Override public String toString() { StringBuilder sb = new StringBuilder(); Expression authorize = getAuthorizeExpression(); Expression filter = getFilterExpression(); sb.append("[authorize: '").append((authorize != null) ? authorize.getExpressionString() : "null"); sb.append("', filter: '").append((filter != null) ? filter.getExpressionString() : "null"); sb.append("', filterTarget: '").append(this.filterTarget).append("']"); return sb.toString(); } }
PreInvocationExpressionAttribute
java
netty__netty
codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultLastStompContentSubframe.java
{ "start": 795, "end": 2211 }
class ____ extends DefaultStompContentSubframe implements LastStompContentSubframe { public DefaultLastStompContentSubframe(ByteBuf content) { super(content); } @Override public LastStompContentSubframe copy() { return (LastStompContentSubframe) super.copy(); } @Override public LastStompContentSubframe duplicate() { return (LastStompContentSubframe) super.duplicate(); } @Override public LastStompContentSubframe retainedDuplicate() { return (LastStompContentSubframe) super.retainedDuplicate(); } @Override public LastStompContentSubframe replace(ByteBuf content) { return new DefaultLastStompContentSubframe(content); } @Override public DefaultLastStompContentSubframe retain() { super.retain(); return this; } @Override public LastStompContentSubframe retain(int increment) { super.retain(increment); return this; } @Override public LastStompContentSubframe touch() { super.touch(); return this; } @Override public LastStompContentSubframe touch(Object hint) { super.touch(hint); return this; } @Override public String toString() { return "DefaultLastStompContent{" + "decoderResult=" + decoderResult() + '}'; } }
DefaultLastStompContentSubframe
java
quarkusio__quarkus
extensions/mailer/runtime/src/main/java/io/quarkus/mailer/runtime/MailersBuildTimeConfig.java
{ "start": 325, "end": 552 }
interface ____ { /** * Caches data from attachment's Stream to a temporary file. * It tries to delete it after sending email. */ @WithDefault("false") boolean cacheAttachments(); }
MailersBuildTimeConfig
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/lock/internal/CockroachLockingSupport.java
{ "start": 989, "end": 3984 }
class ____ implements LockingSupport, LockingSupport.Metadata, ConnectionLockTimeoutStrategy { public static final CockroachLockingSupport COCKROACH_LOCKING_SUPPORT = new CockroachLockingSupport( false ); public static final CockroachLockingSupport LEGACY_COCKROACH_LOCKING_SUPPORT = new CockroachLockingSupport( true ); private final boolean supportsNoWait; private final RowLockStrategy rowLockStrategy; public CockroachLockingSupport(boolean isLegacy) { rowLockStrategy = isLegacy ? RowLockStrategy.NONE : RowLockStrategy.TABLE; supportsNoWait = !isLegacy; } @Override public Metadata getMetadata() { return this; } @Override public RowLockStrategy getWriteRowLockStrategy() { return rowLockStrategy; } @Override public LockTimeoutType getLockTimeoutType(Timeout timeout) { // [1] See https://www.cockroachlabs.com/docs/stable/select-for-update.html#wait-policies // todo (db-locking) : to me, reading that doc, Cockroach *does* support skip-locked. // figure out why we report false here. version? return switch (timeout.milliseconds()) { case WAIT_FOREVER_MILLI -> QUERY; case NO_WAIT_MILLI -> supportsNoWait ? QUERY : LockTimeoutType.NONE; // Due to https://github.com/cockroachdb/cockroach/issues/88995, locking doesn't work properly // without certain configuration options and hence skipping locked rows also doesn't work correctly. case SKIP_LOCKED_MILLI -> LockTimeoutType.NONE; // it does not, however, support WAIT as part of for-update, but does support a connection-level lock_timeout setting default -> CONNECTION; }; } @Override public OuterJoinLockingType getOuterJoinLockingType() { return OuterJoinLockingType.UNSUPPORTED; } @Override public ConnectionLockTimeoutStrategy getConnectionLockTimeoutStrategy() { return this; } @Override public Level getSupportedLevel() { return ConnectionLockTimeoutStrategy.Level.SUPPORTED; } @Override public Timeout getLockTimeout(Connection connection, SessionFactoryImplementor factory) { return Helper.getLockTimeout( "show lock_timeout", (resultSet) -> { final int millis = resultSet.getInt( 1 ); return switch ( millis ) { case 0 -> WAIT_FOREVER; default -> Timeout.milliseconds( millis ); }; }, connection, factory ); } @Override public void setLockTimeout( Timeout timeout, Connection connection, SessionFactoryImplementor factory) { Helper.setLockTimeout( timeout, (t) -> { final int milliseconds = timeout.milliseconds(); if ( milliseconds == SKIP_LOCKED_MILLI ) { throw new HibernateException( "Connection lock-timeout does not accept skip-locked" ); } if ( milliseconds == NO_WAIT_MILLI ) { throw new HibernateException( "Connection lock-timeout does not accept no-wait" ); } return milliseconds == WAIT_FOREVER_MILLI ? 0 : milliseconds; }, "set lock_timeout = %s", connection, factory ); } }
CockroachLockingSupport
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/source/presencecheck/spi/CollectionWithNonDirectMapper.java
{ "start": 1011, "end": 1400 }
class ____ { private final Collection<PlayerSource> players; public Source(Collection<PlayerSource> players) { this.players = players; } public Collection<PlayerSource> getPlayers() { return players; } public boolean hasPlayers() { return players != null && !players.isEmpty(); } }
Source
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AbfsPermission.java
{ "start": 1060, "end": 3896 }
class ____ extends FsPermission { private static final int STICKY_BIT_OCTAL_VALUE = 01000; private final boolean aclBit; public AbfsPermission(Short aShort, boolean aclBitStatus) { super(aShort); this.aclBit = aclBitStatus; } public AbfsPermission(FsAction u, FsAction g, FsAction o) { super(u, g, o, false); this.aclBit = false; } /** * Returns true if there is also an ACL (access control list). * * @return boolean true if there is also an ACL (access control list). * @deprecated Get acl bit from the {@link org.apache.hadoop.fs.FileStatus} * object. */ public boolean getAclBit() { return aclBit; } @Override public boolean equals(Object obj) { if (obj instanceof FsPermission) { FsPermission that = (FsPermission) obj; return this.getUserAction() == that.getUserAction() && this.getGroupAction() == that.getGroupAction() && this.getOtherAction() == that.getOtherAction() && this.getStickyBit() == that.getStickyBit(); } return false; } /** * Create a AbfsPermission from a abfs symbolic permission string * @param abfsSymbolicPermission e.g. "rw-rw-rw-+" / "rw-rw-rw-" * @return a permission object for the provided string representation */ public static AbfsPermission valueOf(final String abfsSymbolicPermission) { if (StringUtils.isEmpty(abfsSymbolicPermission)) { return null; } final boolean isExtendedAcl = abfsSymbolicPermission.charAt(abfsSymbolicPermission.length() - 1) == '+'; final String abfsRawSymbolicPermission = isExtendedAcl ? abfsSymbolicPermission.substring(0, abfsSymbolicPermission.length() - 1) : abfsSymbolicPermission; int n = 0; for (int i = 0; i < abfsRawSymbolicPermission.length(); i++) { n = n << 1; char c = abfsRawSymbolicPermission.charAt(i); n += (c == '-' || c == 'T' || c == 'S') ? 0: 1; } // Add sticky bit value if set if (abfsRawSymbolicPermission.charAt(abfsRawSymbolicPermission.length() - 1) == 't' || abfsRawSymbolicPermission.charAt(abfsRawSymbolicPermission.length() - 1) == 'T') { n += STICKY_BIT_OCTAL_VALUE; } return new AbfsPermission((short) n, isExtendedAcl); } /** * Check whether abfs symbolic permission string is a extended Acl * @param abfsSymbolicPermission e.g. "rw-rw-rw-+" / "rw-rw-rw-" * @return true if the permission string indicates the existence of an * extended ACL; otherwise false. */ public static boolean isExtendedAcl(final String abfsSymbolicPermission) { if (StringUtils.isEmpty(abfsSymbolicPermission)) { return false; } return abfsSymbolicPermission.charAt(abfsSymbolicPermission.length() - 1) == '+'; } @Override public int hashCode() { return toShort(); } }
AbfsPermission
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FilterDefinitionBinder.java
{ "start": 707, "end": 2852 }
class ____ { /** * Handling for a {@code <filter-def/>} declaration. * * @param context Access to information relative to the mapping document containing this binding * @param filterDefinitionMapping The {@code <filter-def/>} JAXB mapping */ static void processFilterDefinition( HbmLocalMetadataBuildingContext context, JaxbHbmFilterDefinitionType filterDefinitionMapping) { Map<String, JdbcMapping> parameterMap = null; final String condition = filterDefinitionMapping.getCondition(); final var collector = context.getMetadataCollector(); final var basicTypeRegistry = collector.getTypeConfiguration().getBasicTypeRegistry(); for ( var content : filterDefinitionMapping.getContent() ) { if ( content instanceof String string ) { if ( isNotBlank( string ) ) { if ( condition != null && BOOT_LOGGER.isDebugEnabled() ) { BOOT_LOGGER.filterDefDefinedMultipleConditions( filterDefinitionMapping.getName(), context.getOrigin().toString() ); } } } else { final var parameterMapping = filterParameterType( context, content ); if ( parameterMap == null ) { parameterMap = new HashMap<>(); } parameterMap.put( parameterMapping.getParameterName(), basicTypeRegistry.getRegisteredType( parameterMapping.getParameterValueTypeName() ) ); } } collector.addFilterDefinition( new FilterDefinition( filterDefinitionMapping.getName(), condition, parameterMap ) ); BOOT_LOGGER.processedFilterDefinition( filterDefinitionMapping.getName() ); } private static JaxbHbmFilterParameterType filterParameterType( HbmLocalMetadataBuildingContext context, Serializable content) { if ( content instanceof JaxbHbmFilterParameterType filterParameterType ) { return filterParameterType; } else if ( content instanceof JAXBElement ) { final var jaxbElement = (JAXBElement<JaxbHbmFilterParameterType>) content; return jaxbElement.getValue(); } else { throw new MappingException( "Unable to decipher filter-def content type [" + content.getClass().getName() + "]", context.getOrigin() ); } } }
FilterDefinitionBinder
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/FieldAliasMapper.java
{ "start": 1067, "end": 1181 }
class ____ extends Mapper { public static final String CONTENT_TYPE = "alias"; public static
FieldAliasMapper
java
spring-projects__spring-boot
module/spring-boot-jersey/src/test/java/org/springframework/boot/jersey/autoconfigure/actuate/web/JerseySameManagementContextConfigurationTests.java
{ "start": 1824, "end": 4526 }
class ____ { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); @Test void autoConfigurationIsConditionalOnServletWebApplication() { ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JerseySameManagementContextConfiguration.class)); contextRunner .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test void autoConfigurationIsConditionalOnClassResourceConfig() { this.contextRunner.withClassLoader(new FilteredClassLoader(ResourceConfig.class)) .run((context) -> assertThat(context).doesNotHaveBean(JerseySameManagementContextConfiguration.class)); } @Test void jerseyApplicationPathIsAutoConfiguredWhenNeeded() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(DefaultJerseyApplicationPath.class)); } @Test void jerseyApplicationPathIsConditionalOnMissingBean() { this.contextRunner.withUserConfiguration(ConfigWithJerseyApplicationPath.class).run((context) -> { assertThat(context).hasSingleBean(JerseyApplicationPath.class); assertThat(context).hasBean("testJerseyApplicationPath"); }); } @Test void existingResourceConfigBeanShouldNotAutoConfigureRelatedBeans() { this.contextRunner.withUserConfiguration(ConfigWithResourceConfig.class).run((context) -> { assertThat(context).hasSingleBean(ResourceConfig.class); assertThat(context).doesNotHaveBean(JerseyApplicationPath.class); assertThat(context).doesNotHaveBean(ServletRegistrationBean.class); assertThat(context).hasBean("customResourceConfig"); }); } @Test @SuppressWarnings("unchecked") void servletRegistrationBeanIsAutoConfiguredWhenNeeded() { this.contextRunner.withPropertyValues("spring.jersey.application-path=/jersey").run((context) -> { ServletRegistrationBean<ServletContainer> bean = context.getBean(ServletRegistrationBean.class); assertThat(bean.getUrlMappings()).containsExactly("/jersey/*"); }); } @Test void resourceConfigIsCustomizedWithResourceConfigCustomizerBean() { this.contextRunner.withUserConfiguration(CustomizerConfiguration.class).run((context) -> { assertThat(context).hasSingleBean(ResourceConfig.class); ResourceConfig config = context.getBean(ResourceConfig.class); ManagementContextResourceConfigCustomizer customizer = context .getBean(ManagementContextResourceConfigCustomizer.class); then(customizer).should().customize(config); }); } @Configuration(proxyBeanMethods = false) static
JerseySameManagementContextConfigurationTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest3.java
{ "start": 298, "end": 766 }
class ____ extends TestCase { public void test_array() throws Exception { Model model = new Model(); model.item = new Item(); model.item.id = 1001; String text = JSON.toJSONString(model); Assert.assertEquals("{\"item\":[1001]}", text); Model model2 = JSON.parseObject(text, Model.class); Assert.assertEquals(model2.item.id, model.item.id); } public static
BeanToArrayTest3
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/examples/ConnectToRedisClusterSSL.java
{ "start": 220, "end": 834 }
class ____ { public static void main(String[] args) { // Syntax: rediss://[password@]host[:port] RedisURI redisURI = RedisURI.create("rediss://password@localhost:7379"); redisURI.setVerifyPeer(false); // depending on your setup, you might want to disable peer verification RedisClusterClient redisClient = RedisClusterClient.create(redisURI); StatefulRedisClusterConnection<String, String> connection = redisClient.connect(); System.out.println("Connected to Redis"); connection.close(); redisClient.shutdown(); } }
ConnectToRedisClusterSSL
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/index/engine/InternalEngineMergeIT.java
{ "start": 1787, "end": 7764 }
class ____ extends ESIntegTestCase { private boolean useThreadPoolMerging; @Override protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) { useThreadPoolMerging = randomBoolean(); Settings.Builder settings = Settings.builder().put(super.nodeSettings(nodeOrdinal, otherSettings)); settings.put(ThreadPoolMergeScheduler.USE_THREAD_POOL_MERGE_SCHEDULER_SETTING.getKey(), useThreadPoolMerging); return settings.build(); } public void testMergesHappening() throws Exception { final int numOfShards = randomIntBetween(1, 5); // some settings to keep num segments low assertAcked(prepareCreate("test").setSettings(indexSettings(numOfShards, 0).build())); long id = 0; final int rounds = scaledRandomIntBetween(50, 300); logger.info("Starting rounds [{}] ", rounds); for (int i = 0; i < rounds; ++i) { final int numDocs = scaledRandomIntBetween(100, 1000); BulkRequestBuilder request = client().prepareBulk(); for (int j = 0; j < numDocs; ++j) { request.add( new IndexRequest("test").id(Long.toString(id++)) .source(jsonBuilder().startObject().field("l", randomLong()).endObject()) ); } BulkResponse response = request.get(); refresh(); assertNoFailures(response); IndicesStatsResponse stats = indicesAdmin().prepareStats("test").setSegments(true).setMerge(true).get(); logger.info( "index round [{}] - segments {}, total merges {}, current merge {}", i, stats.getPrimaries().getSegments().getCount(), stats.getPrimaries().getMerge().getTotal(), stats.getPrimaries().getMerge().getCurrent() ); } final long upperNumberSegments = 2 * numOfShards * 10; assertBusy(() -> { IndicesStatsResponse stats = indicesAdmin().prepareStats().setSegments(true).setMerge(true).get(); logger.info( "numshards {}, segments {}, total merges {}, current merge {}", numOfShards, stats.getPrimaries().getSegments().getCount(), stats.getPrimaries().getMerge().getTotal(), stats.getPrimaries().getMerge().getCurrent() ); long current = stats.getPrimaries().getMerge().getCurrent(); long count = stats.getPrimaries().getSegments().getCount(); assertThat(count, lessThan(upperNumberSegments)); assertThat(current, equalTo(0L)); }); IndicesStatsResponse stats = indicesAdmin().prepareStats().setSegments(true).setMerge(true).get(); logger.info( "numshards {}, segments {}, total merges {}, current merge {}", numOfShards, stats.getPrimaries().getSegments().getCount(), stats.getPrimaries().getMerge().getTotal(), stats.getPrimaries().getMerge().getCurrent() ); long count = stats.getPrimaries().getSegments().getCount(); assertThat(count, lessThanOrEqualTo(upperNumberSegments)); } public void testMergesUseTheMergeThreadPool() throws Exception { final String indexName = randomIdentifier(); createIndex(indexName, indexSettings(randomIntBetween(1, 3), 0).build()); long id = 0; final int minMerges = randomIntBetween(1, 5); long totalDocs = 0; while (true) { int docs = randomIntBetween(100, 200); totalDocs += docs; BulkRequestBuilder request = client().prepareBulk(); for (int j = 0; j < docs; ++j) { request.add( new IndexRequest(indexName).id(Long.toString(id++)) .source(jsonBuilder().startObject().field("l", randomLong()).endObject()) ); } BulkResponse response = request.get(); assertNoFailures(response); refresh(indexName); var mergesResponse = client().admin().indices().prepareStats(indexName).clear().setMerge(true).get(); var primaries = mergesResponse.getIndices().get(indexName).getPrimaries(); if (primaries.merge.getTotal() >= minMerges) { break; } } forceMerge(); refresh(indexName); // after a force merge there should only be 1 segment per shard var shardsWithMultipleSegments = getShardSegments().stream() .filter(shardSegments -> shardSegments.getSegments().size() > 1) .toList(); assertTrue("there are shards with multiple segments " + shardsWithMultipleSegments, shardsWithMultipleSegments.isEmpty()); final long expectedTotalDocs = totalDocs; assertHitCount(prepareSearch(indexName).setQuery(QueryBuilders.matchAllQuery()).setTrackTotalHits(true), expectedTotalDocs); IndicesStatsResponse indicesStats = client().admin().indices().prepareStats(indexName).setMerge(true).get(); long mergeCount = indicesStats.getIndices().get(indexName).getPrimaries().merge.getTotal(); NodesStatsResponse nodesStatsResponse = client().admin().cluster().prepareNodesStats().setThreadPool(true).get(); assertThat(nodesStatsResponse.getNodes().size(), equalTo(1)); NodeStats nodeStats = nodesStatsResponse.getNodes().get(0); if (useThreadPoolMerging) { assertThat( nodeStats.getThreadPool().stats().stream().filter(s -> ThreadPool.Names.MERGE.equals(s.name())).findAny().get().completed(), equalTo(mergeCount) ); } else { assertTrue(nodeStats.getThreadPool().stats().stream().filter(s -> ThreadPool.Names.MERGE.equals(s.name())).findAny().isEmpty()); } } }
InternalEngineMergeIT
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jLogEvent.java
{ "start": 14106, "end": 15409 }
class ____ of the caller. * @param level The logging Level. * @param message The Message. * @param properties the properties to be merged with ThreadContext key-value pairs into the event's ReadOnlyStringMap. * @param t A Throwable or null. */ // This constructor is called from LogEventFactories. public Log4jLogEvent( final String loggerName, final Marker marker, final String loggerFQCN, final Level level, final Message message, final List<Property> properties, final Throwable t) { this( loggerName, marker, loggerFQCN, level, message, t, createContextData(properties), ThreadContext.getDepth() == 0 ? null : ThreadContext.cloneStack(), // mutable copy 0, // thread id null, // thread name 0, // thread priority null, // StackTraceElement source CLOCK, // nanoClock.nanoTime()); } /** * Constructor. * @param loggerName The name of the Logger. * @param marker The Marker or null. * @param loggerFQCN The fully qualified
name
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/shard/ShardFieldStats.java
{ "start": 1991, "end": 4433 }
class ____ { static final String SHARD_FIELD_STATS = "shard_field_stats"; static final String NUM_SEGMENTS = "num_segments"; static final String TOTAL_FIELDS = "total_fields"; static final String FIELD_USAGES = "field_usages"; static final String POSTINGS_IN_MEMORY_BYTES = "postings_in_memory_bytes"; static final String POSTINGS_IN_MEMORY = "postings_in_memory"; static final String LIVE_DOCS_BYTES = "live_docs_bytes"; static final String LIVE_DOCS = "live_docs"; } public static final ConstructingObjectParser<ShardFieldStats, Void> PARSER = new ConstructingObjectParser<>( "shard_field_stats", true, args -> (ShardFieldStats) args[0] ); protected static final ConstructingObjectParser<ShardFieldStats, Void> SHARD_FIELD_STATS_PARSER = new ConstructingObjectParser<>( "shard_field_stats_fields", true, args -> new ShardFieldStats((int) args[0], (int) args[1], (long) args[2], (long) args[3], (long) args[4]) ); static { PARSER.declareObject(constructorArg(), SHARD_FIELD_STATS_PARSER, new ParseField(Fields.SHARD_FIELD_STATS)); } static { SHARD_FIELD_STATS_PARSER.declareInt(constructorArg(), new ParseField(Fields.NUM_SEGMENTS)); SHARD_FIELD_STATS_PARSER.declareInt(constructorArg(), new ParseField(Fields.TOTAL_FIELDS)); SHARD_FIELD_STATS_PARSER.declareLong(constructorArg(), new ParseField(Fields.FIELD_USAGES)); SHARD_FIELD_STATS_PARSER.declareLong(constructorArg(), new ParseField(Fields.POSTINGS_IN_MEMORY_BYTES)); SHARD_FIELD_STATS_PARSER.declareLong(constructorArg(), new ParseField(Fields.LIVE_DOCS_BYTES)); } @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(Fields.SHARD_FIELD_STATS); builder.field(Fields.NUM_SEGMENTS, numSegments); builder.field(Fields.TOTAL_FIELDS, totalFields); builder.field(Fields.FIELD_USAGES, fieldUsages); builder.humanReadableField( Fields.POSTINGS_IN_MEMORY_BYTES, Fields.POSTINGS_IN_MEMORY, ByteSizeValue.ofBytes(postingsInMemoryBytes) ); builder.humanReadableField(Fields.LIVE_DOCS_BYTES, Fields.LIVE_DOCS, ByteSizeValue.ofBytes(liveDocsBytes)); builder.endObject(); return builder; } }
Fields
java
apache__rocketmq
test/src/test/java/org/apache/rocketmq/test/client/producer/batch/BatchSendIT.java
{ "start": 2424, "end": 15132 }
class ____ extends BaseConf { private static Logger logger = LoggerFactory.getLogger(TagMessageWith1ConsumerIT.class); private String topic = null; private Random random = new Random(); @Before public void setUp() { topic = initTopic(); logger.info(String.format("user topic[%s]!", topic)); } @After public void tearDown() { super.shutdown(); } @Test public void testBatchSend_ViewMessage() throws Exception { Assert.assertTrue(brokerController1.getMessageStore() instanceof DefaultMessageStore); Assert.assertTrue(brokerController2.getMessageStore() instanceof DefaultMessageStore); List<Message> messageList = new ArrayList<>(); int batchNum = 100; for (int i = 0; i < batchNum; i++) { messageList.add(new Message(topic, RandomUtils.getStringByUUID().getBytes())); } DefaultMQProducer producer = ProducerFactory.getRMQProducer(NAMESRV_ADDR); removeBatchUniqueId(producer); SendResult sendResult = producer.send(messageList); Assert.assertEquals(SendStatus.SEND_OK, sendResult.getSendStatus()); String[] offsetIds = sendResult.getOffsetMsgId().split(","); String[] msgIds = sendResult.getMsgId().split(","); Assert.assertEquals(messageList.size(), offsetIds.length); Assert.assertEquals(messageList.size(), msgIds.length); Thread.sleep(2000); for (int i = 0; i < 3; i++) { producer.viewMessage(topic, offsetIds[random.nextInt(batchNum)]); } for (int i = 0; i < 3; i++) { producer.viewMessage(topic, msgIds[random.nextInt(batchNum)]); } } @Test public void testBatchSend_SysInnerBatch() throws Exception { waitBrokerRegistered(NAMESRV_ADDR, CLUSTER_NAME, BROKER_NUM); String batchTopic = UUID.randomUUID().toString(); IntegrationTestBase.initTopic(batchTopic, NAMESRV_ADDR, CLUSTER_NAME, CQType.BatchCQ); Assert.assertEquals(CQType.BatchCQ.toString(), brokerController1.getTopicConfigManager().getTopicConfigTable().get(batchTopic).getAttributes().get(TopicAttributes.QUEUE_TYPE_ATTRIBUTE.getName())); Assert.assertEquals(CQType.BatchCQ.toString(), brokerController2.getTopicConfigManager().getTopicConfigTable().get(batchTopic).getAttributes().get(TopicAttributes.QUEUE_TYPE_ATTRIBUTE.getName())); Assert.assertEquals(CQType.BatchCQ.toString(), brokerController3.getTopicConfigManager().getTopicConfigTable().get(batchTopic).getAttributes().get(TopicAttributes.QUEUE_TYPE_ATTRIBUTE.getName())); Assert.assertEquals(8, brokerController1.getTopicConfigManager().getTopicConfigTable().get(batchTopic).getReadQueueNums()); Assert.assertEquals(8, brokerController2.getTopicConfigManager().getTopicConfigTable().get(batchTopic).getReadQueueNums()); Assert.assertEquals(8, brokerController3.getTopicConfigManager().getTopicConfigTable().get(batchTopic).getReadQueueNums()); Assert.assertEquals(-1, brokerController1.getMessageStore().getMinOffsetInQueue(batchTopic, 0)); Assert.assertEquals(-1, brokerController2.getMessageStore().getMinOffsetInQueue(batchTopic, 0)); Assert.assertEquals(-1, brokerController3.getMessageStore().getMinOffsetInQueue(batchTopic, 0)); Assert.assertEquals(0, brokerController1.getMessageStore().getMaxOffsetInQueue(batchTopic, 0)); Assert.assertEquals(0, brokerController2.getMessageStore().getMaxOffsetInQueue(batchTopic, 0)); Assert.assertEquals(0, brokerController3.getMessageStore().getMaxOffsetInQueue(batchTopic, 0)); DefaultMQProducer producer = ProducerFactory.getRMQProducer(NAMESRV_ADDR); MessageQueue messageQueue = producer.fetchPublishMessageQueues(batchTopic).iterator().next(); int batchCount = 10; int batchNum = 10; for (int i = 0; i < batchCount; i++) { List<Message> messageList = new ArrayList<>(); for (int j = 0; j < batchNum; j++) { messageList.add(new Message(batchTopic, RandomUtils.getStringByUUID().getBytes())); } SendResult sendResult = producer.send(messageList, messageQueue); Assert.assertEquals(SendStatus.SEND_OK, sendResult.getSendStatus()); Assert.assertEquals(messageQueue.getQueueId(), sendResult.getMessageQueue().getQueueId()); Assert.assertEquals(i * batchNum, sendResult.getQueueOffset()); Assert.assertEquals(1, sendResult.getMsgId().split(",").length); } Thread.sleep(300); { DefaultMQPullConsumer defaultMQPullConsumer = ConsumerFactory.getRMQPullConsumer(NAMESRV_ADDR, "group"); PullResult pullResult = defaultMQPullConsumer.pullBlockIfNotFound(messageQueue, "*", 5, batchCount * batchNum); Assert.assertEquals(PullStatus.FOUND, pullResult.getPullStatus()); Assert.assertEquals(0, pullResult.getMinOffset()); Assert.assertEquals(batchCount * batchNum, pullResult.getMaxOffset()); Assert.assertEquals(batchCount * batchNum, pullResult.getMsgFoundList().size()); MessageExt first = pullResult.getMsgFoundList().get(0); for (int i = 0; i < pullResult.getMsgFoundList().size(); i++) { MessageExt messageExt = pullResult.getMsgFoundList().get(i); if (i % batchNum == 0) { first = messageExt; } Assert.assertEquals(i, messageExt.getQueueOffset()); Assert.assertEquals(batchTopic, messageExt.getTopic()); Assert.assertEquals(messageQueue.getQueueId(), messageExt.getQueueId()); Assert.assertEquals(first.getBornHostString(), messageExt.getBornHostString()); Assert.assertEquals(first.getBornHostNameString(), messageExt.getBornHostNameString()); Assert.assertEquals(first.getBornTimestamp(), messageExt.getBornTimestamp()); Assert.assertEquals(first.getStoreTimestamp(), messageExt.getStoreTimestamp()); } } } @Test public void testBatchSend_SysOuterBatch() throws Exception { Assert.assertTrue(brokerController1.getMessageStore() instanceof DefaultMessageStore); Assert.assertTrue(brokerController2.getMessageStore() instanceof DefaultMessageStore); Assert.assertTrue(brokerController3.getMessageStore() instanceof DefaultMessageStore); String batchTopic = UUID.randomUUID().toString(); IntegrationTestBase.initTopic(batchTopic, NAMESRV_ADDR, CLUSTER_NAME, CQType.SimpleCQ); Assert.assertEquals(8, brokerController1.getTopicConfigManager().getTopicConfigTable().get(batchTopic).getReadQueueNums()); Assert.assertEquals(8, brokerController2.getTopicConfigManager().getTopicConfigTable().get(batchTopic).getReadQueueNums()); Assert.assertEquals(8, brokerController3.getTopicConfigManager().getTopicConfigTable().get(batchTopic).getReadQueueNums()); Assert.assertEquals(0, brokerController1.getMessageStore().getMinOffsetInQueue(batchTopic, 0)); Assert.assertEquals(0, brokerController2.getMessageStore().getMinOffsetInQueue(batchTopic, 0)); Assert.assertEquals(0, brokerController3.getMessageStore().getMinOffsetInQueue(batchTopic, 0)); Assert.assertEquals(0, brokerController1.getMessageStore().getMaxOffsetInQueue(batchTopic, 0)); Assert.assertEquals(0, brokerController2.getMessageStore().getMaxOffsetInQueue(batchTopic, 0)); Assert.assertEquals(0, brokerController3.getMessageStore().getMaxOffsetInQueue(batchTopic, 0)); DefaultMQProducer producer = ProducerFactory.getRMQProducer(NAMESRV_ADDR); MessageQueue messageQueue = producer.fetchPublishMessageQueues(batchTopic).iterator().next(); int batchCount = 10; int batchNum = 10; for (int i = 0; i < batchCount; i++) { List<Message> messageList = new ArrayList<>(); for (int j = 0; j < batchNum; j++) { messageList.add(new Message(batchTopic, RandomUtils.getStringByUUID().getBytes())); } SendResult sendResult = producer.send(messageList, messageQueue); Assert.assertEquals(SendStatus.SEND_OK, sendResult.getSendStatus()); Assert.assertEquals(messageQueue.getQueueId(), sendResult.getMessageQueue().getQueueId()); Assert.assertEquals(i * batchNum, sendResult.getQueueOffset()); Assert.assertEquals(10, sendResult.getMsgId().split(",").length); } Thread.sleep(300); { DefaultMQPullConsumer defaultMQPullConsumer = ConsumerFactory.getRMQPullConsumer(NAMESRV_ADDR, "group"); long startOffset = 5; PullResult pullResult = defaultMQPullConsumer.pullBlockIfNotFound(messageQueue, "*", startOffset, batchCount * batchNum); Assert.assertEquals(PullStatus.FOUND, pullResult.getPullStatus()); Assert.assertEquals(0, pullResult.getMinOffset()); Assert.assertEquals(batchCount * batchNum, pullResult.getMaxOffset()); Assert.assertEquals(batchCount * batchNum - startOffset, pullResult.getMsgFoundList().size()); for (int i = 0; i < pullResult.getMsgFoundList().size(); i++) { MessageExt messageExt = pullResult.getMsgFoundList().get(i); Assert.assertEquals(i + startOffset, messageExt.getQueueOffset()); Assert.assertEquals(batchTopic, messageExt.getTopic()); Assert.assertEquals(messageQueue.getQueueId(), messageExt.getQueueId()); } } } @Test public void testBatchSend_CheckProperties() throws Exception { List<Message> messageList = new ArrayList<>(); Message message = new Message(); message.setTopic(topic); message.setKeys("keys123"); message.setTags("tags123"); message.setWaitStoreMsgOK(false); message.setBuyerId("buyerid123"); message.setFlag(123); message.setBody("body".getBytes()); messageList.add(message); DefaultMQProducer producer = ProducerFactory.getRMQProducer(NAMESRV_ADDR); removeBatchUniqueId(producer); SendResult sendResult = producer.send(messageList); Assert.assertEquals(SendStatus.SEND_OK, sendResult.getSendStatus()); String[] offsetIds = sendResult.getOffsetMsgId().split(","); String[] msgIds = sendResult.getMsgId().split(","); Assert.assertEquals(messageList.size(), offsetIds.length); Assert.assertEquals(messageList.size(), msgIds.length); Thread.sleep(2000); Message messageByOffset = producer.viewMessage(topic, offsetIds[0]); Message messageByMsgId = producer.viewMessage(topic, msgIds[0]); Assert.assertEquals(message.getTopic(), messageByMsgId.getTopic()); Assert.assertEquals(message.getTopic(), messageByOffset.getTopic()); Assert.assertEquals(message.getKeys(), messageByOffset.getKeys()); Assert.assertEquals(message.getKeys(), messageByMsgId.getKeys()); Assert.assertEquals(message.getTags(), messageByOffset.getTags()); Assert.assertEquals(message.getTags(), messageByMsgId.getTags()); Assert.assertEquals(message.isWaitStoreMsgOK(), messageByOffset.isWaitStoreMsgOK()); Assert.assertEquals(message.isWaitStoreMsgOK(), messageByMsgId.isWaitStoreMsgOK()); Assert.assertEquals(message.getBuyerId(), messageByOffset.getBuyerId()); Assert.assertEquals(message.getBuyerId(), messageByMsgId.getBuyerId()); Assert.assertEquals(message.getFlag(), messageByOffset.getFlag()); Assert.assertEquals(message.getFlag(), messageByMsgId.getFlag()); } // simulate legacy batch message send. private void removeBatchUniqueId(DefaultMQProducer producer) { producer.getDefaultMQProducerImpl().registerSendMessageHook(new SendMessageHook() { @Override public String hookName() { return null; } @Override public void sendMessageBefore(SendMessageContext context) { MessageBatch messageBatch = (MessageBatch) context.getMessage(); if (messageBatch.getProperty(MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX) != null) { messageBatch.getProperties().remove(MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX); } } @Override public void sendMessageAfter(SendMessageContext context) { } }); } }
BatchSendIT
java
google__dagger
javatests/dagger/functional/multipackage/MultibindsComponent.java
{ "start": 1251, "end": 1324 }
interface ____ { UsesInaccessible usesInaccessible(); }
MultibindsComponent
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/support/processor/UnmarshalProcessor.java
{ "start": 1720, "end": 7264 }
class ____ extends AsyncProcessorSupport implements Traceable, CamelContextAware, IdAware, RouteIdAware, DisabledAware { private String id; private String routeId; private CamelContext camelContext; private boolean disabled; private final DataFormat dataFormat; private final boolean allowNullBody; private String variableSend; private String variableReceive; public UnmarshalProcessor(DataFormat dataFormat) { this(dataFormat, false); } public UnmarshalProcessor(DataFormat dataFormat, boolean allowNullBody) { this.dataFormat = dataFormat; this.allowNullBody = allowNullBody; } @Override public boolean process(Exchange exchange, AsyncCallback callback) { ObjectHelper.notNull(dataFormat, "dataFormat"); InputStream stream = null; Object result = null; try { final Message in = exchange.getIn(); final Object originalBody = in.getBody(); Object body = originalBody; if (variableSend != null) { body = ExchangeHelper.getVariable(exchange, variableSend); } final Message out; if (allowNullBody && body == null) { // The body is null, and it is an allowed value so let's skip the unmarshalling out = exchange.getOut(); } else { // lets set up the out message before we invoke the dataFormat so that it can mutate it if necessary out = exchange.getOut(); out.copyFrom(in); if (body instanceof InputStream is) { stream = is; result = dataFormat.unmarshal(exchange, stream); } else { result = dataFormat.unmarshal(exchange, body); } } if (result instanceof Exchange) { if (result != exchange) { // it's not allowed to return another exchange other than the one provided to dataFormat throw new RuntimeCamelException( "The returned exchange " + result + " is not the same as " + exchange + " provided to the DataFormat"); } } else if (result instanceof Message msg) { // result should be stored in variable instead of message body if (variableReceive != null) { Object value = msg.getBody(); ExchangeHelper.setVariable(exchange, variableReceive, value); } else { // the dataformat has probably set headers, attachments, etc. so let's use it as the outbound payload exchange.setOut(msg); } } else { // result should be stored in variable instead of message body if (variableReceive != null) { ExchangeHelper.setVariable(exchange, variableReceive, result); } else { out.setBody(result); } } } catch (Exception e) { // remove OUT message, as an exception occurred exchange.setOut(null); exchange.setException(e); } finally { // The Iterator will close the stream itself if (!(result instanceof Iterator)) { IOHelper.close(stream, "input stream"); } } callback.done(true); return true; } @Override public String toString() { return "Unmarshal[" + dataFormat + "]"; } @Override public String getTraceLabel() { return "unmarshal[" + dataFormat + "]"; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getRouteId() { return routeId; } @Override public void setRouteId(String routeId) { this.routeId = routeId; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public boolean isDisabled() { return disabled; } @Override public void setDisabled(boolean disabled) { this.disabled = disabled; } public boolean isAllowNullBody() { return allowNullBody; } public String getVariableSend() { return variableSend; } public void setVariableSend(String variableSend) { this.variableSend = variableSend; } public String getVariableReceive() { return variableReceive; } public void setVariableReceive(String variableReceive) { this.variableReceive = variableReceive; } @Override protected void doStart() throws Exception { // inject CamelContext on data format CamelContextAware.trySetCamelContext(dataFormat, camelContext); // add dataFormat as service which will also start the service // (false => we handle the lifecycle of the dataFormat) getCamelContext().addService(dataFormat, false, true); } @Override protected void doStop() throws Exception { ServiceHelper.stopService(dataFormat); getCamelContext().removeService(dataFormat); } }
UnmarshalProcessor
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_182.java
{ "start": 1167, "end": 2929 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "SELECT cid FROM \"wenyu_meta_test\".\"WENYU_META_TEST_02\" LIMIT 4"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); SQLSelectStatement selectStmt = (SQLSelectStatement) stmt; SQLSelect select = selectStmt.getSelect(); assertNotNull(select.getQuery()); MySqlSelectQueryBlock queryBlock = (MySqlSelectQueryBlock) select.getQuery(); assertNull(queryBlock.getOrderBy()); // print(statementList); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(1, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertEquals(0, visitor.getOrderByColumns().size()); assertTrue(visitor.containsTable("wenyu_meta_test.WENYU_META_TEST_02")); assertTrue(visitor.containsColumn("wenyu_meta_test.WENYU_META_TEST_02", "cid")); String output = SQLUtils.toMySqlString(stmt); assertEquals("SELECT cid\n" + "FROM \"wenyu_meta_test\".\"WENYU_META_TEST_02\"\n" + "LIMIT 4", // output); } }
MySqlSelectTest_182
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/access/DelegatingMissingAuthorityAccessDeniedHandler.java
{ "start": 10362, "end": 10863 }
class ____ { private final String authority; private final @Nullable RequiredFactorError error; private AuthorityRequiredFactorErrorEntry(String authority, @Nullable RequiredFactorError error) { Assert.notNull(authority, "authority cannot be null"); this.authority = authority; this.error = error; } private String getAuthority() { return this.authority; } private @Nullable RequiredFactorError getError() { return this.error; } } }
AuthorityRequiredFactorErrorEntry
java
grpc__grpc-java
core/src/main/java/io/grpc/internal/PickFirstLoadBalancer.java
{ "start": 7471, "end": 8006 }
class ____ { @Nullable public final Boolean shuffleAddressList; // For testing purposes only, not meant to be parsed from a real config. @Nullable final Long randomSeed; public PickFirstLoadBalancerConfig(@Nullable Boolean shuffleAddressList) { this(shuffleAddressList, null); } PickFirstLoadBalancerConfig(@Nullable Boolean shuffleAddressList, @Nullable Long randomSeed) { this.shuffleAddressList = shuffleAddressList; this.randomSeed = randomSeed; } } }
PickFirstLoadBalancerConfig
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/wrappedio/impl/DynamicWrappedStatistics.java
{ "start": 11235, "end": 23328 }
class ____ found and loaded. */ public boolean loaded() { return loaded; } /** * Are the core IOStatistics methods and classes available. * @return true if the relevant methods are loaded. */ public boolean ioStatisticsAvailable() { return available(iostatisticsSnapshotCreateMethod); } /** * Are the IOStatisticsContext methods and classes available? * @return true if the relevant methods are loaded. */ public boolean ioStatisticsContextAvailable() { return available(iostatisticsContextEnabledMethod); } /** * Require a IOStatistics to be available. * @throws UnsupportedOperationException if the method was not found. */ private void checkIoStatisticsAvailable() { checkAvailable(iostatisticsSnapshotCreateMethod); } /** * Require IOStatisticsContext methods to be available. * @throws UnsupportedOperationException if the classes/methods were not found */ private void checkIoStatisticsContextAvailable() { checkAvailable(iostatisticsContextEnabledMethod); } /** * Probe for an object being an instance of {@code IOStatisticsSource}. * @param object object to probe * @return true if the object is the right type, false if the classes * were not found or the object is null/of a different type */ public boolean isIOStatisticsSource(Object object) { return ioStatisticsAvailable() && (boolean) isIOStatisticsSourceMethod.invoke(null, object); } /** * Probe for an object being an instance of {@code IOStatisticsSource}. * @param object object to probe * @return true if the object is the right type, false if the classes * were not found or the object is null/of a different type */ public boolean isIOStatistics(Object object) { return ioStatisticsAvailable() && (boolean) isIOStatisticsMethod.invoke(null, object); } /** * Probe for an object being an instance of {@code IOStatisticsSnapshot}. * @param object object to probe * @return true if the object is the right type, false if the classes * were not found or the object is null/of a different type */ public boolean isIOStatisticsSnapshot(Serializable object) { return ioStatisticsAvailable() && (boolean) isIOStatisticsSnapshotMethod.invoke(null, object); } /** * Probe to check if the thread-level IO statistics enabled. * If the relevant classes and methods were not found, returns false * @return true if the IOStatisticsContext API was found * and is enabled. */ public boolean iostatisticsContext_enabled() { return ioStatisticsAvailable() && (boolean) iostatisticsContextEnabledMethod.invoke(null); } /** * Get the context's {@code IOStatisticsContext} which * implements {@code IOStatisticsSource}. * This is either a thread-local value or a global empty context. * @return instance of {@code IOStatisticsContext}. * @throws UnsupportedOperationException if the IOStatisticsContext API was not found */ public Object iostatisticsContext_getCurrent() throws UnsupportedOperationException { checkIoStatisticsContextAvailable(); return iostatisticsContextGetCurrentMethod.invoke(null); } /** * Set the IOStatisticsContext for the current thread. * @param statisticsContext IOStatistics context instance for the * current thread. If null, the context is reset. * @throws UnsupportedOperationException if the IOStatisticsContext API was not found */ public void iostatisticsContext_setThreadIOStatisticsContext( @Nullable Object statisticsContext) throws UnsupportedOperationException { checkIoStatisticsContextAvailable(); iostatisticsContextSetThreadContextMethod.invoke(null, statisticsContext); } /** * Reset the context's IOStatistics. * {@code IOStatisticsContext#reset()} * @throws UnsupportedOperationException if the IOStatisticsContext API was not found */ public void iostatisticsContext_reset() throws UnsupportedOperationException { checkIoStatisticsContextAvailable(); iostatisticsContextResetMethod.invoke(null); } /** * Take a snapshot of the context IOStatistics. * {@code IOStatisticsContext#snapshot()} * @return an instance of {@code IOStatisticsSnapshot}. * @throws UnsupportedOperationException if the IOStatisticsContext API was not found */ public Serializable iostatisticsContext_snapshot() throws UnsupportedOperationException { checkIoStatisticsContextAvailable(); return iostatisticsContextSnapshotMethod.invoke(null); } /** * Aggregate into the IOStatistics context the statistics passed in via * IOStatistics/source parameter. * <p> * Returns false if the source is null or does not contain any statistics. * @param source implementation of {@link IOStatisticsSource} or {@link IOStatistics} * @return true if the the source object was aggregated. */ public boolean iostatisticsContext_aggregate(Object source) { checkIoStatisticsContextAvailable(); return iostatisticsContextAggregateMethod.invoke(null, source); } /** * Aggregate an existing {@code IOStatisticsSnapshot} with * the supplied statistics. * @param snapshot snapshot to update * @param statistics IOStatistics to add * @return true if the snapshot was updated. * @throws IllegalArgumentException if the {@code statistics} argument is not * null but not an instance of IOStatistics, or if {@code snapshot} is invalid. * @throws UnsupportedOperationException if the IOStatistics classes were not found */ public boolean iostatisticsSnapshot_aggregate( Serializable snapshot, @Nullable Object statistics) throws UnsupportedOperationException { checkIoStatisticsAvailable(); return iostatisticsSnapshotAggregateMethod.invoke(null, snapshot, statistics); } /** * Create a new {@code IOStatisticsSnapshot} instance. * @return an empty IOStatisticsSnapshot. * @throws UnsupportedOperationException if the IOStatistics classes were not found */ public Serializable iostatisticsSnapshot_create() throws UnsupportedOperationException { checkIoStatisticsAvailable(); return iostatisticsSnapshotCreateMethod.invoke(null); } /** * Create a new {@code IOStatisticsSnapshot} instance. * @param source optional source statistics * @return an IOStatisticsSnapshot. * @throws ClassCastException if the {@code source} is not valid. * @throws UnsupportedOperationException if the IOStatistics classes were not found */ public Serializable iostatisticsSnapshot_create( @Nullable Object source) throws UnsupportedOperationException, ClassCastException { checkIoStatisticsAvailable(); return iostatisticsSnapshotCreateWithSourceMethod.invoke(null, source); } /** * Save IOStatisticsSnapshot to a JSON string. * @param snapshot statistics; may be null or of an incompatible type * @return JSON string value or null if source is not an IOStatisticsSnapshot * @throws UncheckedIOException Any IO/jackson exception. * @throws UnsupportedOperationException if the IOStatistics classes were not found */ public String iostatisticsSnapshot_toJsonString(@Nullable Serializable snapshot) throws UncheckedIOException, UnsupportedOperationException { checkIoStatisticsAvailable(); return iostatisticsSnapshotToJsonStringMethod.invoke(null, snapshot); } /** * Load IOStatisticsSnapshot from a JSON string. * @param json JSON string value. * @return deserialized snapshot. * @throws UncheckedIOException Any IO/jackson exception. * @throws UnsupportedOperationException if the IOStatistics classes were not found */ public Serializable iostatisticsSnapshot_fromJsonString( final String json) throws UncheckedIOException, UnsupportedOperationException { checkIoStatisticsAvailable(); return iostatisticsSnapshotFromJsonStringMethod.invoke(null, json); } /** * Load IOStatisticsSnapshot from a Hadoop filesystem. * @param fs filesystem * @param path path * @return the loaded snapshot * @throws UncheckedIOException Any IO exception. * @throws UnsupportedOperationException if the IOStatistics classes were not found */ public Serializable iostatisticsSnapshot_load( FileSystem fs, Path path) throws UncheckedIOException, UnsupportedOperationException { checkIoStatisticsAvailable(); return iostatisticsSnapshotLoadMethod.invoke(null, fs, path); } /** * Extract the IOStatistics from an object in a serializable form. * @param source source object, may be null/not a statistics source/instance * @return {@code IOStatisticsSnapshot} or null if the object is null/doesn't have statistics * @throws UnsupportedOperationException if the IOStatistics classes were not found */ public Serializable iostatisticsSnapshot_retrieve(@Nullable Object source) throws UnsupportedOperationException { checkIoStatisticsAvailable(); return iostatisticsSnapshotRetrieveMethod.invoke(null, source); } /** * Save IOStatisticsSnapshot to a Hadoop filesystem as a JSON file. * @param snapshot statistics * @param fs filesystem * @param path path * @param overwrite should any existing file be overwritten? * @throws UncheckedIOException Any IO exception. * @throws UnsupportedOperationException if the IOStatistics classes were not found */ public void iostatisticsSnapshot_save( @Nullable Serializable snapshot, FileSystem fs, Path path, boolean overwrite) throws UncheckedIOException, UnsupportedOperationException { checkIoStatisticsAvailable(); iostatisticsSnapshotSaveMethod.invoke(null, snapshot, fs, path, overwrite); } /** * Get the counters of an IOStatisticsSnapshot. * @param source source of statistics. * @return the map of counters. */ public Map<String, Long> iostatistics_counters( Serializable source) { return iostatisticsCountersMethod.invoke(null, source); } /** * Get the gauges of an IOStatisticsSnapshot. * @param source source of statistics. * @return the map of gauges. */ public Map<String, Long> iostatistics_gauges( Serializable source) { return iostatisticsGaugesMethod.invoke(null, source); } /** * Get the minimums of an IOStatisticsSnapshot. * @param source source of statistics. * @return the map of minimums. */ public Map<String, Long> iostatistics_minimums( Serializable source) { return iostatisticsMinimumsMethod.invoke(null, source); } /** * Get the maximums of an IOStatisticsSnapshot. * @param source source of statistics. * @return the map of maximums. */ public Map<String, Long> iostatistics_maximums( Serializable source) { return iostatisticsMaximumsMethod.invoke(null, source); } /** * Get the means of an IOStatisticsSnapshot. * Each value in the map is the (sample, sum) tuple of the values; * the mean is then calculated by dividing sum/sample wherever sample is non-zero. * @param source source of statistics. * @return a map of mean key to (sample, sum) tuples. */ public Map<String, Map.Entry<Long, Long>> iostatistics_means( Serializable source) { return iostatisticsMeansMethod.invoke(null, source); } /** * Convert IOStatistics to a string form, with all the metrics sorted * and empty value stripped. * @param statistics A statistics instance. * @return string value or the empty string if null * @throws UnsupportedOperationException if the IOStatistics classes were not found */ public String iostatistics_toPrettyString(Object statistics) { checkIoStatisticsAvailable(); return iostatisticsToPrettyStringMethod.invoke(null, statistics); } @Override public String toString() { return "DynamicWrappedStatistics{" + "ioStatisticsAvailable =" + ioStatisticsAvailable() + ", ioStatisticsContextAvailable =" + ioStatisticsContextAvailable() + '}'; } }
was
java
qos-ch__slf4j
slf4j-ext/src/main/java/org/slf4j/ext/LoggerWrapper.java
{ "start": 1425, "end": 1619 }
class ____ an {@link org.slf4j.Logger} instance preserving * location information if the wrapped instance supports it. * * @author Ralph Goers * @author Ceki G&uuml;lc&uuml; */ public
wrapping
java
quarkusio__quarkus
extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftBuild.java
{ "start": 177, "end": 586 }
class ____ implements BooleanSupplier { private final ContainerImageConfig containerImageConfig; OpenshiftBuild(ContainerImageConfig containerImageConfig) { this.containerImageConfig = containerImageConfig; } @Override public boolean getAsBoolean() { return containerImageConfig.builder().map(b -> b.equals(OpenshiftProcessor.OPENSHIFT)).orElse(true); } }
OpenshiftBuild
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_agapple_2.java
{ "start": 506, "end": 759 }
class ____ { private DataMediaType type; public DataMediaType getType() { return type; } public void setType(DataMediaType type) { this.type = type; } } public static
DbMediaSource
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/PeriodTaskScheduler.java
{ "start": 1146, "end": 2168 }
interface ____ { /** * Schedules the period task. * * @param task the period task (the task can extend {@link org.apache.camel.support.service.ServiceSupport} to * have lifecycle) * @param period the interval (approximate) in millis, between running the task */ void schedulePeriodTask(Runnable task, long period); /** * Schedules the task once so the task keeps running always. This is to be used for tasks that is not triggered in * periods, but need to run forever. * * @param task the task (the task can extend {@link org.apache.camel.support.service.ServiceSupport} to have * lifecycle) */ void scheduledTask(Runnable task); /** * Gets an existing task by a given type, assuming there is only one task of the given type. * * @param type the type of the task * @return the task, or <tt>null</tt> if no tasks exists */ <T> T getTaskByType(Class<T> type); }
PeriodTaskScheduler
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine.java
{ "start": 15216, "end": 17337 }
class ____ implements ProtobufRpcEngineCallback { private final RPC.Server server; private final Call call; private final String methodName; public ProtobufRpcEngineCallbackImpl() { this.server = CURRENT_CALL_INFO.get().getServer(); this.call = Server.getCurCall().get(); this.methodName = CURRENT_CALL_INFO.get().getMethodName(); } private void updateProcessingDetails(Call rpcCall, long deltaNanos) { ProcessingDetails details = rpcCall.getProcessingDetails(); rpcCall.getProcessingDetails().set(ProcessingDetails.Timing.PROCESSING, deltaNanos, TimeUnit.NANOSECONDS); deltaNanos -= details.get(ProcessingDetails.Timing.LOCKWAIT, TimeUnit.NANOSECONDS); deltaNanos -= details.get(ProcessingDetails.Timing.LOCKSHARED, TimeUnit.NANOSECONDS); deltaNanos -= details.get(ProcessingDetails.Timing.LOCKEXCLUSIVE, TimeUnit.NANOSECONDS); details.set(ProcessingDetails.Timing.LOCKFREE, deltaNanos, TimeUnit.NANOSECONDS); } @Override public void setResponse(Message message) { long deltaNanos = Time.monotonicNowNanos() - call.getStartHandleTimestampNanos(); updateProcessingDetails(call, deltaNanos); call.setDeferredResponse(RpcWritable.wrap(message)); server.updateDeferredMetrics(call, methodName); } @Override public void error(Throwable t) { long deltaNanos = Time.monotonicNowNanos() - call.getStartHandleTimestampNanos(); updateProcessingDetails(call, deltaNanos); call.setDeferredError(t); String detailedMetricsName = t.getClass().getSimpleName(); server.updateDeferredMetrics(call, detailedMetricsName); } } @InterfaceStability.Unstable public static ProtobufRpcEngineCallback registerForDeferredResponse() { ProtobufRpcEngineCallback callback = new ProtobufRpcEngineCallbackImpl(); currentCallback.set(callback); return callback; } /** * Construct an RPC server. * * @param protocolClass the
ProtobufRpcEngineCallbackImpl
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/associations/NestedOneToOneDiscriminatorTest.java
{ "start": 5006, "end": 5144 }
class ____ extends BaseEntity { public NestedEntity() { } public NestedEntity(String name) { this.name = name; } } }
NestedEntity
java
FasterXML__jackson-core
src/test/java/tools/jackson/core/unittest/io/schubfach/DoubleToDecimalTest.java
{ "start": 404, "end": 4206 }
class ____ { @Test void extremeValues() { toDec(Double.NEGATIVE_INFINITY); toDec(-Double.MAX_VALUE); toDec(-Double.MIN_NORMAL); toDec(-Double.MIN_VALUE); toDec(-0.0); toDec(0.0); toDec(Double.MIN_VALUE); toDec(Double.MIN_NORMAL); toDec(Double.MAX_VALUE); toDec(Double.POSITIVE_INFINITY); toDec(Double.NaN); /* Quiet NaNs have the most significant bit of the mantissa as 1, while signaling NaNs have it as 0. Exercise 4 combinations of quiet/signaling NaNs and "positive/negative" NaNs */ toDec(longBitsToDouble(0x7FF8_0000_0000_0001L)); toDec(longBitsToDouble(0x7FF0_0000_0000_0001L)); toDec(longBitsToDouble(0xFFF8_0000_0000_0001L)); toDec(longBitsToDouble(0xFFF0_0000_0000_0001L)); /* All values treated specially by Schubfach */ for (int c = 1; c < C_TINY; ++c) { toDec(c * Double.MIN_VALUE); } } /* A few "powers of 10" are incorrectly rendered by the JDK. The rendering is either too long or it is not the closest decimal. */ @Test void powersOf10() { for (int e = E_MIN; e <= E_MAX; ++e) { toDec(Double.parseDouble("1e" + e)); } } /* Many powers of 2 are incorrectly rendered by the JDK. The rendering is either too long or it is not the closest decimal. */ @Test void powersOf2() { for (double v = Double.MIN_VALUE; v <= Double.MAX_VALUE; v *= 2) { toDec(v); } } @Test void someAnomalies() { for (String dec : Anomalies) { toDec(Double.parseDouble(dec)); } } @Test void paxson() { for (int i = 0; i < PaxsonSignificands.length; ++i) { toDec(scalb(PaxsonSignificands[i], PaxsonExponents[i])); } } /* Tests all integers of the form yx_xxx_000_000_000_000_000, y != 0. These are all exact doubles. */ @Test void longs() { for (int i = 10_000; i < 100_000; ++i) { toDec(i * 1e15); } } /* Tests all integers up to 1_000_000. These are all exact doubles and exercise a fast path. */ @Test void ints() { for (int i = 0; i <= 1_000_000; ++i) { toDec(i); } } @Test void constants() { assertEquals(DoubleToDecimal.P, P, "P"); assertEquals(C_MIN, (long) (double) C_MIN, "C_MIN"); assertEquals(C_MAX, (long) (double) C_MAX, "C_MAX"); assertEquals(Double.MIN_VALUE, MIN_VALUE, "MIN_VALUE"); assertEquals(Double.MIN_NORMAL, MIN_NORMAL, "MIN_NORMAL"); assertEquals(Double.MAX_VALUE, MAX_VALUE, "MAX_VALUE"); assertEquals(DoubleToDecimal.Q_MIN, Q_MIN, "Q_MIN"); assertEquals(DoubleToDecimal.Q_MAX, Q_MAX, "Q_MAX"); assertEquals(DoubleToDecimal.K_MIN, K_MIN, "K_MIN"); assertEquals(DoubleToDecimal.K_MAX, K_MAX, "K_MAX"); assertEquals(DoubleToDecimal.H, H, "H"); assertEquals(DoubleToDecimal.E_MIN, E_MIN, "E_MIN"); assertEquals(DoubleToDecimal.E_MAX, E_MAX, "E_MAX"); assertEquals(DoubleToDecimal.C_TINY, C_TINY, "C_TINY"); } @Test void hardValues() { for (double v : hard0()) { toDec(v); } for (double v : hard1()) { toDec(v); } for (double v : hard2()) { toDec(v); } for (double v : hard3()) { toDec(v); } } @Test void randomNumberTests() { // 29-Nov-2022, tatu: Reduce from 1M due to slowness DoubleToDecimalChecker.randomNumberTests(250_000, new Random()); } }
DoubleToDecimalTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/metrics/AllSubTasksRunningOrFinishedStateTimeMetrics.java
{ "start": 1701, "end": 1833 }
class ____ implements ExecutionStatusMetricsRegistrar, StateTimeMetric { public
AllSubTasksRunningOrFinishedStateTimeMetrics
java
quarkusio__quarkus
extensions/jdbc/jdbc-mssql/runtime/src/main/java/io/quarkus/jdbc/mssql/runtime/graal/com/microsoft/sqlserver/jdbc/SQLServerJDBCSubstitutions.java
{ "start": 3049, "end": 3491 }
class ____ { @Substitute SQLServerFMTQuery(String userSql) throws SQLServerException { throw new IllegalStateException("It is not supported to connect to SQL Server versions older than 2012"); } } /** * This substitution is not strictly necessary, but it helps by providing a better error message to our users. */ @TargetClass(className = "com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement") final
SQLServerFMTQuery
java
apache__spark
sql/core/src/test/java/test/org/apache/spark/sql/connector/JavaSimpleDataSourceV2.java
{ "start": 1206, "end": 1796 }
class ____ extends JavaSimpleScanBuilder { @Override public InputPartition[] planInputPartitions() { InputPartition[] partitions = new InputPartition[2]; partitions[0] = new JavaRangeInputPartition(0, 5); partitions[1] = new JavaRangeInputPartition(5, 10); return partitions; } } @Override public Table getTable(CaseInsensitiveStringMap options) { return new JavaSimpleBatchTable() { @Override public ScanBuilder newScanBuilder(CaseInsensitiveStringMap options) { return new MyScanBuilder(); } }; } }
MyScanBuilder
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/MustParameterizedTest2.java
{ "start": 784, "end": 1276 }
class ____ extends TestCase { private String sql = "select * from t where id in (3, 5)"; private WallConfig config = new WallConfig(); protected void setUp() throws Exception { config.setMustParameterized(true); } public void testMySql() throws Exception { assertFalse(WallUtils.isValidateMySql(sql, config)); } public void testORACLE() throws Exception { assertFalse(WallUtils.isValidateOracle(sql, config)); } }
MustParameterizedTest2
java
apache__logging-log4j2
log4j-core-java9/src/main/java/org/apache/logging/log4j/core/jackson/ExtendedStackTraceElementMixIn.java
{ "start": 1932, "end": 5371 }
class ____ implements Serializable { protected static final String ATTR_CLASS_LOADER_NAME = StackTraceElementConstants.ATTR_CLASS_LOADER_NAME; protected static final String ATTR_MODULE = StackTraceElementConstants.ATTR_MODULE; protected static final String ATTR_MODULE_VERSION = StackTraceElementConstants.ATTR_MODULE_VERSION; protected static final String ATTR_CLASS = StackTraceElementConstants.ATTR_CLASS; protected static final String ATTR_METHOD = StackTraceElementConstants.ATTR_METHOD; protected static final String ATTR_FILE = StackTraceElementConstants.ATTR_FILE; protected static final String ATTR_LINE = StackTraceElementConstants.ATTR_LINE; protected static final String ATTR_EXACT = "exact"; protected static final String ATTR_LOCATION = "location"; protected static final String ATTR_VERSION = "version"; private static final long serialVersionUID = 1L; @JsonCreator public ExtendedStackTraceElementMixIn( // @formatter:off @JsonProperty(ATTR_CLASS_LOADER_NAME) final String classLoaderName, @JsonProperty(ATTR_MODULE) final String moduleName, @JsonProperty(ATTR_MODULE_VERSION) final String moduleVersion, @JsonProperty(ATTR_CLASS) final String declaringClass, @JsonProperty(ATTR_METHOD) final String methodName, @JsonProperty(ATTR_FILE) final String fileName, @JsonProperty(ATTR_LINE) final int lineNumber, @JsonProperty(ATTR_EXACT) final boolean exact, @JsonProperty(ATTR_LOCATION) final String location, @JsonProperty(ATTR_VERSION) final String version // @formatter:on ) { // empty } @JsonProperty(ATTR_CLASS_LOADER_NAME) @JacksonXmlProperty(localName = ATTR_CLASS_LOADER_NAME, isAttribute = true) public abstract String getClassLoaderName(); @JsonProperty(ATTR_MODULE) @JacksonXmlProperty(localName = ATTR_MODULE, isAttribute = true) public abstract String getModuleName(); @JsonProperty(ATTR_MODULE_VERSION) @JacksonXmlProperty(localName = ATTR_MODULE_VERSION, isAttribute = true) public abstract String getModuleVersion(); @JsonProperty(ATTR_CLASS) @JacksonXmlProperty(localName = ATTR_CLASS, isAttribute = true) public abstract String getClassName(); @JsonProperty(ATTR_EXACT) @JacksonXmlProperty(localName = ATTR_EXACT, isAttribute = true) public abstract boolean getExact(); @JsonIgnore public abstract ExtendedClassInfo getExtraClassInfo(); @JsonProperty(ATTR_FILE) @JacksonXmlProperty(localName = ATTR_FILE, isAttribute = true) public abstract String getFileName(); @JsonProperty(ATTR_LINE) @JacksonXmlProperty(localName = ATTR_LINE, isAttribute = true) public abstract int getLineNumber(); @JsonProperty(ATTR_LOCATION) @JacksonXmlProperty(localName = ATTR_LOCATION, isAttribute = true) public abstract String getLocation(); @JsonProperty(ATTR_METHOD) @JacksonXmlProperty(localName = ATTR_METHOD, isAttribute = true) public abstract String getMethodName(); @JsonIgnore abstract StackTraceElement getStackTraceElement(); @JsonProperty(ATTR_VERSION) @JacksonXmlProperty(localName = ATTR_VERSION, isAttribute = true) public abstract String getVersion(); @JsonIgnore public abstract boolean isNativeMethod(); }
ExtendedStackTraceElementMixIn
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/Configuration.java
{ "start": 1380, "end": 3891 }
class ____ { * * &#064;Bean * public MyBean myBean() { * // instantiate, configure and return bean ... * } * }</pre> * * <h2>Bootstrapping {@code @Configuration} classes</h2> * * <h3>Via {@code AnnotationConfigApplicationContext}</h3> * * <p>{@code @Configuration} classes are typically bootstrapped using either * {@link AnnotationConfigApplicationContext} or its web-capable variant, * {@link org.springframework.web.context.support.AnnotationConfigWebApplicationContext * AnnotationConfigWebApplicationContext}. A simple example with the former follows: * * <pre class="code"> * AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); * ctx.register(AppConfig.class); * ctx.refresh(); * MyBean myBean = ctx.getBean(MyBean.class); * // use myBean ... * </pre> * * <p>See the {@link AnnotationConfigApplicationContext} javadocs for further details, and see * {@link org.springframework.web.context.support.AnnotationConfigWebApplicationContext * AnnotationConfigWebApplicationContext} for web configuration instructions in a * {@code Servlet} container. * * <h3>Via Spring {@code <beans>} XML</h3> * * <p>As an alternative to registering {@code @Configuration} classes directly against an * {@code AnnotationConfigApplicationContext}, {@code @Configuration} classes may be * declared as normal {@code <bean>} definitions within Spring XML files: * * <pre class="code"> * &lt;beans&gt; * &lt;context:annotation-config/&gt; * &lt;bean class="com.acme.AppConfig"/&gt; * &lt;/beans&gt; * </pre> * * <p>In the example above, {@code <context:annotation-config/>} is required in order to * enable {@link ConfigurationClassPostProcessor} and other annotation-related * post processors that facilitate handling {@code @Configuration} classes. * * <h3>Via component scanning</h3> * * <p>Since {@code @Configuration} is meta-annotated with {@link Component @Component}, * {@code @Configuration} classes are candidates for component scanning &mdash; * for example, using {@link ComponentScan @ComponentScan} or Spring XML's * {@code <context:component-scan/>} element &mdash; and therefore may also take * advantage of {@link Autowired @Autowired}/{@link jakarta.inject.Inject @Inject} * like any regular {@code @Component}. In particular, if a single constructor is * present, autowiring semantics will be applied transparently for that constructor: * * <pre class="code"> * &#064;Configuration * public
AppConfig
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/LongSumReducer.java
{ "start": 1359, "end": 1850 }
class ____<K> extends MapReduceBase implements Reducer<K, LongWritable, K, LongWritable> { public void reduce(K key, Iterator<LongWritable> values, OutputCollector<K, LongWritable> output, Reporter reporter) throws IOException { // sum all values for this key long sum = 0; while (values.hasNext()) { sum += values.next().get(); } // output sum output.collect(key, new LongWritable(sum)); } }
LongSumReducer
java
spring-projects__spring-boot
module/spring-boot-jetty/src/main/java/org/springframework/boot/jetty/servlet/JettyServletWebServerFactory.java
{ "start": 5097, "end": 19173 }
class ____ extends JettyWebServerFactory implements ConfigurableJettyWebServerFactory, ConfigurableServletWebServerFactory, ResourceLoaderAware { private static final Log logger = LogFactory.getLog(JettyServletWebServerFactory.class); private final ServletWebServerSettings settings = new ServletWebServerSettings(); @SuppressWarnings("NullAway.Init") private ResourceLoader resourceLoader; /** * Create a new {@link JettyServletWebServerFactory} instance. */ public JettyServletWebServerFactory() { } /** * Create a new {@link JettyServletWebServerFactory} that listens for requests using * the specified port. * @param port the port to listen on */ public JettyServletWebServerFactory(int port) { super(port); } /** * Create a new {@link JettyServletWebServerFactory} with the specified context path * and port. * @param contextPath the root context path * @param port the port to listen on */ public JettyServletWebServerFactory(String contextPath, int port) { super(port); getSettings().setContextPath(ContextPath.of(contextPath)); } @Override public WebServer getWebServer(ServletContextInitializer... initializers) { JettyEmbeddedWebAppContext context = new JettyEmbeddedWebAppContext(); context.getContext().getServletContext().setExtendedListenerTypes(true); int port = Math.max(getPort(), 0); InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = createServer(address); context.setServer(server); configureWebAppContext(context, initializers); server.setHandler(addHandlerWrappers(context)); logger.info("Server initialized with port: " + port); if (this.getMaxConnections() > -1) { server.addBean(new NetworkConnectionLimit(this.getMaxConnections(), server.getConnectors())); } if (Ssl.isEnabled(getSsl())) { customizeSsl(server, address); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.isUseForwardHeaders()) { new ForwardHeadersCustomizer().customize(server); } if (getShutdown() == Shutdown.GRACEFUL) { StatisticsHandler statisticsHandler = new StatisticsHandler(); statisticsHandler.setHandler(server.getHandler()); server.setHandler(statisticsHandler); } return getJettyWebServer(server); } private Server createServer(InetSocketAddress address) { Server server = new Server(getThreadPool()); server.setConnectors(new Connector[] { createConnector(address, server) }); server.setStopTimeout(0); MimeTypes.Mutable mimeTypes = server.getMimeTypes(); for (MimeMappings.Mapping mapping : getSettings().getMimeMappings()) { mimeTypes.addMimeMapping(mapping.getExtension(), mapping.getMimeType()); } return server; } @Override protected Handler addHandlerWrappers(Handler handler) { handler = super.addHandlerWrappers(handler); if (!CollectionUtils.isEmpty(getSettings().getCookieSameSiteSuppliers())) { handler = applyWrapper(handler, new SuppliedSameSiteCookieHandlerWrapper(getSessionCookieName(), getSettings().getCookieSameSiteSuppliers())); } return handler; } private String getSessionCookieName() { String name = getSettings().getSession().getCookie().getName(); return (name != null) ? name : SessionConfig.__DefaultSessionCookie; } /** * Configure the given Jetty {@link WebAppContext} for use. * @param context the context to configure * @param initializers the set of initializers to apply */ protected final void configureWebAppContext(WebAppContext context, ServletContextInitializer... initializers) { Assert.notNull(context, "'context' must not be null"); context.clearAliasChecks(); if (this.resourceLoader != null) { context.setClassLoader(this.resourceLoader.getClassLoader()); } String contextPath = getSettings().getContextPath().toString(); context.setContextPath(StringUtils.hasLength(contextPath) ? contextPath : "/"); context.setDisplayName(getSettings().getDisplayName()); configureDocumentRoot(context); if (getSettings().isRegisterDefaultServlet()) { addDefaultServlet(context); } if (shouldRegisterJspServlet()) { addJspServlet(context); context.addBean(new JasperInitializer(context), true); } addLocaleMappings(context); ServletContextInitializers initializersToUse = ServletContextInitializers.from(this.settings, initializers); Configuration[] configurations = getWebAppContextConfigurations(context, initializersToUse); context.setConfigurations(configurations); context.setThrowUnavailableOnStartupException(true); configureSession(context); context.setTempDirectory(getTempDirectory(context)); postProcessWebAppContext(context); } private boolean shouldRegisterJspServlet() { return this.settings.getJsp() != null && this.settings.getJsp().getRegistered() && ClassUtils.isPresent(this.settings.getJsp().getClassName(), getClass().getClassLoader()); } private void configureSession(WebAppContext context) { SessionHandler handler = context.getSessionHandler(); SameSite sessionSameSite = getSettings().getSession().getCookie().getSameSite(); if (sessionSameSite != null && sessionSameSite != SameSite.OMITTED) { handler.setSameSite(HttpCookie.SameSite.valueOf(sessionSameSite.name())); } Duration sessionTimeout = getSettings().getSession().getTimeout(); handler.setMaxInactiveInterval(isNegative(sessionTimeout) ? -1 : (int) sessionTimeout.getSeconds()); if (getSettings().getSession().isPersistent()) { DefaultSessionCache cache = new DefaultSessionCache(handler); FileSessionDataStore store = new FileSessionDataStore(); store.setStoreDir(getSettings().getSession().getSessionStoreDirectory().getValidDirectory(true)); cache.setSessionDataStore(store); handler.setSessionCache(cache); } } @Contract("null -> true") private boolean isNegative(@Nullable Duration sessionTimeout) { return sessionTimeout == null || sessionTimeout.isNegative(); } private void addLocaleMappings(WebAppContext context) { getSettings().getLocaleCharsetMappings() .forEach((locale, charset) -> context.addLocaleEncoding(locale.toString(), charset.toString())); } private @Nullable File getTempDirectory(WebAppContext context) { String temp = System.getProperty("java.io.tmpdir"); return (temp != null) ? new File(temp, getTempDirectoryPrefix(context) + UUID.randomUUID()) : null; } @SuppressWarnings("removal") private String getTempDirectoryPrefix(WebAppContext context) { try { return ((JettyEmbeddedWebAppContext) context).getCanonicalNameForTmpDir(); } catch (Throwable ex) { return WebInfConfiguration.getCanonicalNameForWebAppTmpDir(context); } } private void configureDocumentRoot(WebAppContext handler) { DocumentRoot documentRoot = new DocumentRoot(logger); documentRoot.setDirectory(this.settings.getDocumentRoot()); File root = documentRoot.getValidDirectory(); File docBase = (root != null) ? root : createTempDir("jetty-docbase"); try { ResourceFactory resourceFactory = handler.getResourceFactory(); List<Resource> resources = new ArrayList<>(); Resource rootResource = (docBase.isDirectory() ? resourceFactory.newResource(docBase.getCanonicalFile().toURI()) : resourceFactory.newJarFileResource(docBase.toURI())); resources.add((root != null) ? new LoaderHidingResource(rootResource, rootResource) : rootResource); URLResourceFactory urlResourceFactory = new URLResourceFactory(); for (URL resourceJarUrl : getSettings().getStaticResourceUrls()) { Resource resource = createResource(resourceJarUrl, resourceFactory, urlResourceFactory); if (resource != null) { resources.add(resource); } } handler.setBaseResource(ResourceFactory.combine(resources)); } catch (Exception ex) { throw new IllegalStateException(ex); } } private @Nullable Resource createResource(URL url, ResourceFactory resourceFactory, URLResourceFactory urlResourceFactory) throws Exception { if ("file".equals(url.getProtocol())) { File file = new File(url.toURI()); if (file.isFile()) { return resourceFactory.newResource("jar:" + url + "!/META-INF/resources/"); } if (file.isDirectory()) { return resourceFactory.newResource(url).resolve("META-INF/resources/"); } } return urlResourceFactory.newResource(url + "META-INF/resources/"); } /** * Add Jetty's {@code DefaultServlet} to the given {@link WebAppContext}. * @param context the jetty {@link WebAppContext} */ protected final void addDefaultServlet(WebAppContext context) { Assert.notNull(context, "'context' must not be null"); ServletHolder holder = new ServletHolder(); holder.setName("default"); holder.setClassName("org.eclipse.jetty.ee11.servlet.DefaultServlet"); holder.setInitParameter("dirAllowed", "false"); holder.setInitOrder(1); context.getServletHandler().addServletWithMapping(holder, "/"); ServletMapping servletMapping = context.getServletHandler().getServletMapping("/"); servletMapping.setFromDefaultDescriptor(true); } /** * Add Jetty's {@code JspServlet} to the given {@link WebAppContext}. * @param context the jetty {@link WebAppContext} */ protected final void addJspServlet(WebAppContext context) { Assert.notNull(context, "'context' must not be null"); ServletHolder holder = new ServletHolder(); holder.setName("jsp"); holder.setClassName(this.settings.getJsp().getClassName()); holder.setInitParameter("fork", "false"); holder.setInitParameters(this.settings.getJsp().getInitParameters()); holder.setInitOrder(3); context.getServletHandler().addServlet(holder); ServletMapping mapping = new ServletMapping(); mapping.setServletName("jsp"); mapping.setPathSpecs(new String[] { "*.jsp", "*.jspx" }); context.getServletHandler().addServletMapping(mapping); } /** * Return the Jetty {@link Configuration}s that should be applied to the server. * @param webAppContext the Jetty {@link WebAppContext} * @param initializers the {@link ServletContextInitializer}s to apply * @return configurations to apply */ protected Configuration[] getWebAppContextConfigurations(WebAppContext webAppContext, ServletContextInitializers initializers) { List<Configuration> configurations = new ArrayList<>(); configurations.add(getServletContextInitializerConfiguration(webAppContext, initializers)); configurations.add(getErrorPageConfiguration()); configurations.add(getMimeTypeConfiguration()); configurations.add(new WebListenersConfiguration(getSettings().getWebListenerClassNames())); configurations.addAll(getConfigurations()); return configurations.toArray(new Configuration[0]); } /** * Create a configuration object that adds error handlers. * @return a configuration object for adding error pages */ private Configuration getErrorPageConfiguration() { return new AbstractConfiguration(new AbstractConfiguration.Builder()) { @Override public void configure(WebAppContext context) throws Exception { JettyEmbeddedErrorHandler errorHandler = new JettyEmbeddedErrorHandler(); context.setErrorHandler(errorHandler); addJettyErrorPages(errorHandler, getErrorPages()); } }; } /** * Create a configuration object that adds mime type mappings. * @return a configuration object for adding mime type mappings */ private Configuration getMimeTypeConfiguration() { return new AbstractConfiguration(new AbstractConfiguration.Builder()) { @Override public void configure(WebAppContext context) throws Exception { MimeTypes.Mutable mimeTypes = context.getMimeTypes(); mimeTypes.clear(); for (MimeMappings.Mapping mapping : getSettings().getMimeMappings()) { mimeTypes.addMimeMapping(mapping.getExtension(), mapping.getMimeType()); } } }; } /** * Return a Jetty {@link Configuration} that will invoke the specified * {@link ServletContextInitializer}s. By default this method will return a * {@link ServletContextInitializerConfiguration}. * @param webAppContext the Jetty {@link WebAppContext} * @param initializers the {@link ServletContextInitializer}s to apply * @return the {@link Configuration} instance */ protected Configuration getServletContextInitializerConfiguration(WebAppContext webAppContext, ServletContextInitializers initializers) { return new ServletContextInitializerConfiguration(initializers); } /** * Post process the Jetty {@link WebAppContext} before it's used with the Jetty * Server. Subclasses can override this method to apply additional processing to the * {@link WebAppContext}. * @param webAppContext the Jetty {@link WebAppContext} */ protected void postProcessWebAppContext(WebAppContext webAppContext) { } /** * Factory method called to create the {@link JettyWebServer}. Subclasses can override * this method to return a different {@link JettyWebServer} or apply additional * processing to the Jetty server. * @param server the Jetty server. * @return a new {@link JettyWebServer} instance */ protected JettyWebServer getJettyWebServer(Server server) { return new JettyServletWebServer(server, getPort() >= 0); } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } private void addJettyErrorPages(ErrorHandler errorHandler, Collection<ErrorPage> errorPages) { if (errorHandler instanceof ErrorPageErrorHandler handler) { for (ErrorPage errorPage : errorPages) { if (errorPage.isGlobal()) { handler.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE, errorPage.getPath()); } else { if (errorPage.getExceptionName() != null) { handler.addErrorPage(errorPage.getExceptionName(), errorPage.getPath()); } else { handler.addErrorPage(errorPage.getStatusCode(), errorPage.getPath()); } } } } } @Override public ServletWebServerSettings getSettings() { return this.settings; } /** * {@link AbstractConfiguration} to apply {@code @WebListener} classes. */ private static
JettyServletWebServerFactory
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/language/XPathExpression.java
{ "start": 9158, "end": 13923 }
class ____ of the result type (type from output) * <p/> * The default result type is NodeSet */ public Builder resultQName(ResultQName resultQName) { this.resultQName = resultQName == null ? null : resultQName.name(); return this; } /** * Whether to use Saxon. */ public Builder saxon(String saxon) { this.saxon = saxon; return this; } /** * Whether to use Saxon. */ public Builder saxon(boolean saxon) { this.saxon = Boolean.toString(saxon); return this; } /** * References to a custom XPathFactory to lookup in the registry */ public Builder factoryRef(String factoryRef) { this.factoryRef = factoryRef; return this; } /** * The XPath object model to use */ public Builder objectModel(String objectModel) { this.objectModel = objectModel; return this; } /** * Whether to log namespaces which can assist during troubleshooting */ public Builder logNamespaces(String logNamespaces) { this.logNamespaces = logNamespaces; return this; } /** * Whether to log namespaces which can assist during troubleshooting */ public Builder logNamespaces(boolean logNamespaces) { this.logNamespaces = Boolean.toString(logNamespaces); return this; } /** * Whether to enable thread-safety for the returned result of the xpath expression. This applies to when using * NODESET as the result type, and the returned set has multiple elements. In this situation there can be * thread-safety issues if you process the NODESET concurrently such as from a Camel Splitter EIP in parallel * processing mode. This option prevents concurrency issues by doing defensive copies of the nodes. * <p/> * It is recommended to turn this option on if you are using camel-saxon or Saxon in your application. Saxon has * thread-safety issues which can be prevented by turning this option on. */ public Builder threadSafety(String threadSafety) { this.threadSafety = threadSafety; return this; } /** * Whether to enable thread-safety for the returned result of the xpath expression. This applies to when using * NODESET as the result type, and the returned set has multiple elements. In this situation there can be * thread-safety issues if you process the NODESET concurrently such as from a Camel Splitter EIP in parallel * processing mode. This option prevents concurrency issues by doing defensive copies of the nodes. * <p/> * It is recommended to turn this option on if you are using camel-saxon or Saxon in your application. Saxon has * thread-safety issues which can be prevented by turning this option on. */ public Builder threadSafety(boolean threadSafety) { this.threadSafety = Boolean.toString(threadSafety); return this; } /** * Whether to enable pre-compiling the xpath expression during initialization phase. pre-compile is enabled by * default. * <p> * This can be used to turn off, for example in cases the compilation phase is desired at the starting phase, * such as if the application is ahead of time compiled (for example with camel-quarkus) which would then load * the xpath factory of the built operating system, and not a JVM runtime. */ public Builder preCompile(String preCompile) { this.preCompile = preCompile; return this; } /** * Whether to enable pre-compiling the xpath expression during initialization phase. pre-compile is enabled by * default. * <p> * This can be used to turn off, for example in cases the compilation phase is desired at the starting phase, * such as if the application is ahead of time compiled (for example with camel-quarkus) which would then load * the xpath factory of the built operating system, and not a JVM runtime. */ public Builder preCompile(boolean preCompile) { this.preCompile = Boolean.toString(preCompile); return this; } @Override public XPathExpression end() { return new XPathExpression(this); } } /** * {@code ResultQName} defines the possible
name
java
redisson__redisson
redisson/src/main/java/org/redisson/client/handler/RedisChannelInitializer.java
{ "start": 1801, "end": 1881 }
class ____ extends ChannelInitializer<Channel> { public
RedisChannelInitializer
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/nativeio/NativeIO.java
{ "start": 31125, "end": 32081 }
class ____ cache */ private static native void initNative(boolean doThreadsafeWorkaround); /** * Get the maximum number of bytes that can be locked into memory at any * given point. * * @return 0 if no bytes can be locked into memory; * Long.MAX_VALUE if there is no limit; * The number of bytes that can be locked into memory otherwise. */ static long getMemlockLimit() { return isAvailable() ? getMemlockLimit0() : 0; } private static native long getMemlockLimit0(); /** * @return the operating system's page size. */ static long getOperatingSystemPageSize() { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); Unsafe unsafe = (Unsafe)f.get(null); return unsafe.pageSize(); } catch (Throwable e) { LOG.warn("Unable to get operating system page size. Guessing 4096.", e); return 4096; } } private static
ID
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/mocking/SpyOnInterceptedBeanTest.java
{ "start": 1390, "end": 1859 }
class ____ { @MyInterceptorBinding String doSomething(int param) { return doSomethingElse() + param; } @MyInterceptorBinding String doSomethingElse() { return getValue(); } String getValue() { return "foobar"; } } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @InterceptorBinding public @
MyBean
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeToSingle.java
{ "start": 1696, "end": 3209 }
class ____<T> implements MaybeObserver<T>, Disposable { final SingleObserver<? super T> downstream; final T defaultValue; Disposable upstream; ToSingleMaybeSubscriber(SingleObserver<? super T> actual, T defaultValue) { this.downstream = actual; this.defaultValue = defaultValue; } @Override public void dispose() { upstream.dispose(); upstream = DisposableHelper.DISPOSED; } @Override public boolean isDisposed() { return upstream.isDisposed(); } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { this.upstream = d; downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { upstream = DisposableHelper.DISPOSED; downstream.onSuccess(value); } @Override public void onError(Throwable e) { upstream = DisposableHelper.DISPOSED; downstream.onError(e); } @Override public void onComplete() { upstream = DisposableHelper.DISPOSED; if (defaultValue != null) { downstream.onSuccess(defaultValue); } else { downstream.onError(new NoSuchElementException("The MaybeSource is empty")); } } } }
ToSingleMaybeSubscriber
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_containsExactly_Test.java
{ "start": 834, "end": 1238 }
class ____ extends AtomicReferenceArrayAssertBaseTest { @Override protected AtomicReferenceArrayAssert<Object> invoke_api_method() { return assertions.containsExactly("Yoda", "Luke"); } @Override protected void verify_internal_effects() { verify(arrays).assertContainsExactly(info(), internalArray(), new String[] { "Yoda", "Luke" }); } }
AtomicReferenceArrayAssert_containsExactly_Test
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/readonly/VersionedNode.java
{ "start": 242, "end": 1197 }
class ____ { private String id; private String name; private long version; private VersionedNode parent; private Set children = new HashSet(); public VersionedNode() { } public VersionedNode(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } public VersionedNode getParent() { return parent; } public void setParent(VersionedNode parent) { this.parent = parent; } public Set getChildren() { return children; } public void setChildren(Set children) { this.children = children; } public void addChild(VersionedNode child) { child.setParent( this ); children.add( child ); } }
VersionedNode
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/filter/ProblemHandlerLocation1440Test.java
{ "start": 584, "end": 1114 }
class ____ { public List<String> unknownProperties = new ArrayList<>(); public DeserializationProblem() { } public void addUnknownProperty(final String prop) { unknownProperties.add(prop); } public boolean foundProblems() { return !unknownProperties.isEmpty(); } @Override public String toString() { return "DeserializationProblem{" +"unknownProperties=" + unknownProperties +'}'; } } static
DeserializationProblem