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-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/TableEnvironment.java
{ "start": 59931, "end": 60647 }
class ____ for the format of the path. * @param ignoreIfNotExists If false exception will be thrown if the view to drop does not * exist. * @return true if table existed in the given path and was dropped, false if table didn't exist * in the given path. */ boolean dropTable(String path, boolean ignoreIfNotExists); /** * Drops a temporary view registered in the given path. * * <p>If a permanent table or view with a given path exists, it will be used from now on for any * queries that reference this path. * * @param path The given path under which the temporary view will be dropped. See also the * {@link TableEnvironment}
description
java
elastic__elasticsearch
x-pack/plugin/fleet/src/main/java/org/elasticsearch/xpack/fleet/action/GetSecretAction.java
{ "start": 353, "end": 626 }
class ____ extends ActionType<GetSecretResponse> { public static final String NAME = "cluster:admin/fleet/secrets/get"; public static final GetSecretAction INSTANCE = new GetSecretAction(); private GetSecretAction() { super(NAME); } }
GetSecretAction
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/targetclass/mixed/PostConstructOnTargetClassAndOutsideAndSuperclassesTest.java
{ "start": 1301, "end": 1530 }
class ____ { @PostConstruct void superPostConstruct() { MyBean.invocations.add(MyBeanSuperclass.class.getSimpleName()); } } @Singleton @MyInterceptorBinding static
MyBeanSuperclass
java
apache__kafka
connect/basic-auth-extension/src/test/java/org/apache/kafka/connect/rest/basic/auth/extension/BasicAuthSecurityRestExtensionTest.java
{ "start": 1697, "end": 4878 }
class ____ { Configuration priorConfiguration; @BeforeEach public void setup() { priorConfiguration = Configuration.getConfiguration(); } @AfterEach public void tearDown() { Configuration.setConfiguration(priorConfiguration); } @SuppressWarnings("unchecked") @Test public void testJaasConfigurationNotOverwritten() { ArgumentCaptor<JaasBasicAuthFilter> jaasFilter = ArgumentCaptor.forClass(JaasBasicAuthFilter.class); Configurable<? extends Configurable<?>> configurable = mock(Configurable.class); when(configurable.register(jaasFilter.capture())).thenReturn(null); ConnectRestExtensionContext context = mock(ConnectRestExtensionContext.class); when(context.configurable()).thenReturn((Configurable) configurable); BasicAuthSecurityRestExtension extension = new BasicAuthSecurityRestExtension(); Configuration overwrittenConfiguration = mock(Configuration.class); Configuration.setConfiguration(overwrittenConfiguration); extension.register(context); assertNotEquals(overwrittenConfiguration, jaasFilter.getValue().configuration, "Overwritten JAAS configuration should not be used by basic auth REST extension"); } @Test public void testBadJaasConfigInitialization() { SecurityException jaasConfigurationException = new SecurityException(new IOException("Bad JAAS config is bad")); Supplier<Configuration> configuration = BasicAuthSecurityRestExtension.initializeConfiguration(() -> { throw jaasConfigurationException; }); ConnectException thrownException = assertThrows(ConnectException.class, configuration::get); assertEquals(jaasConfigurationException, thrownException.getCause()); } @Test public void testGoodJaasConfigInitialization() { AtomicBoolean configurationInitializerEvaluated = new AtomicBoolean(false); Configuration mockConfiguration = mock(Configuration.class); Supplier<Configuration> configuration = BasicAuthSecurityRestExtension.initializeConfiguration(() -> { configurationInitializerEvaluated.set(true); return mockConfiguration; }); assertTrue(configurationInitializerEvaluated.get()); assertEquals(mockConfiguration, configuration.get()); } @Test public void testBadJaasConfigExtensionSetup() { SecurityException jaasConfigurationException = new SecurityException(new IOException("Bad JAAS config is bad")); Supplier<Configuration> configuration = () -> { throw jaasConfigurationException; }; BasicAuthSecurityRestExtension extension = new BasicAuthSecurityRestExtension(configuration); Exception thrownException = assertThrows(Exception.class, () -> extension.configure(Map.of())); assertEquals(jaasConfigurationException, thrownException); thrownException = assertThrows(Exception.class, () -> extension.register(mock(ConnectRestExtensionContext.class))); assertEquals(jaasConfigurationException, thrownException); } }
BasicAuthSecurityRestExtensionTest
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/cache/NoCacheOnMethodsImplementationTest.java
{ "start": 2430, "end": 2721 }
interface ____ { @Path("withFields") @GET String withFields(); @Path("withoutFields") @GET String withoutFields(); @Path("withoutAnnotation") @GET String withoutAnnotation(); } public static
IResourceWithNoCache
java
quarkusio__quarkus
extensions/panache/hibernate-orm-panache/deployment/src/test/java/io/quarkus/hibernate/orm/panache/deployment/test/multiple_pu/MultiplePersistenceUnitConfigTest.java
{ "start": 730, "end": 2517 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(FirstEntity.class, SecondEntity.class, PanacheTestResource.class) .addAsResource("application-multiple-persistence-units.properties", "application.properties")); @Inject EntityManager defaultEntityManager; @Inject Session defaulSession; @Inject @PersistenceUnit("second") EntityManager secondEntityManager; @Inject @PersistenceUnit("second") Session secondSession; @Test public void panacheOperations() { /** * First entity operations */ RestAssured.when().get("/persistence-unit/first/name-1").then().body(Matchers.is("1")); RestAssured.when().get("/persistence-unit/first/name-2").then().body(Matchers.is("2")); /** * second entity operations */ RestAssured.when().get("/persistence-unit/second/name-1").then().body(Matchers.is("1")); RestAssured.when().get("/persistence-unit/second/name-2").then().body(Matchers.is("2")); } @Test void entityManagerShouldExist() { assertNotNull(FirstEntity.getEntityManager()); assertEquals(FirstEntity.getEntityManager(), defaultEntityManager); assertNotNull(SecondEntity.getEntityManager()); assertEquals(SecondEntity.getEntityManager(), secondEntityManager); } @Test void sessionShouldExist() { assertNotNull(FirstEntity.getSession()); assertEquals(FirstEntity.getSession(), defaulSession); assertNotNull(SecondEntity.getSession()); assertEquals(SecondEntity.getSession(), secondSession); } }
MultiplePersistenceUnitConfigTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/VoidMissingNullableTest.java
{ "start": 10055, "end": 10493 }
interface ____ { void consume(Iterable<@Nullable Void> it); Test TEST = it -> {}; } """) .doTest(); } // TODO(cpovirk): Test under Java 11+ with `(var x) -> {}` lambda syntax. @Test public void negativeVar() { aggressiveCompilationHelper .addSourceLines( "Test.java", """ import javax.annotation.Nullable;
Test
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/FileNoOpLockFileTest.java
{ "start": 1545, "end": 3822 }
class ____ extends ContextTestSupport { @Test public void testLocked() throws Exception { MockEndpoint mock = getMockEndpoint("mock:report"); mock.expectedBodiesReceived("Hello Locked"); template.sendBodyAndHeader(fileUri("locked"), "Hello Locked", Exchange.FILE_NAME, "report.txt"); mock.assertIsSatisfied(); // sleep to let file consumer do its unlocking await().atMost(1, TimeUnit.SECONDS).until(() -> existsLockFile(false)); // should be deleted after processing checkLockFile(false); } @Test public void testNotLocked() throws Exception { MockEndpoint mock = getMockEndpoint("mock:report"); mock.expectedBodiesReceived("Hello Not Locked"); template.sendBodyAndHeader(fileUri("notlocked"), "Hello Not Locked", Exchange.FILE_NAME, "report.txt"); mock.assertIsSatisfied(); // sleep to let file consumer do its unlocking await().atMost(1, TimeUnit.SECONDS).until(() -> existsLockFile(false)); // no lock files should exists after processing checkLockFile(false); } private boolean existsLockFile(boolean expected) { String filename = (expected ? "locked/" : "notlocked/") + "report.txt" + FileComponent.DEFAULT_LOCK_FILE_POSTFIX; return expected == Files.exists(testFile(filename)); } private void checkLockFile(boolean expected) { String filename = (expected ? "locked/" : "notlocked/") + "report.txt" + FileComponent.DEFAULT_LOCK_FILE_POSTFIX; assertEquals(expected, Files.exists(testFile(filename)), "Lock file should " + (expected ? "exists" : "not exists")); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // for locks from(fileUri("locked/?initialDelay=0&delay=10&noop=true&readLock=markerFile")) .process(new MyNoopProcessor()).to("mock:report"); // for no locks from(fileUri("notlocked/?initialDelay=0&delay=10&noop=true&readLock=none")) .process(new MyNoopProcessor()).to("mock:report"); } }; } private
FileNoOpLockFileTest
java
netty__netty
common/src/test/java/io/netty/util/internal/logging/Log4J2LoggerTest.java
{ "start": 1489, "end": 3098 }
class ____ extends AbstractInternalLoggerTest<Logger> { { mockLog = LogManager.getLogger(loggerName); logger = new Log4J2Logger(mockLog) { private static final long serialVersionUID = 1L; @Override public void logMessage(String fqcn, Level level, Marker marker, Message message, Throwable t) { result.put("level", level.name()); result.put("t", t); super.logMessage(fqcn, level, marker, message, t); } }; } private static final EnumMap<InternalLogLevel, Level> DISABLING_LEVEL = new EnumMap<>(InternalLogLevel.class); static { DISABLING_LEVEL.put(InternalLogLevel.TRACE, Level.DEBUG); DISABLING_LEVEL.put(InternalLogLevel.DEBUG, Level.INFO); DISABLING_LEVEL.put(InternalLogLevel.INFO, Level.WARN); DISABLING_LEVEL.put(InternalLogLevel.WARN, Level.ERROR); DISABLING_LEVEL.put(InternalLogLevel.ERROR, Level.FATAL); } @Override protected void setLevelEnable(InternalLogLevel level, boolean enable) { Level targetLevel = Level.valueOf(level.name()); if (!enable) { targetLevel = DISABLING_LEVEL.get(level); } ((org.apache.logging.log4j.core.Logger) mockLog).setLevel(targetLevel); } @Override protected void assertResult(InternalLogLevel level, String format, Throwable t, Object... args) { super.assertResult(level, format, t, args); assertEquals(t, result.get("t")); assertEquals(level.name(), result.get("level")); } }
Log4J2LoggerTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/jdbc/EmptyDatabaseConfig.java
{ "start": 1228, "end": 1620 }
class ____ { @Bean JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean DataSource dataSource() { return new EmbeddedDatabaseBuilder() .generateUniqueName(true) .build(); } }
EmptyDatabaseConfig
java
apache__camel
components/camel-xj/src/generated/java/org/apache/camel/component/xj/XJEndpointConfigurer.java
{ "start": 734, "end": 2151 }
class ____ extends XsltSaxonEndpointConfigurer implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { XJEndpoint target = (XJEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "transformdirection": case "transformDirection": target.setTransformDirection(property(camelContext, org.apache.camel.component.xj.TransformDirection.class, value)); return true; default: return super.configure(camelContext, obj, name, value, ignoreCase); } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "transformdirection": case "transformDirection": return org.apache.camel.component.xj.TransformDirection.class; default: return super.getOptionType(name, ignoreCase); } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { XJEndpoint target = (XJEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "transformdirection": case "transformDirection": return target.getTransformDirection(); default: return super.getOptionValue(obj, name, ignoreCase); } } }
XJEndpointConfigurer
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromSourceTest.java
{ "start": 16535, "end": 18203 }
class ____ implements FlowableOnSubscribe<Integer>, FlowableSubscriber<Integer> { final PublishProcessor<Integer> processor; FlowableEmitter<Integer> current; PublishAsyncEmitter() { this.processor = PublishProcessor.create(); } long requested() { return current.requested(); } @Override public void subscribe(final FlowableEmitter<Integer> t) { this.current = t; final ResourceSubscriber<Integer> as = new ResourceSubscriber<Integer>() { @Override public void onComplete() { t.onComplete(); } @Override public void onError(Throwable e) { t.onError(e); } @Override public void onNext(Integer v) { t.onNext(v); } }; processor.subscribe(as); t.setCancellable(new Cancellable() { @Override public void cancel() throws Exception { as.dispose(); } });; } @Override public void onSubscribe(Subscription s) { s.request(Long.MAX_VALUE); } @Override public void onNext(Integer t) { processor.onNext(t); } @Override public void onError(Throwable e) { processor.onError(e); } @Override public void onComplete() { processor.onComplete(); } } static final
PublishAsyncEmitter
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java
{ "start": 32864, "end": 33198 }
class ____ { @Deprecated @InlineMe(replacement = "x * y") public int multiply(int x, int y) { return x * y; } } """) .expectUnchanged() .addInputLines( "Caller.java", """ public final
Client
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/formatmapper/FormatMapperBehaviorJsonObjectMapperCustomizerTest.java
{ "start": 341, "end": 1018 }
class ____ { @RegisterExtension static QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(MyJsonEntity.class, MyObjectMapperCustomizer.class) .addClasses(SchemaUtil.class, SmokeTestUtils.class)) .withConfigurationResource("application.properties") .assertException(ex -> assertThat(ex).hasCauseInstanceOf(IllegalStateException.class) .cause() .hasMessageContaining("set \"quarkus.hibernate-orm.mapping.format.global=ignore\"")); @Test void smoke() { } }
FormatMapperBehaviorJsonObjectMapperCustomizerTest
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/ObjectOfInputTypeStrategyTest.java
{ "start": 7282, "end": 7640 }
class ____, but was INT."), // Invalid test case - field name not a string TestSpec.forStrategy( "OBJECT_OF with non-string field name", OBJECT_OF_INPUT_STRATEGY) .calledWithArgumentTypes( DataTypes.STRING().notNull(), // implementation
name
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/streaming/runtime/MultipleInputITCase.java
{ "start": 7318, "end": 7918 }
class ____ extends AbstractInput<Long, Long> { public KeyedSumInput(AbstractStreamOperatorV2<Long> owner, int inputId) { super(owner, inputId); } @Override public void processElement(StreamRecord<Long> element) throws Exception { if (sumState.value() == null) { sumState.update(0L); } sumState.update(sumState.value() + element.getValue()); output.collect(element.replace(sumState.value())); } } } private static
KeyedSumInput
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/bytes/AbstractBytesReference.java
{ "start": 821, "end": 7560 }
class ____ implements BytesReference { protected final int length; private int hash; // we cache the hash of this reference since it can be quite costly to re-calculated it private boolean hashIsZero; // if the calculated hash is actually zero protected AbstractBytesReference(int length) { this.length = length; } @Override public final int length() { return length; } @Override public int getInt(int index) { return (get(index) & 0xFF) << 24 | (get(index + 1) & 0xFF) << 16 | (get(index + 2) & 0xFF) << 8 | get(index + 3) & 0xFF; } @Override public int getIntLE(int index) { return (get(index + 3) & 0xFF) << 24 | (get(index + 2) & 0xFF) << 16 | (get(index + 1) & 0xFF) << 8 | get(index) & 0xFF; } @Override public long getLongLE(int index) { return (long) (get(index + 7) & 0xFF) << 56 | (long) (get(index + 6) & 0xFF) << 48 | (long) (get(index + 5) & 0xFF) << 40 | (long) (get(index + 4) & 0xFF) << 32 | (long) (get(index + 3) & 0xFF) << 24 | (get(index + 2) & 0xFF) << 16 | (get(index + 1) & 0xFF) << 8 | get(index) & 0xFF; } @Override public double getDoubleLE(int index) { return Double.longBitsToDouble(getLongLE(index)); } @Override public int indexOf(byte marker, int from) { final int to = length(); for (int i = from; i < to; i++) { if (get(i) == marker) { return i; } } return -1; } @Override public StreamInput streamInput() throws IOException { return new BytesReferenceStreamInput(this); } @Override public void writeTo(OutputStream os) throws IOException { final BytesRefIterator iterator = iterator(); BytesRef ref; while ((ref = iterator.next()) != null) { os.write(ref.bytes, ref.offset, ref.length); } } @Override public String utf8ToString() { return toBytesRef().utf8ToString(); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof final BytesReference otherRef) { if (length() != otherRef.length()) { return false; } return compareIterators( this, otherRef, (a, b) -> a.bytesEquals(b) ? 0 : 1 // this is a call to BytesRef#bytesEquals - this method is the hot one in the comparison ) == 0; } return false; } @Override public int hashCode() { if (hash == 0 && hashIsZero == false) { final BytesRefIterator iterator = iterator(); BytesRef ref; int result = 1; try { while ((ref = iterator.next()) != null) { for (int i = 0; i < ref.length; i++) { result = 31 * result + ref.bytes[ref.offset + i]; } } } catch (IOException ex) { throw new AssertionError("wont happen", ex); } if (result == 0) { hashIsZero = true; } else { hash = result; } } return hash; } @Override public int compareTo(final BytesReference other) { return compareIterators(this, other, BytesRef::compareTo); } /** * Compares the two references using the given int function. */ private static int compareIterators(final BytesReference a, final BytesReference b, final ToIntBiFunction<BytesRef, BytesRef> f) { try { // we use the iterators since it's a 0-copy comparison where possible! final long lengthToCompare = Math.min(a.length(), b.length()); final BytesRefIterator aIter = a.iterator(); final BytesRefIterator bIter = b.iterator(); BytesRef aRef = aIter.next(); BytesRef bRef = bIter.next(); if (aRef != null && bRef != null) { // do we have any data? aRef = aRef.clone(); // we clone since we modify the offsets and length in the iteration below bRef = bRef.clone(); if (aRef.length == a.length() && bRef.length == b.length()) { // is it only one array slice we are comparing? return f.applyAsInt(aRef, bRef); } else { for (int i = 0; i < lengthToCompare;) { if (aRef.length == 0) { aRef = aIter.next().clone(); // must be non null otherwise we have a bug } if (bRef.length == 0) { bRef = bIter.next().clone(); // must be non null otherwise we have a bug } final int aLength = aRef.length; final int bLength = bRef.length; final int length = Math.min(aLength, bLength); // shrink to the same length and use the fast compare in lucene aRef.length = bRef.length = length; // now we move to the fast comparison - this is the hot part of the loop int diff = f.applyAsInt(aRef, bRef); aRef.length = aLength; bRef.length = bLength; if (diff != 0) { return diff; } advance(aRef, length); advance(bRef, length); i += length; } } } // One is a prefix of the other, or, they are equal: return a.length() - b.length(); } catch (IOException ex) { throw new AssertionError("can not happen", ex); } } private static void advance(final BytesRef ref, final int length) { assert ref.length >= length : " ref.length: " + ref.length + " length: " + length; assert ref.offset + length < ref.bytes.length || (ref.offset + length == ref.bytes.length && ref.length - length == 0) : "offset: " + ref.offset + " ref.bytes.length: " + ref.bytes.length + " length: " + length + " ref.length: " + ref.length; ref.length -= length; ref.offset += length; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { BytesRef bytes = toBytesRef(); return builder.value(bytes.bytes, bytes.offset, bytes.length); } }
AbstractBytesReference
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/exec/internal/CallbackImpl.java
{ "start": 453, "end": 1132 }
class ____ implements Callback { private final List<AfterLoadAction> afterLoadActions; public CallbackImpl() { afterLoadActions = new ArrayList<>( 1 ); } @Override public void registerAfterLoadAction(AfterLoadAction afterLoadAction) { afterLoadActions.add( afterLoadAction ); } @Override public void invokeAfterLoadActions(Object entity, EntityMappingType entityMappingType, SharedSessionContractImplementor session) { for ( int i = 0; i < afterLoadActions.size(); i++ ) { afterLoadActions.get( i ).afterLoad( entity, entityMappingType, session ); } } @Override public boolean hasAfterLoadActions() { return !afterLoadActions.isEmpty(); } }
CallbackImpl
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/test/ESTestCase.java
{ "start": 94599, "end": 94834 }
class ____ holds all analysis building blocks that are used * to build IndexAnalyzers. This is only for testing since in production we only need the * result and we don't even expose it there. */ public static final
just
java
mockito__mockito
mockito-integration-tests/module-named-tests/src/test/java/org/mockito/modulenamedtest/ModuleUseTest.java
{ "start": 1454, "end": 1559 }
class ____ { public String value() { return null; } } public static
Bar
java
apache__camel
core/camel-api/src/generated/java/org/apache/camel/ExchangeConstantProvider.java
{ "start": 322, "end": 10042 }
class ____ { private static final Map<String, String> MAP; static { Map<String, String> map = new HashMap<>(149); map.put("AGGREGATED_COLLECTION_GUARD", "CamelAggregatedCollectionGuard"); map.put("AGGREGATED_COMPLETED_BY", "CamelAggregatedCompletedBy"); map.put("AGGREGATED_CORRELATION_KEY", "CamelAggregatedCorrelationKey"); map.put("AGGREGATED_SIZE", "CamelAggregatedSize"); map.put("AGGREGATED_TIMEOUT", "CamelAggregatedTimeout"); map.put("AGGREGATION_COMPLETE_ALL_GROUPS", "CamelAggregationCompleteAllGroups"); map.put("AGGREGATION_COMPLETE_ALL_GROUPS_INCLUSIVE", "CamelAggregationCompleteAllGroupsInclusive"); map.put("AGGREGATION_COMPLETE_CURRENT_GROUP", "CamelAggregationCompleteCurrentGroup"); map.put("AGGREGATION_STRATEGY", "CamelAggregationStrategy"); map.put("ASYNC_WAIT", "CamelAsyncWait"); map.put("ATTACHMENTS_SIZE", "CamelAttachmentsSize"); map.put("AUTHENTICATION", "CamelAuthentication"); map.put("AUTHENTICATION_FAILURE_POLICY_ID", "CamelAuthenticationFailurePolicyId"); map.put("BATCH_COMPLETE", "CamelBatchComplete"); map.put("BATCH_INDEX", "CamelBatchIndex"); map.put("BATCH_SIZE", "CamelBatchSize"); map.put("BINDING", "CamelBinding"); map.put("BREADCRUMB_ID", "breadcrumbId"); map.put("CHARSET_NAME", "CamelCharsetName"); map.put("CIRCUIT_BREAKER_STATE", "CamelCircuitBreakerState"); map.put("CLAIM_CHECK_REPOSITORY", "CamelClaimCheckRepository"); map.put("CONTENT_ENCODING", "Content-Encoding"); map.put("CONTENT_LENGTH", "Content-Length"); map.put("CONTENT_SCHEMA", "CamelContentSchema"); map.put("CONTENT_SCHEMA_TYPE", "CamelContentSchemaType"); map.put("CONTENT_TYPE", "Content-Type"); map.put("COOKIE_HANDLER", "CamelCookieHandler"); map.put("CORRELATION_ID", "CamelCorrelationId"); map.put("DATASET_INDEX", "CamelDataSetIndex"); map.put("DEBUGGER_SELF_TIME", "CamelDebuggerSelfTime"); map.put("DEFAULT_CHARSET_PROPERTY", "org.apache.camel.default.charset"); map.put("DESTINATION_OVERRIDE_URL", "CamelDestinationOverrideUrl"); map.put("DISABLE_HTTP_STREAM_CACHE", "CamelDisableHttpStreamCache"); map.put("DOCUMENT_BUILDER_FACTORY", "CamelDocumentBuilderFactory"); map.put("DUPLICATE_MESSAGE", "CamelDuplicateMessage"); map.put("ERRORHANDLER_BRIDGE", "CamelErrorHandlerBridge"); map.put("ERRORHANDLER_CIRCUIT_DETECTED", "CamelErrorHandlerCircuitDetected"); map.put("EVALUATE_EXPRESSION_RESULT", "CamelEvaluateExpressionResult"); map.put("EXCEPTION_CAUGHT", "CamelExceptionCaught"); map.put("EXCEPTION_HANDLED", "CamelExceptionHandled"); map.put("FAILURE_ENDPOINT", "CamelFailureEndpoint"); map.put("FAILURE_HANDLED", "CamelFailureHandled"); map.put("FAILURE_ROUTE_ID", "CamelFailureRouteId"); map.put("FATAL_FALLBACK_ERROR_HANDLER", "CamelFatalFallbackErrorHandler"); map.put("FILE_CONTENT_TYPE", "CamelFileContentType"); map.put("FILE_EXCHANGE_FILE", "CamelFileExchangeFile"); map.put("FILE_LAST_MODIFIED", "CamelFileLastModified"); map.put("FILE_LENGTH", "CamelFileLength"); map.put("FILE_LOCAL_WORK_PATH", "CamelFileLocalWorkPath"); map.put("FILE_LOCK_CHANNEL_FILE", "CamelFileLockChannelFile"); map.put("FILE_LOCK_EXCLUSIVE_LOCK", "CamelFileLockExclusiveLock"); map.put("FILE_LOCK_FILE_ACQUIRED", "CamelFileLockFileAcquired"); map.put("FILE_LOCK_FILE_NAME", "CamelFileLockFileName"); map.put("FILE_LOCK_RANDOM_ACCESS_FILE", "CamelFileLockRandomAccessFile"); map.put("FILE_NAME", "CamelFileName"); map.put("FILE_NAME_CONSUMED", "CamelFileNameConsumed"); map.put("FILE_NAME_ONLY", "CamelFileNameOnly"); map.put("FILE_NAME_PRODUCED", "CamelFileNameProduced"); map.put("FILE_PARENT", "CamelFileParent"); map.put("FILE_PATH", "CamelFilePath"); map.put("FILTER_NON_XML_CHARS", "CamelFilterNonXmlChars"); map.put("GROUPED_EXCHANGE", "CamelGroupedExchange"); map.put("HTTP_BASE_URI", "CamelHttpBaseUri"); map.put("HTTP_CHARACTER_ENCODING", "CamelHttpCharacterEncoding"); map.put("HTTP_CHUNKED", "CamelHttpChunked"); map.put("HTTP_HOST", "CamelHttpHost"); map.put("HTTP_METHOD", "CamelHttpMethod"); map.put("HTTP_PATH", "CamelHttpPath"); map.put("HTTP_PORT", "CamelHttpPort"); map.put("HTTP_PROTOCOL_VERSION", "CamelHttpProtocolVersion"); map.put("HTTP_QUERY", "CamelHttpQuery"); map.put("HTTP_RAW_QUERY", "CamelHttpRawQuery"); map.put("HTTP_RESPONSE_CODE", "CamelHttpResponseCode"); map.put("HTTP_RESPONSE_TEXT", "CamelHttpResponseText"); map.put("HTTP_SCHEME", "CamelHttpScheme"); map.put("HTTP_SERVLET_REQUEST", "CamelHttpServletRequest"); map.put("HTTP_SERVLET_RESPONSE", "CamelHttpServletResponse"); map.put("HTTP_URI", "CamelHttpUri"); map.put("HTTP_URL", "CamelHttpUrl"); map.put("INTERCEPT_SEND_TO_ENDPOINT_WHEN_MATCHED", "CamelInterceptSendToEndpointWhenMatched"); map.put("INTERCEPTED_ENDPOINT", "CamelInterceptedEndpoint"); map.put("INTERCEPTED_NODE_ID", "CamelInterceptedNodeId"); map.put("INTERCEPTED_ROUTE_ENDPOINT_URI", "CamelInterceptedParentEndpointUri"); map.put("INTERCEPTED_ROUTE_ID", "CamelInterceptedRouteId"); map.put("JPA_ENTITY_MANAGER", "CamelEntityManager"); map.put("LANGUAGE_SCRIPT", "CamelLanguageScript"); map.put("LOG_DEBUG_BODY_MAX_CHARS", "CamelLogDebugBodyMaxChars"); map.put("LOG_DEBUG_BODY_STREAMS", "CamelLogDebugStreams"); map.put("LOG_EIP_LANGUAGE", "CamelLogEipLanguage"); map.put("LOG_EIP_NAME", "CamelLogEipName"); map.put("LOOP_INDEX", "CamelLoopIndex"); map.put("LOOP_SIZE", "CamelLoopSize"); map.put("MAXIMUM_CACHE_POOL_SIZE", "CamelMaximumCachePoolSize"); map.put("MAXIMUM_ENDPOINT_CACHE_SIZE", "CamelMaximumEndpointCacheSize"); map.put("MAXIMUM_SIMPLE_CACHE_SIZE", "CamelMaximumSimpleCacheSize"); map.put("MAXIMUM_TRANSFORMER_CACHE_SIZE", "CamelMaximumTransformerCacheSize"); map.put("MAXIMUM_VALIDATOR_CACHE_SIZE", "CamelMaximumValidatorCacheSize"); map.put("MESSAGE_HISTORY", "CamelMessageHistory"); map.put("MESSAGE_HISTORY_HEADER_FORMAT", "CamelMessageHistoryHeaderFormat"); map.put("MESSAGE_HISTORY_OUTPUT_FORMAT", "CamelMessageHistoryOutputFormat"); map.put("MESSAGE_TIMESTAMP", "CamelMessageTimestamp"); map.put("MULTICAST_COMPLETE", "CamelMulticastComplete"); map.put("MULTICAST_INDEX", "CamelMulticastIndex"); map.put("OFFSET", "CamelOffset"); map.put("ON_COMPLETION", "CamelOnCompletion"); map.put("ON_COMPLETION_ROUTE_IDS", "CamelOnCompletionRouteIds"); map.put("OTEL_ACTIVE_SPAN", "OpenTracing.activeSpan"); map.put("OTEL_CLOSE_CLIENT_SCOPE", "OpenTracing.closeClientScope"); map.put("OVERRULE_FILE_NAME", "CamelOverruleFileName"); map.put("PARENT_UNIT_OF_WORK", "CamelParentUnitOfWork"); map.put("RECEIVED_TIMESTAMP", "CamelReceivedTimestamp"); map.put("RECIPIENT_LIST_ENDPOINT", "CamelRecipientListEndpoint"); map.put("REDELIVERED", "CamelRedelivered"); map.put("REDELIVERY_COUNTER", "CamelRedeliveryCounter"); map.put("REDELIVERY_DELAY", "CamelRedeliveryDelay"); map.put("REDELIVERY_MAX_COUNTER", "CamelRedeliveryMaxCounter"); map.put("REST_HTTP_QUERY", "CamelRestHttpQuery"); map.put("REST_HTTP_URI", "CamelRestHttpUri"); map.put("REST_OPENAPI", "CamelRestOpenAPI"); map.put("SAGA_LONG_RUNNING_ACTION", "Long-Running-Action"); map.put("SCHEDULER_POLLED_MESSAGES", "CamelSchedulerPolledMessages"); map.put("SKIP_GZIP_ENCODING", "CamelSkipGzipEncoding"); map.put("SKIP_OVER", "CamelSkipOver"); map.put("SKIP_WWW_FORM_URLENCODED", "CamelSkipWwwFormUrlEncoding"); map.put("SLIP_ENDPOINT", "CamelSlipEndpoint"); map.put("SLIP_PRODUCER", "CamelSlipProducer"); map.put("SPLIT_COMPLETE", "CamelSplitComplete"); map.put("SPLIT_INDEX", "CamelSplitIndex"); map.put("SPLIT_SIZE", "CamelSplitSize"); map.put("STEP_ID", "CamelStepId"); map.put("STREAM_CACHE_UNIT_OF_WORK", "CamelStreamCacheUnitOfWork"); map.put("TIMER_COUNTER", "CamelTimerCounter"); map.put("TIMER_FIRED_TIME", "CamelTimerFiredTime"); map.put("TIMER_NAME", "CamelTimerName"); map.put("TIMER_PERIOD", "CamelTimerPeriod"); map.put("TIMER_TIME", "CamelTimerTime"); map.put("TO_ENDPOINT", "CamelToEndpoint"); map.put("TRACE_EVENT", "CamelTraceEvent"); map.put("TRACE_EVENT_EXCHANGE", "CamelTraceEventExchange"); map.put("TRACE_EVENT_NODE_ID", "CamelTraceEventNodeId"); map.put("TRACE_EVENT_TIMESTAMP", "CamelTraceEventTimestamp"); map.put("TRANSACTION_CONTEXT_DATA", "CamelTransactionContextData"); map.put("TRANSFER_ENCODING", "Transfer-Encoding"); map.put("TRY_ROUTE_BLOCK", "TryRouteBlock"); map.put("UNIT_OF_WORK_EXHAUSTED", "CamelUnitOfWorkExhausted"); map.put("XSLT_ERROR", "CamelXsltError"); map.put("XSLT_FATAL_ERROR", "CamelXsltFatalError"); map.put("XSLT_FILE_NAME", "CamelXsltFileName"); map.put("XSLT_WARNING", "CamelXsltWarning"); MAP = map; } public static String lookup(String key) { return MAP.get(key); } }
ExchangeConstantProvider
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/util/ConvertingFutureCallback.java
{ "start": 1472, "end": 1670 }
class ____ being retrieved via * {@link Future#get}. * @param <U> the callback result type * @param <T> the future result type obtained after converting the callback result */ public abstract
before
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/parsetools/RecordParser.java
{ "start": 2016, "end": 7988 }
interface ____ extends Handler<Buffer>, ReadStream<Buffer> { void setOutput(Handler<Buffer> output); /** * Like {@link #newDelimited(String)} but set the {@code output} that will receive whole records * which have been parsed. * * @param delim the initial delimiter string * @param output handler that will receive the output */ static RecordParser newDelimited(String delim, Handler<Buffer> output) { return RecordParserImpl.newDelimited(delim, null, output); } /** * Like {@link #newDelimited(String)} but wraps the {@code stream}. The {@code stream} handlers will be set/unset * when the {@link #handler(Handler)} is set. * <p/> * The {@code pause()}/{@code resume()} operations are propagated to the {@code stream}. * * @param delim the initial delimiter string * @param stream the wrapped stream */ static RecordParser newDelimited(String delim, ReadStream<Buffer> stream) { return RecordParserImpl.newDelimited(delim, stream, null); } /** * Create a new {@code RecordParser} instance, initially in delimited mode, and where the delimiter can be represented * by the String {@code} delim endcoded in latin-1 . Don't use this if your String contains other than latin-1 characters. * <p> * {@code output} Will receive whole records which have been parsed. * * @param delim the initial delimiter string */ static RecordParser newDelimited(String delim) { return RecordParserImpl.newDelimited(delim, null, null); } /** * Create a new {@code RecordParser} instance, initially in delimited mode, and where the delimiter can be represented * by the {@code Buffer} delim. * <p> * * @param delim the initial delimiter buffer */ static RecordParser newDelimited(Buffer delim) { return RecordParserImpl.newDelimited(delim,null, null); } /** * Like {@link #newDelimited(Buffer)} but set the {@code output} that will receive whole records * which have been parsed. * * @param delim the initial delimiter buffer * @param output handler that will receive the output */ static RecordParser newDelimited(Buffer delim, Handler<Buffer> output) { return RecordParserImpl.newDelimited(delim, null, output); } /** * Like {@link #newDelimited(Buffer)} but wraps the {@code stream}. The {@code stream} handlers will be set/unset * when the {@link #handler(Handler)} is set. * <p/> * The {@code pause()}/{@code resume()} operations are propagated to the {@code stream}. * * @param delim the initial delimiter buffer * @param stream the wrapped stream */ static RecordParser newDelimited(Buffer delim, ReadStream<Buffer> stream) { return RecordParserImpl.newDelimited(delim, stream, null); } /** * Create a new {@code RecordParser} instance, initially in fixed size mode, and where the record size is specified * by the {@code size} parameter. * <p> * {@code output} Will receive whole records which have been parsed. * * @param size the initial record size */ static RecordParser newFixed(int size) { return RecordParserImpl.newFixed(size, null, null); } /** * Like {@link #newFixed(int)} but set the {@code output} that will receive whole records * which have been parsed. * * @param size the initial record size * @param output handler that will receive the output */ static RecordParser newFixed(int size, Handler<Buffer> output) { return RecordParserImpl.newFixed(size, null, output); } /** * Like {@link #newFixed(int)} but wraps the {@code stream}. The {@code stream} handlers will be set/unset * when the {@link #handler(Handler)} is set. * <p/> * The {@code pause()}/{@code resume()} operations are propagated to the {@code stream}. * * @param size the initial record size * @param stream the wrapped stream */ static RecordParser newFixed(int size, ReadStream<Buffer> stream) { return RecordParserImpl.newFixed(size, stream, null); } /** * Flip the parser into delimited mode, and where the delimiter can be represented * by the String {@code delim} encoded in latin-1 . Don't use this if your String contains other than latin-1 characters. * <p> * This method can be called multiple times with different values of delim while data is being parsed. * * @param delim the new delimeter */ void delimitedMode(String delim); /** * Flip the parser into delimited mode, and where the delimiter can be represented * by the delimiter {@code delim}. * <p> * This method can be called multiple times with different values of delim while data is being parsed. * * @param delim the new delimiter */ void delimitedMode(Buffer delim); /** * Flip the parser into fixed size mode, where the record size is specified by {@code size} in bytes. * <p> * This method can be called multiple times with different values of size while data is being parsed. * * @param size the new record size */ void fixedSizeMode(int size); /** * Set the maximum allowed size for a record when using the delimited mode. * The delimiter itself does not count for the record size. * <p> * If a record is longer than specified, an {@link IllegalStateException} will be thrown. * * @param size the maximum record size * @return a reference to this, so the API can be used fluently */ @Fluent RecordParser maxRecordSize(int size); /** * This method is called to provide the parser with data. * * @param buffer a chunk of data */ void handle(Buffer buffer); @Override RecordParser exceptionHandler(Handler<Throwable> handler); @Override RecordParser handler(Handler<Buffer> handler); @Override RecordParser pause(); @Override RecordParser fetch(long amount); @Override RecordParser resume(); @Override RecordParser endHandler(Handler<Void> endHandler); }
RecordParser
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/aroundconstruct/AroundConstructExceptionHandlingTest.java
{ "start": 2364, "end": 2624 }
class ____ { static boolean intercepted = false; @AroundConstruct void aroundConstruct(InvocationContext ctx) { intercepted = true; throw new IllegalArgumentException("intentional"); } } }
MyInterceptor2
java
quarkusio__quarkus
extensions/oidc-client-graphql/deployment/src/main/java/io/quarkus/oidc/client/graphql/OidcGraphQLClientIntegrationProcessor.java
{ "start": 947, "end": 2850 }
class ____ { private static final DotName GRAPHQL_CLIENT_API = DotName .createSimple("io.smallrye.graphql.client.typesafe.api.GraphQLClientApi"); private static final String OIDC_CLIENT_FILTER = "io.quarkus.oidc.client.filter.OidcClientFilter"; @BuildStep void feature(BuildProducer<FeatureBuildItem> featureProducer) { featureProducer.produce(new FeatureBuildItem(Feature.OIDC_CLIENT_GRAPHQL_CLIENT_INTEGRATION)); } @BuildStep @Record(RUNTIME_INIT) void initialize(BeanContainerBuildItem containerBuildItem, OidcGraphQLClientIntegrationRecorder recorder, OidcClientGraphQLConfig config, BeanArchiveIndexBuildItem index, GraphQLClientConfigInitializedBuildItem configInitialized) { Map<String, String> configKeysToOidcClients = new HashMap<>(); for (AnnotationInstance annotation : index.getIndex().getAnnotations(GRAPHQL_CLIENT_API)) { ClassInfo clazz = annotation.target().asClass(); AnnotationInstance oidcClient = clazz.annotation(OIDC_CLIENT_FILTER); if (oidcClient != null) { String oidcClientName = oidcClient.valueWithDefault(index.getIndex(), "value").asString(); AnnotationValue configKeyValue = annotation.value("configKey"); String configKey = configKeyValue != null ? configKeyValue.asString() : null; String actualConfigKey = (configKey != null && !configKey.equals("")) ? configKey : clazz.name().toString(); if (oidcClientName != null && !oidcClientName.isEmpty()) { configKeysToOidcClients.put(actualConfigKey, oidcClientName); } } } recorder.enhanceGraphQLClientConfigurationWithOidc(configKeysToOidcClients, config.clientName().orElse(null)); } }
OidcGraphQLClientIntegrationProcessor
java
google__dagger
javatests/dagger/internal/codegen/SubcomponentCreatorValidationTest.java
{ "start": 16111, "end": 16236 }
interface ____ {", " String build();", " }", "", " @Subcomponent.Builder", "
Parent
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/transport/TransportInfoTests.java
{ "start": 996, "end": 3302 }
class ____ extends ESTestCase { private TransportInfo createTransportInfo(InetAddress address, int port) { BoundTransportAddress boundAddress = new BoundTransportAddress( new TransportAddress[] { new TransportAddress(address, port) }, new TransportAddress(address, port) ); Map<String, BoundTransportAddress> profiles = Collections.singletonMap("test_profile", boundAddress); return new TransportInfo(boundAddress, profiles); } public void testCorrectlyDisplayPublishedCname() throws Exception { InetAddress address = InetAddress.getByName("localhost"); int port = 9200; assertPublishAddress(createTransportInfo(address, port), "localhost/" + NetworkAddress.format(address) + ':' + port); } public void testCorrectDisplayPublishedIp() throws Exception { InetAddress address = InetAddress.getByName(NetworkAddress.format(InetAddress.getByName("localhost"))); int port = 9200; assertPublishAddress(createTransportInfo(address, port), NetworkAddress.format(address) + ':' + port); } public void testCorrectDisplayPublishedIpv6() throws Exception { InetAddress address = InetAddress.getByName(NetworkAddress.format(InetAddress.getByName("0:0:0:0:0:0:0:1"))); int port = 9200; assertPublishAddress(createTransportInfo(address, port), new TransportAddress(address, port).toString()); } @SuppressWarnings("unchecked") private void assertPublishAddress(TransportInfo httpInfo, String expected) throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); httpInfo.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); Map<String, Object> transportMap; try (var parser = createParser(builder)) { transportMap = (Map<String, Object>) parser.map().get(TransportInfo.Fields.TRANSPORT); } Map<String, Object> profilesMap = (Map<String, Object>) transportMap.get("profiles"); assertEquals(expected, transportMap.get(TransportInfo.Fields.PUBLISH_ADDRESS)); assertEquals(expected, ((Map<String, Object>) profilesMap.get("test_profile")).get(TransportInfo.Fields.PUBLISH_ADDRESS)); } }
TransportInfoTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/dates/Dates_assertIsToday_Test.java
{ "start": 1557, "end": 3678 }
class ____ extends DatesBaseTest { @Test void should_fail_if_actual_is_not_today() { AssertionInfo info = someInfo(); actual = parseDate("2111-01-01"); Throwable error = catchThrowable(() -> dates.assertIsToday(info, actual)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeToday(actual)); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> dates.assertIsToday(someInfo(), null)) .withMessage(actualIsNull()); } @Test void should_pass_if_actual_is_today() { dates.assertIsToday(someInfo(), new Date()); } @Test void should_fail_if_actual_is_not_today_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); actual = parseDate("2111-01-01"); Throwable error = catchThrowable(() -> datesWithCustomComparisonStrategy.assertIsToday(info, actual)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeToday(actual, yearAndMonthComparisonStrategy)); } @Test void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> datesWithCustomComparisonStrategy.assertIsToday(someInfo(), null)) .withMessage(actualIsNull()); } @Test void should_pass_if_actual_is_today_according_to_custom_comparison_strategy() { // we want actual to be different from today but still in the same month so that it is equal to today // according to our comparison strategy (that compares only month and year). // => if we are at the end of the month we subtract one day instead of adding one actual = monthOf(tomorrow()) == monthOf(new Date()) ? tomorrow() : yesterday(); datesWithCustomComparisonStrategy.assertIsToday(someInfo(), actual); } }
Dates_assertIsToday_Test
java
alibaba__nacos
common/src/test/java/com/alibaba/nacos/common/utils/ArrayUtilsTest.java
{ "start": 860, "end": 1736 }
class ____ { Integer[] nullArr = null; Integer[] nothingArr = new Integer[] {}; @Test void testisEmpty() { Integer[] arr = new Integer[] {1, 2}; assertTrue(ArrayUtils.isEmpty(nullArr)); assertTrue(ArrayUtils.isEmpty(nothingArr)); assertFalse(ArrayUtils.isEmpty(arr)); } @Test void contains() { assertFalse(ArrayUtils.contains(nullArr, "a")); assertFalse(ArrayUtils.contains(nullArr, null)); assertFalse(ArrayUtils.contains(nothingArr, "b")); Integer[] arr = new Integer[] {1, 2, 3}; assertFalse(ArrayUtils.contains(arr, null)); Integer[] arr1 = new Integer[] {1, 2, 3, null}; assertTrue(ArrayUtils.contains(arr1, null)); assertTrue(ArrayUtils.contains(arr, 1)); assertFalse(ArrayUtils.contains(arr, "1")); } }
ArrayUtilsTest
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/QueryStringEncoder.java
{ "start": 1361, "end": 3930 }
class ____ { private final Charset charset; private final StringBuilder uriBuilder; private boolean hasParams; private static final byte WRITE_UTF_UNKNOWN = (byte) '?'; private static final char[] CHAR_MAP = "0123456789ABCDEF".toCharArray(); /** * Creates a new encoder that encodes a URI that starts with the specified * path string. The encoder will encode the URI in UTF-8. */ public QueryStringEncoder(String uri) { this(uri, HttpConstants.DEFAULT_CHARSET); } /** * Creates a new encoder that encodes a URI that starts with the specified * path string in the specified charset. */ public QueryStringEncoder(String uri, Charset charset) { ObjectUtil.checkNotNull(charset, "charset"); uriBuilder = new StringBuilder(uri); this.charset = CharsetUtil.UTF_8.equals(charset) ? null : charset; } /** * Adds a parameter with the specified name and value to this encoder. */ public void addParam(String name, String value) { ObjectUtil.checkNotNull(name, "name"); if (hasParams) { uriBuilder.append('&'); } else { uriBuilder.append('?'); hasParams = true; } encodeComponent(name); if (value != null) { uriBuilder.append('='); encodeComponent(value); } } private void encodeComponent(CharSequence s) { if (charset == null) { encodeUtf8Component(s); } else { encodeNonUtf8Component(s); } } /** * Returns the URL-encoded URI object which was created from the path string * specified in the constructor and the parameters added by * {@link #addParam(String, String)} method. */ public URI toUri() throws URISyntaxException { return new URI(toString()); } /** * Returns the URL-encoded URI which was created from the path string * specified in the constructor and the parameters added by * {@link #addParam(String, String)} method. */ @Override public String toString() { return uriBuilder.toString(); } /** * Encode the String as per RFC 3986, Section 2. * <p> * There is a little different between the JDK's encode method : {@link URLEncoder#encode(String, String)}. * The JDK's encoder encode the space to {@code +} and this method directly encode the blank to {@code %20} * beyond that , this method reuse the {@link #uriBuilder} in this
QueryStringEncoder
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/CompositeMap.java
{ "start": 1183, "end": 4369 }
class ____<K, V> implements Map<K, V> { private final Map<K,V> first; private final Map<K,V> second; private final @Nullable BiFunction<K,V,V> putFunction; private final @Nullable Consumer<Map<K, V>> putAllFunction; CompositeMap(Map<K, V> first, Map<K, V> second) { this(first, second, null, null); } CompositeMap(Map<K, V> first, Map<K, V> second, @Nullable BiFunction<K, V, V> putFunction, @Nullable Consumer<Map<K,V>> putAllFunction) { Assert.notNull(first, "First must not be null"); Assert.notNull(second, "Second must not be null"); this.first = first; this.second = new FilteredMap<>(second, key -> !this.first.containsKey(key)); this.putFunction = putFunction; this.putAllFunction = putAllFunction; } @Override public int size() { return this.first.size() + this.second.size(); } @Override public boolean isEmpty() { return this.first.isEmpty() && this.second.isEmpty(); } @Override public boolean containsKey(Object key) { if (this.first.containsKey(key)) { return true; } else { return this.second.containsKey(key); } } @Override public boolean containsValue(Object value) { if (this.first.containsValue(value)) { return true; } else { return this.second.containsValue(value); } } @Override public @Nullable V get(Object key) { V firstResult = this.first.get(key); if (firstResult != null) { return firstResult; } else { return this.second.get(key); } } @Override public @Nullable V put(K key, V value) { if (this.putFunction == null) { throw new UnsupportedOperationException(); } else { return this.putFunction.apply(key, value); } } @Override public @Nullable V remove(Object key) { V firstResult = this.first.remove(key); V secondResult = this.second.remove(key); if (firstResult != null) { return firstResult; } else { return secondResult; } } @Override @SuppressWarnings("unchecked") public void putAll(Map<? extends K, ? extends V> m) { if (this.putAllFunction != null) { this.putAllFunction.accept((Map<K, V>) m); } else { for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) { put(e.getKey(), e.getValue()); } } } @Override public void clear() { this.first.clear(); this.second.clear(); } @Override public Set<K> keySet() { return new CompositeSet<>(this.first.keySet(), this.second.keySet()); } @Override public Collection<V> values() { return new CompositeCollection<>(this.first.values(), this.second.values()); } @Override public Set<Entry<K, V>> entrySet() { return new CompositeSet<>(this.first.entrySet(), this.second.entrySet()); } @Override public String toString() { Iterator<Entry<K, V>> i = entrySet().iterator(); if (!i.hasNext()) { return "{}"; } StringBuilder sb = new StringBuilder(); sb.append('{'); while (true) { Entry<K, V> e = i.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key); sb.append('='); sb.append(value == this ? "(this Map)" : value); if (!i.hasNext()) { return sb.append('}').toString(); } sb.append(',').append(' '); } } }
CompositeMap
java
redisson__redisson
redisson/src/main/java/org/redisson/api/stream/StreamReadGroupParams.java
{ "start": 768, "end": 1642 }
class ____ implements StreamReadGroupArgs { private boolean noAck; private final StreamMessageId id1; private int count; private Duration timeout; StreamReadGroupParams(StreamMessageId id1) { this.id1 = id1; } @Override public StreamReadGroupArgs noAck() { this.noAck = true; return this; } @Override public StreamReadGroupArgs count(int count) { this.count = count; return this; } @Override public StreamReadGroupArgs timeout(Duration timeout) { this.timeout = timeout; return this; } public boolean isNoAck() { return noAck; } public StreamMessageId getId1() { return id1; } public int getCount() { return count; } public Duration getTimeout() { return timeout; } }
StreamReadGroupParams
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java
{ "start": 20594, "end": 21034 }
class ____ implements AsyncInterface { @Override public void doSomething(int i) { assertThat(Thread.currentThread().getName()).isNotEqualTo(originalThreadName); } @Override @SuppressWarnings("deprecation") public Future<String> returnSomething(int i) { assertThat(Thread.currentThread().getName()).isNotEqualTo(originalThreadName); return new AsyncResult<>(Integer.toString(i)); } } public static
AsyncInterfaceBean
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitchTest.java
{ "start": 3384, "end": 4079 }
enum ____ { ONE, TWO, THREE, UNRECOGNIZED } boolean m(Case c) { switch (c) { case ONE: case TWO: case THREE: return true; case UNRECOGNIZED: break; } // This is a comment throw new AssertionError(c); } } """) .doTest(TEXT_MATCH); } @Test public void emptyDefault() { refactoringTestHelper .addInputLines( "in/Test.java", """
Case
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/cluster/ClusterTestSettings.java
{ "start": 164, "end": 1346 }
class ____ extends TestSupport { public static final String host = TestSettings.hostAddr(); public static final int SLOT_A = SlotHash.getSlot("a".getBytes()); public static final int SLOT_B = SlotHash.getSlot("b".getBytes()); // default test cluster 2 masters + 2 slaves public static final int port1 = TestSettings.port(900); public static final int port2 = port1 + 1; public static final int port3 = port1 + 2; public static final int port4 = port1 + 3; // master+replica or master+master public static final int port5 = port1 + 4; public static final int port6 = port1 + 5; // auth cluster public static final int port7 = port1 + 6; public static final String KEY_A = "a"; public static final String KEY_B = "b"; public static final String KEY_D = "d"; /** * Don't allow instances. */ private ClusterTestSettings() { } public static int[] createSlots(int from, int to) { int[] result = new int[to - from]; int counter = 0; for (int i = from; i < to; i++) { result[counter++] = i; } return result; } }
ClusterTestSettings
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/stream/state/MultiJoinStateViews.java
{ "start": 2148, "end": 2699 }
class ____ create different implementations of {@link MultiJoinStateView} based on the * characteristics described in {@link JoinInputSideSpec}. * * <p>Each state view uses a {@link MapState} where the primary key is the `joinKey` derived from * the join conditions (via {@link * org.apache.flink.table.runtime.operators.join.stream.keyselector.JoinKeyExtractor}). The value * stored within this map depends on whether the input side has a unique key and how it relates to * the join key, optimizing storage and access patterns. */ public final
to
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/NotFoundExceptionMapperTestCase.java
{ "start": 438, "end": 3566 }
class ____ { private static final String META_INF_RESOURCES = "META-INF/resources/"; @RegisterExtension static QuarkusDevModeTest test = new QuarkusDevModeTest() .withApplicationRoot((jar) -> jar .addClasses(RootResource.class) .addAsResource(new StringAsset("index content"), META_INF_RESOURCES + "index.html")); @Test public void testResourceNotFound() { // test the exception mapper provided in dev mode, if no accept, will just return a plain 404 RestAssured.when().get("/not_found") .then() .statusCode(404); } @Test public void testHtmlResourceNotFound() { // test the exception mapper provided in dev mode, if no accept, will just return a plain 404 RestAssured.given().accept(ContentType.HTML) .when().get("/not_found") .then() .statusCode(404) .contentType(ContentType.HTML) .body(containsString("/index.html")) // check that index.html is displayed .body(Matchers.containsString("<div class=\"callout\">404 - Resource Not Found</div>")); } @Test public void testJsonResourceNotFound() { // test the default exception mapper provided in dev mode : displays json when accept is application/json RestAssured.given().accept(ContentType.JSON) .when().get("/not_found") .then() .statusCode(404) .contentType(ContentType.JSON); } @Test public void shouldDisplayNewAddedFileIn404ErrorPage() { String CONTENT = "html content"; test.addResourceFile(META_INF_RESOURCES + "index2.html", CONTENT); RestAssured.get("/index2.html") .then() .statusCode(200) .body(containsString(CONTENT)); // check that index2.html is live reloaded RestAssured.given() .accept(ContentType.HTML) .when() .get("/api") .then() // try to load unknown path .statusCode(404) .body(containsString("index2.html")); // check that index2.html is displayed } @Test public void shouldNotDisplayDeletedFileIn404ErrorPage() { String TEST_CONTENT = "test html content"; test.addResourceFile(META_INF_RESOURCES + "test.html", TEST_CONTENT); RestAssured .get("/test.html") .then() .statusCode(200) .body(containsString(TEST_CONTENT)); // check that test.html is live reloaded test.deleteResourceFile(META_INF_RESOURCES + "test.html"); // delete test.html file RestAssured .given() .accept(ContentType.HTML) .when() .get("/test.html") .then() // try to load static file .statusCode(404) .body(not(containsString("test.html"))); // check that test.html is not displayed } }
NotFoundExceptionMapperTestCase
java
quarkusio__quarkus
devtools/gradle/gradle-extension-plugin/src/main/java/io/quarkus/extension/gradle/dsl/Capabilities.java
{ "start": 101, "end": 757 }
class ____ { private List<Capability> provided = new ArrayList<>(0); private List<Capability> required = new ArrayList<>(0); public Capability provides(String name) { Capability capability = new Capability(name); provided.add(capability); return capability; } public Capability requires(String name) { Capability capability = new Capability(name); required.add(capability); return capability; } public List<Capability> getProvidedCapabilities() { return provided; } public List<Capability> getRequiredCapabilities() { return required; } }
Capabilities
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/commands/transactional/GeoTxCommandIntegrationTests.java
{ "start": 372, "end": 1251 }
class ____ extends GeoCommandIntegrationTests { @Inject GeoTxCommandIntegrationTests(StatefulRedisConnection<String, String> connection) { super(TxSyncInvocationHandler.sync(connection)); } @Disabled @Override public void georadiusbymemberWithArgsInTransaction() { } @Disabled @Override public void geoaddInTransaction() { } @Disabled @Override public void geoaddMultiInTransaction() { } @Disabled @Override public void geoposInTransaction() { } @Disabled @Override public void georadiusWithArgsAndTransaction() { } @Disabled @Override public void georadiusInTransaction() { } @Disabled @Override public void geodistInTransaction() { } @Disabled @Override public void geohashInTransaction() { } }
GeoTxCommandIntegrationTests
java
quarkusio__quarkus
extensions/smallrye-health/deployment/src/test/java/io/quarkus/smallrye/health/test/WellnessHealthCheckTest.java
{ "start": 1190, "end": 1385 }
class ____ implements HealthCheck { @Override public HealthCheckResponse call() { return HealthCheckResponse.up(WellnessHC.class.getName()); } } }
WellnessHC
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/commit/staging/StagingTestBase.java
{ "start": 11191, "end": 12085 }
class ____ extends HadoopTestBase { private static MiniDFSClusterService hdfs; private static JobConf conf = null; protected static JobConf getConfiguration() { return conf; } protected static FileSystem getDFS() { return hdfs.getClusterFS(); } /** * Setup the mini HDFS cluster. * @throws IOException Failure */ @BeforeAll @SuppressWarnings("deprecation") public static void setupHDFS() throws IOException { if (hdfs == null) { JobConf c = new JobConf(); hdfs = new MiniDFSClusterService(); hdfs.init(c); hdfs.start(); conf = c; } } @SuppressWarnings("ThrowableNotThrown") @AfterAll public static void teardownFS() throws IOException { ServiceOperations.stopQuietly(hdfs); conf = null; hdfs = null; } } /** * Base
MiniDFSTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/property/access/spi/GetterFieldImpl.java
{ "start": 818, "end": 2645 }
class ____ implements Getter { private final Class<?> containerClass; private final String propertyName; private final Field field; private final @Nullable Method getterMethod; public GetterFieldImpl(Class<?> containerClass, String propertyName, Field field) { this ( containerClass, propertyName, field, findGetterMethodForFieldAccess( field, propertyName ) ); } GetterFieldImpl(Class<?> containerClass, String propertyName, Field field, Method getterMethod) { this.containerClass = containerClass; this.propertyName = propertyName; this.field = field; this.getterMethod = getterMethod; } @Override public @Nullable Object get(Object owner) { try { return field.get( owner ); } catch (Exception e) { throw new PropertyAccessException( String.format( Locale.ROOT, "Error accessing field [%s] by reflection for persistent property [%s#%s] : %s", field.toGenericString(), containerClass.getName(), propertyName, owner ), e ); } } @Override public @Nullable Object getForInsert(Object owner, Map<Object, Object> mergeMap, SharedSessionContractImplementor session) { return get( owner ); } @Override public Class<?> getReturnTypeClass() { return field.getType(); } @Override public Type getReturnType() { return field.getGenericType(); } public Field getField() { return field; } @Override public Member getMember() { return getField(); } @Override public @Nullable String getMethodName() { return getterMethod != null ? getterMethod.getName() : null; } @Override public @Nullable Method getMethod() { return getterMethod; } @Serial private Object writeReplace() throws ObjectStreamException { return new SerialForm( containerClass, propertyName, field ); } private static
GetterFieldImpl
java
elastic__elasticsearch
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/planner/ExpressionTranslators.java
{ "start": 10559, "end": 11283 }
class ____ extends ExpressionTranslator<IsNull> { @Override protected Query asQuery(IsNull isNull, TranslatorHandler handler) { return doTranslate(isNull, handler); } public static Query doTranslate(IsNull isNull, TranslatorHandler handler) { return handler.wrapFunctionQuery(isNull, isNull.field(), () -> translate(isNull, handler)); } private static Query translate(IsNull isNull, TranslatorHandler handler) { return new NotQuery(isNull.source(), new ExistsQuery(isNull.source(), handler.nameOf(isNull.field()))); } } // assume the Optimizer properly orders the predicates to ease the translation public static
IsNulls
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
{ "start": 22528, "end": 23049 }
interface ____ further up the inheritance chain // than the previously found match if (isAssignable(midClass, superClass) && isAssignable(genericInterface, (Type) midClass)) { genericInterface = midType; } } // found a match? if (genericInterface != null) { return genericInterface; } } // none of the interfaces were descendants of the target class, so the // super
is
java
apache__camel
components/camel-huawei/camel-huaweicloud-iam/src/generated/java/org/apache/camel/component/huaweicloud/iam/IAMEndpointConfigurer.java
{ "start": 742, "end": 5373 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { IAMEndpoint target = (IAMEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": target.setAccessKey(property(camelContext, java.lang.String.class, value)); return true; case "groupid": case "groupId": target.setGroupId(property(camelContext, java.lang.String.class, value)); return true; case "ignoresslverification": case "ignoreSslVerification": target.setIgnoreSslVerification(property(camelContext, boolean.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "proxyhost": case "proxyHost": target.setProxyHost(property(camelContext, java.lang.String.class, value)); return true; case "proxypassword": case "proxyPassword": target.setProxyPassword(property(camelContext, java.lang.String.class, value)); return true; case "proxyport": case "proxyPort": target.setProxyPort(property(camelContext, int.class, value)); return true; case "proxyuser": case "proxyUser": target.setProxyUser(property(camelContext, java.lang.String.class, value)); return true; case "region": target.setRegion(property(camelContext, java.lang.String.class, value)); return true; case "secretkey": case "secretKey": target.setSecretKey(property(camelContext, java.lang.String.class, value)); return true; case "servicekeys": case "serviceKeys": target.setServiceKeys(property(camelContext, org.apache.camel.component.huaweicloud.common.models.ServiceKeys.class, value)); return true; case "userid": case "userId": target.setUserId(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": return java.lang.String.class; case "groupid": case "groupId": return java.lang.String.class; case "ignoresslverification": case "ignoreSslVerification": return boolean.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "proxyhost": case "proxyHost": return java.lang.String.class; case "proxypassword": case "proxyPassword": return java.lang.String.class; case "proxyport": case "proxyPort": return int.class; case "proxyuser": case "proxyUser": return java.lang.String.class; case "region": return java.lang.String.class; case "secretkey": case "secretKey": return java.lang.String.class; case "servicekeys": case "serviceKeys": return org.apache.camel.component.huaweicloud.common.models.ServiceKeys.class; case "userid": case "userId": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { IAMEndpoint target = (IAMEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": return target.getAccessKey(); case "groupid": case "groupId": return target.getGroupId(); case "ignoresslverification": case "ignoreSslVerification": return target.isIgnoreSslVerification(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "proxyhost": case "proxyHost": return target.getProxyHost(); case "proxypassword": case "proxyPassword": return target.getProxyPassword(); case "proxyport": case "proxyPort": return target.getProxyPort(); case "proxyuser": case "proxyUser": return target.getProxyUser(); case "region": return target.getRegion(); case "secretkey": case "secretKey": return target.getSecretKey(); case "servicekeys": case "serviceKeys": return target.getServiceKeys(); case "userid": case "userId": return target.getUserId(); default: return null; } } }
IAMEndpointConfigurer
java
micronaut-projects__micronaut-core
http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/ExpressionTest.java
{ "start": 1353, "end": 2252 }
class ____ { public static final String SPEC_NAME = "ExpressionTest"; @Test void testConditionalGetRequest() throws IOException { asserts(SPEC_NAME, HttpRequest.GET("/expr/test"), (server, request) -> AssertionUtils.assertThrows(server, request, HttpResponseAssertion.builder() .status(HttpStatus.NOT_FOUND) .build())); asserts(SPEC_NAME, HttpRequest.GET("/expr/test") .header(HttpHeaders.AUTHORIZATION, "foo"), (server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("ok") .build())); } @Controller("/expr") @Requires(property = "spec.name", value = SPEC_NAME) static
ExpressionTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/WindowsSecureContainerExecutor.java
{ "start": 2980, "end": 3259 }
class ____ extends DefaultContainerExecutor { private static final Logger LOG = LoggerFactory .getLogger(WindowsSecureContainerExecutor.class); public static final String LOCALIZER_PID_FORMAT = "STAR_LOCALIZER_%s"; /** * This
WindowsSecureContainerExecutor
java
apache__flink
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/sstmerge/CompactionTask.java
{ "start": 1127, "end": 2389 }
class ____ { final int level; final List<String> files; final ColumnFamilyHandle columnFamilyHandle; CompactionTask(int level, List<String> files, ColumnFamilyHandle columnFamilyHandle) { checkArgument(!files.isEmpty()); checkArgument(level >= 0); this.level = level; this.files = checkNotNull(files); this.columnFamilyHandle = checkNotNull(columnFamilyHandle); } @Override public String toString() { return "CompactionTask{" + "level=" + level + ", files=" + files + ", columnFamily=" + columnFamilyHandle + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompactionTask that = (CompactionTask) o; return level == that.level && Objects.equals(files, that.files) && Objects.equals(columnFamilyHandle, that.columnFamilyHandle); } @Override public int hashCode() { return Objects.hash(level, files, columnFamilyHandle); } }
CompactionTask
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/javaconfig/JavaConfigReferenceBeanTest.java
{ "start": 21537, "end": 21895 }
class ____ { // The ReferenceBean is missing necessary generic type @Bean @DubboReference(group = "${myapp.group}", interfaceClass = DemoService.class) public ReferenceBean helloService() { return new ReferenceBean(); } } @Configuration public static
MissingGenericTypeAnnotationBeanConfiguration
java
netty__netty
handler/src/main/java/io/netty/handler/pcap/PcapWriteHandler.java
{ "start": 34407, "end": 34609 }
enum ____ { TCP, UDP } public static Builder builder() { return new Builder(); } /** * Builder for {@link PcapWriteHandler} */ public static final
ChannelType
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/RuntimeExchangeException.java
{ "start": 914, "end": 1791 }
class ____ extends RuntimeCamelException { private final transient Exchange exchange; public RuntimeExchangeException(String message, Exchange exchange) { super(createMessage(message, exchange)); this.exchange = exchange; } public RuntimeExchangeException(String message, Exchange exchange, Throwable cause) { super(createMessage(message, exchange), cause); this.exchange = exchange; } /** * Returns the exchange which caused the exception * <p/> * Can be <tt>null</tt> */ public Exchange getExchange() { return exchange; } protected static String createMessage(String message, Exchange exchange) { if (exchange != null) { return message + " on the exchange: " + exchange; } else { return message; } } }
RuntimeExchangeException
java
quarkusio__quarkus
integration-tests/maven/src/test/resources-filtered/projects/multimodule-parent-dep/level0/src/main/java/org/acme/level0/Level0Service.java
{ "start": 169, "end": 320 }
class ____ { @ConfigProperty(name = "greeting") String greeting; public String getGreeting() { return greeting; } }
Level0Service
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/bean/BeanPropertiesFunctionTest.java
{ "start": 1998, "end": 2089 }
class ____ { public String bar() { return "bar"; } } }
BarBean
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/spi/Provider.java
{ "start": 7469, "end": 7807 }
class ____ of a LoggerContextFactory implementation or {@code null} if unspecified. * @see #loadLoggerContextFactory() */ public @Nullable String getClassName() { return loggerContextFactoryClass != null ? loggerContextFactoryClass.getName() : className; } /** * Loads the {@link LoggerContextFactory}
name
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/odps/OdpsFormatCommentTest6.java
{ "start": 255, "end": 1283 }
class ____ extends TestCase { public void test_column_comment() throws Exception { String sql = "select *" + "\nfrom t "// + "\nwhere status = '20' -- comment xxx" + "\nand flag & 127 > 0 -- comment kkkkk" + "\n;"; SQLStatement stmt = SQLUtils .parseSingleStatement(sql, DbType.odps, SQLParserFeature.KeepComments, SQLParserFeature.EnableSQLBinaryOpExprGroup); System.out.println("第一次生成的sql===" + stmt.toString()); SQLStatement stmt2 = SQLUtils .parseSingleStatement(stmt.toString(), DbType.odps, SQLParserFeature.KeepComments, SQLParserFeature.EnableSQLBinaryOpExprGroup); System.out.println("第二次生成的sql===" + stmt2.toString()); assertEquals("SELECT *" + "\nFROM t" + "\nWHERE status = '20' -- comment xxx" + "\n\tAND flag & 127 > 0 -- comment kkkkk\n;", SQLUtils.formatOdps(sql)); } }
OdpsFormatCommentTest6
java
spring-projects__spring-boot
configuration-metadata/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/method/InvalidMethodConfig.java
{ "start": 909, "end": 1184 }
class ____ { private String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } @TestConfigurationProperties("invalid") InvalidMethodConfig foo() { return new InvalidMethodConfig(); } }
InvalidMethodConfig
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TearDownNotRunTest.java
{ "start": 5963, "end": 6100 }
class ____ { private void tearDown() {} } @RunWith(JUnit4.class)
J4TearDownPrivateTearDown
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/materializedtable/AlterMaterializedTableOperation.java
{ "start": 1181, "end": 1564 }
class ____ implements AlterOperation, MaterializedTableOperation { protected final ObjectIdentifier tableIdentifier; public AlterMaterializedTableOperation(ObjectIdentifier tableIdentifier) { this.tableIdentifier = tableIdentifier; } public ObjectIdentifier getTableIdentifier() { return tableIdentifier; } }
AlterMaterializedTableOperation
java
spring-projects__spring-boot
module/spring-boot-pulsar/src/test/java/org/springframework/boot/pulsar/autoconfigure/PulsarAutoConfigurationTests.java
{ "start": 33422, "end": 35885 }
class ____ { private final ApplicationContextRunner contextRunner = PulsarAutoConfigurationTests.this.contextRunner; @Test @SuppressWarnings("unchecked") void whenHasUserDefinedBeanDoesNotAutoConfigureBean() { PulsarConsumerFactory<String> consumerFactory = mock(PulsarConsumerFactory.class); this.contextRunner .withBean("customPulsarConsumerFactory", PulsarConsumerFactory.class, () -> consumerFactory) .run((context) -> assertThat(context).getBean(PulsarConsumerFactory.class).isSameAs(consumerFactory)); } @Test void injectsExpectedBeans() { this.contextRunner.run((context) -> assertThat(context).getBean(DefaultPulsarConsumerFactory.class) .hasFieldOrPropertyWithValue("pulsarClient", context.getBean(PulsarClient.class)) .extracting("topicBuilder") .isNotNull()); } @Test void hasNoTopicBuilderWhenTopicDefaultsAreDisabled() { this.contextRunner.withPropertyValues("spring.pulsar.defaults.topic.enabled=false") .run((context) -> assertThat(context).getBean(DefaultPulsarConsumerFactory.class) .hasFieldOrPropertyWithValue("pulsarClient", context.getBean(PulsarClient.class)) .extracting("topicBuilder") .isNull()); } @Test <T> void whenHasUserDefinedCustomizersAppliesInCorrectOrder() { this.contextRunner.withPropertyValues("spring.pulsar.consumer.name=fromPropsCustomizer") .withUserConfiguration(ConsumerBuilderCustomizersConfig.class) .run((context) -> { DefaultPulsarConsumerFactory<?> consumerFactory = context .getBean(DefaultPulsarConsumerFactory.class); Customizers<ConsumerBuilderCustomizer<T>, ConsumerBuilder<T>> customizers = Customizers .of(ConsumerBuilder.class, ConsumerBuilderCustomizer::customize); assertThat(customizers.fromField(consumerFactory, "defaultConfigCustomizers")).callsInOrder( ConsumerBuilder::consumerName, "fromPropsCustomizer", "fromCustomizer1", "fromCustomizer2"); }); } @Test void injectsExpectedBeanWithExplicitGenericType() { this.contextRunner.withBean(ExplicitGenericTypeConfig.class) .run((context) -> assertThat(context).getBean(ExplicitGenericTypeConfig.class) .hasFieldOrPropertyWithValue("consumerFactory", context.getBean(PulsarConsumerFactory.class)) .hasFieldOrPropertyWithValue("containerFactory", context.getBean(ConcurrentPulsarListenerContainerFactory.class))); } @TestConfiguration(proxyBeanMethods = false) static
ConsumerFactoryTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/property/access/internal/PropertyAccessStrategyIndexBackRefImpl.java
{ "start": 674, "end": 1230 }
class ____ implements PropertyAccessStrategy { private final String entityName; private final String propertyName; public PropertyAccessStrategyIndexBackRefImpl(String collectionRole, String entityName) { this.entityName = entityName; this.propertyName = collectionRole.substring( entityName.length() + 1 ); } @Override public PropertyAccess buildPropertyAccess(Class<?> containerJavaType, String propertyName, boolean setterRequired) { return new PropertyAccessIndexBackRefImpl( this ); } private static
PropertyAccessStrategyIndexBackRefImpl
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 39645, "end": 39831 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return definesFunction( dialect, "hamming_distance" ); } } public static
SupportsHammingDistance
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/builder/FlexibleAggregationStrategy.java
{ "start": 12094, "end": 12781 }
class ____ { protected Class<E> type; FlexibleAggregationStrategyInjector(Class<E> type) { this.type = type; } public void setType(Class<E> type) { this.type = type; } public abstract void prepareAggregationExchange(Exchange exchange); public abstract E getValue(Exchange exchange); public abstract void setValue(Exchange exchange, E obj); public abstract Collection<E> getValueAsCollection(Exchange exchange, Class<? extends Collection> type); public abstract void setValueAsCollection(Exchange exchange, Collection<E> obj); } private
FlexibleAggregationStrategyInjector
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/ContextServiceLoaderPluginResolver.java
{ "start": 1263, "end": 1947 }
interface ____ in the Camel service * lifecycle and are typically invoked during CamelContext startup to initialize third-party components and extensions. * <p> * The plugin resolution process typically occurs after the CamelContext has been created and configured but before * routes are started, ensuring that all plugins have the opportunity to modify or extend the context as needed. * <p> * Implementations must be stateful services that can be started and stopped as part of the normal Camel lifecycle, and * they must be aware of the CamelContext they are operating on. * * @see ContextServicePlugin * @see CamelContextAware * @see StatefulService */ public
participate
java
apache__logging-log4j2
log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/SpringLookupTest.java
{ "start": 1182, "end": 3231 }
class ____ { @Test void testLookup() { final MockEnvironment env = new MockEnvironment(); env.setActiveProfiles("test"); env.setDefaultProfiles("one", "two"); env.setProperty("app.property", "test"); final LoggerContext context = (LoggerContext) LogManager.getContext(false); context.putObject(Log4j2SpringBootLoggingSystem.ENVIRONMENT_KEY, env); final SpringLookup lookup = new SpringLookup(); lookup.setLoggerContext(context); String result = lookup.lookup("profiles.active"); assertThat(result).as("Incorrect active profile").isEqualTo("test"); result = lookup.lookup("profiles.active[0]"); assertThat(result).as("Incorrect active profile").isEqualTo("test"); result = lookup.lookup("profiles.default"); assertThat(result).as("Incorrect default profiles").isEqualTo("one,two"); result = lookup.lookup("profiles.default[0]"); assertThat(result).as("Incorrect default profiles").isEqualTo("one"); result = lookup.lookup("profiles.default[2]"); result = lookup.lookup("app.property"); assertThat(result).as("Incorrect property value").isEqualTo("test"); } @Test void testSpringLookupWithDefaultInterpolator() { final MockEnvironment env = new MockEnvironment(); env.setActiveProfiles("test"); env.setProperty("app.property", "test"); final LoggerContext context = (LoggerContext) LogManager.getContext(false); context.putObject(Log4j2SpringBootLoggingSystem.ENVIRONMENT_KEY, env); final Interpolator lookup = new Interpolator(); lookup.setConfiguration(context.getConfiguration()); lookup.setLoggerContext(context); String result = lookup.lookup("spring:profiles.active"); assertThat(result).as("Incorrect active profile").isEqualTo("test"); result = lookup.lookup("spring:app.property"); assertThat(result).as("Incorrect property value").isEqualTo("test"); } }
SpringLookupTest
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/io/VFSTest.java
{ "start": 923, "end": 3070 }
class ____ { @Test void getInstanceShouldNotBeNull() { VFS vsf = VFS.getInstance(); Assertions.assertNotNull(vsf); } @Test void getInstanceShouldNotBeNullInMultiThreadEnv() throws InterruptedException { final int threadCount = 3; Thread[] threads = new Thread[threadCount]; InstanceGetterProcedure[] procedures = new InstanceGetterProcedure[threadCount]; for (int i = 0; i < threads.length; i++) { String threadName = "Thread##" + i; procedures[i] = new InstanceGetterProcedure(); threads[i] = new Thread(procedures[i], threadName); } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } // All caller got must be the same instance for (int i = 0; i < threadCount - 1; i++) { Assertions.assertEquals(procedures[i].instanceGot, procedures[i + 1].instanceGot); } } @Test void getExistMethod() { Method method = VFS.getMethod(VFS.class, "list", String.class); Assertions.assertNotNull(method); } @Test void getNotExistMethod() { Method method = VFS.getMethod(VFS.class, "listXxx", String.class); Assertions.assertNull(method); } @Test void invoke() throws IOException, NoSuchMethodException { VFS vfs = VFS.invoke(VFS.class.getMethod("getInstance"), VFS.class); Assertions.assertEquals(vfs, VFS.getInstance()); Assertions.assertThrows(RuntimeException.class, () -> { // java.lang.IllegalArgumentException: wrong number of arguments VFS.invoke(VFS.class.getMethod("getInstance"), VFS.class, "unnecessaryArgument"); }); Assertions.assertThrows(IOException.class, () -> { // InvocationTargetException.getTargetException -> IOException VFS.invoke(Resources.class.getMethod("getResourceAsProperties", String.class), Resources.class, "invalidResource"); }); Assertions.assertThrows(RuntimeException.class, () -> { // Other InvocationTargetException VFS.invoke(Integer.class.getMethod("valueOf", String.class), Resources.class, "InvalidIntegerNumber"); }); } private static
VFSTest
java
quarkusio__quarkus
integration-tests/opentelemetry-reactive-messaging/src/main/java/io/quarkus/it/opentelemetry/SimpleResource.java
{ "start": 336, "end": 657 }
class ____ { @Channel("traces") Emitter<String> emitter; @GET @Path("/direct") public TraceData directTrace() { TraceData data = new TraceData(); data.message = "Direct trace"; emitter.send(data.message).toCompletableFuture().join(); return data; } }
SimpleResource
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateProcedureTest6.java
{ "start": 976, "end": 5270 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = "CREATE PROCEDURE wraptest wrapped \n" + "a000000\n" + "b2\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "7\n" + "121 134\n" + "Pf3/wD+9ncRZhp3XxTMUO3yIRvswg+nQ7UhqfHRG2vg+SD7x9XzsDUFWbdwCJVEOLKBBRuH6\n" + "VMoRHfX6apzfyMkvWhzQLCYvAcq6Zu7++E7PrXNxUJzk/FZW8P9eRgyyyMFnDj53aP1cDje9\n" + "ZdGr2VmJHIw0ZNHBYhDdR+du5U5Yy47a6dJHXFW9eNyxBHtXZDuiWYTUtlnueHQV9iYDwE+r\n" + "jFn+eZm4jgDcTLTEzfmIVtPDRNhYCY3xhPo7vJeS8M1AvP+4xh9+uO35XsRIsRl1PTFVrGwg\n" + "6iuxETwA5Pu2mwx3"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); print(statementList); assertEquals(1, statementList.size()); SQLStatement stmt = (SQLStatement) statementList.get(0); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); assertEquals("CREATE PROCEDURE wraptest WRAPPED \n" + "b2\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "7\n" + "121 134\n" + "Pf3/wD+9ncRZhp3XxTMUO3yIRvswg+nQ7UhqfHRG2vg+SD7x9XzsDUFWbdwCJVEOLKBBRuH6\n" + "VMoRHfX6apzfyMkvWhzQLCYvAcq6Zu7++E7PrXNxUJzk/FZW8P9eRgyyyMFnDj53aP1cDje9\n" + "ZdGr2VmJHIw0ZNHBYhDdR+du5U5Yy47a6dJHXFW9eNyxBHtXZDuiWYTUtlnueHQV9iYDwE+r\n" + "jFn+eZm4jgDcTLTEzfmIVtPDRNhYCY3xhPo7vJeS8M1AvP+4xh9+uO35XsRIsRl1PTFVrGwg\n" + "6iuxETwA5Pu2mwx3", stmt.toString()); assertEquals("CREATE PROCEDURE wraptest WRAPPED \n" + "b2\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "abcd\n" + "7\n" + "121 134\n" + "Pf3/wD+9ncRZhp3XxTMUO3yIRvswg+nQ7UhqfHRG2vg+SD7x9XzsDUFWbdwCJVEOLKBBRuH6\n" + "VMoRHfX6apzfyMkvWhzQLCYvAcq6Zu7++E7PrXNxUJzk/FZW8P9eRgyyyMFnDj53aP1cDje9\n" + "ZdGr2VmJHIw0ZNHBYhDdR+du5U5Yy47a6dJHXFW9eNyxBHtXZDuiWYTUtlnueHQV9iYDwE+r\n" + "jFn+eZm4jgDcTLTEzfmIVtPDRNhYCY3xhPo7vJeS8M1AvP+4xh9+uO35XsRIsRl1PTFVrGwg\n" + "6iuxETwA5Pu2mwx3", SQLUtils.toPGString(stmt)); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(0, visitor.getTables().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("fact_brand_provider"))); assertEquals(0, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertEquals(0, visitor.getRelationships().size()); // assertTrue(visitor.containsColumn("fact_brand_provider", "gyscode")); // assertTrue(visitor.containsColumn("fact_brand_provider", "gysname")); } }
OracleCreateProcedureTest6
java
google__dagger
javatests/dagger/hilt/android/testing/testinstallin/TestInstallInApp.java
{ "start": 1139, "end": 1234 }
class ____ extends Hilt_TestInstallInApp { @Inject Foo foo; @Inject Bar bar; }
TestInstallInApp
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/GzipCodec.java
{ "start": 4259, "end": 4810 }
class ____ extends ZlibCompressor { public GzipZlibCompressor() { super(ZlibCompressor.CompressionLevel.DEFAULT_COMPRESSION, ZlibCompressor.CompressionStrategy.DEFAULT_STRATEGY, ZlibCompressor.CompressionHeader.GZIP_FORMAT, 64*1024); } public GzipZlibCompressor(Configuration conf) { super(ZlibFactory.getCompressionLevel(conf), ZlibFactory.getCompressionStrategy(conf), ZlibCompressor.CompressionHeader.GZIP_FORMAT, 64 * 1024); } } static final
GzipZlibCompressor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoonewithformula/Menu.java
{ "start": 381, "end": 986 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String orderNbr; private String isDefault; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="is_default") public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } @Column(name="order_nbr") public String getOrderNbr() { return orderNbr; } public void setOrderNbr(String orderNbr) { this.orderNbr = orderNbr; } }
Menu
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java
{ "start": 35008, "end": 35189 }
class ____.springframework.core.io.FileSystemResource. " + "If this is intentional, please pass it as a pre-configured Resource via setLocations."); } } private static
org
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/ConcurrentHashMapTest4.java
{ "start": 1275, "end": 1760 }
class ____ { private ConcurrentHashMap<MessageQueue, AtomicReference<A>> offsetTable = new ConcurrentHashMap<MessageQueue, AtomicReference<A>>(); public ConcurrentHashMap<MessageQueue, AtomicReference<A>> getOffsetTable() { return offsetTable; } public void setOffsetTable(ConcurrentHashMap<MessageQueue, AtomicReference<A>> offsetTable) { this.offsetTable = offsetTable; } } public static
OffsetSerializeWrapper
java
elastic__elasticsearch
modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/SearchAsYouTypeFieldMapper.java
{ "start": 3982, "end": 4323 }
class ____ extends FieldMapper { public static final String CONTENT_TYPE = "search_as_you_type"; private static final int MAX_SHINGLE_SIZE_LOWER_BOUND = 2; private static final int MAX_SHINGLE_SIZE_UPPER_BOUND = 4; private static final String PREFIX_FIELD_SUFFIX = "._index_prefix"; public static
SearchAsYouTypeFieldMapper
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/CompositeIdFkGeneratedValueTest.java
{ "start": 14213, "end": 14442 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long nid; @Id @ManyToOne private HeadA hid; @ManyToOne private ComplexNodeA parent; private String name; public static
ComplexNodeA
java
apache__camel
components/camel-xmlsecurity/src/main/java/org/apache/camel/component/xmlsecurity/processor/XmlVerifierProcessor.java
{ "start": 2643, "end": 12435 }
class ____ extends XmlSignatureProcessor { private static final Logger LOG = LoggerFactory.getLogger(XmlVerifierProcessor.class); private final XmlVerifierConfiguration config; public XmlVerifierProcessor(CamelContext context, XmlVerifierConfiguration config) { super(context); this.config = config; } @Override public XmlVerifierConfiguration getConfiguration() { return config; } @Override public void process(Exchange exchange) throws Exception { InputStream stream = exchange.getIn().getMandatoryBody(InputStream.class); try { // lets setup the out message before we invoke the signing // so that it can mutate it if necessary Message out = exchange.getOut(); out.copyFrom(exchange.getIn()); verify(stream, out); clearMessageHeaders(out); } catch (Exception e) { // remove OUT message, as an exception occurred exchange.setOut(null); throw e; } finally { IOHelper.close(stream, "input stream"); } } @SuppressWarnings("unchecked") protected void verify(InputStream input, final Message out) throws Exception { LOG.debug("Verification of XML signature document started"); final Document doc = parseInput(input, out); XMLSignatureFactory fac; // Try to install the Santuario Provider - fall back to the JDK provider if this does // not work try { fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig"); } catch (NoSuchProviderException ex) { fac = XMLSignatureFactory.getInstance("DOM"); } KeySelector selector = getConfiguration().getKeySelector(); if (selector == null) { throw new IllegalStateException("Wrong configuration. Key selector is missing."); } DOMValidateContext valContext = new DOMValidateContext(selector, doc); valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); valContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE); if (getConfiguration().getSecureValidation().equals(Boolean.TRUE)) { valContext.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE); valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE); } setUriDereferencerAndBaseUri(valContext); setCryptoContextProperties(valContext); NodeList signatureNodes = getSignatureNodes(doc); List<XMLObject> collectedObjects = new ArrayList<>(3); List<Reference> collectedReferences = new ArrayList<>(3); int totalCount = signatureNodes.getLength(); for (int i = 0; i < totalCount; i++) { Element signatureNode = (Element) signatureNodes.item(i); valContext.setNode(signatureNode); final XMLSignature signature = fac.unmarshalXMLSignature(valContext); if (getConfiguration().getXmlSignatureChecker() != null) { XmlSignatureChecker.Input checkerInput = new CheckerInputBuilder().message(out).messageBodyDocument(doc) .keyInfo(signature.getKeyInfo()).currentCountOfSignatures(i + 1).currentSignatureElement(signatureNode) .objects(signature.getObjects()).signatureValue(signature.getSignatureValue()) .signedInfo(signature.getSignedInfo()).totalCountOfSignatures(totalCount) .xmlSchemaValidationExecuted(getSchemaResourceUri(out) != null).build(); getConfiguration().getXmlSignatureChecker().checkBeforeCoreValidation(checkerInput); } boolean coreValidity; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException se) { throw getConfiguration().getValidationFailedHandler().onXMLSignatureException(se); } // Check core validation status boolean goon = coreValidity; if (!coreValidity) { goon = handleSignatureValidationFailed(valContext, signature); } if (goon) { LOG.debug("XML signature {} verified", i + 1); } else { throw new XmlSignatureInvalidException("XML signature validation failed"); } collectedObjects.addAll(signature.getObjects()); collectedReferences.addAll(signature.getSignedInfo().getReferences()); } map2Message(collectedReferences, collectedObjects, out, doc); } private void map2Message( final List<Reference> refs, final List<XMLObject> objs, Message out, final Document messageBodyDocument) throws Exception { XmlSignature2Message.Input refsAndObjects = new XmlSignature2Message.Input() { @Override public List<Reference> getReferences() { return refs; } @Override public List<XMLObject> getObjects() { return objs; } @Override public Document getMessageBodyDocument() { return messageBodyDocument; } @Override public Boolean omitXmlDeclaration() { return getConfiguration().getOmitXmlDeclaration(); } @Override public Object getOutputNodeSearch() { return getConfiguration().getOutputNodeSearch(); } @Override public String getOutputNodeSearchType() { return getConfiguration().getOutputNodeSearchType(); } @Override public Boolean getRemoveSignatureElements() { return getConfiguration().getRemoveSignatureElements(); } @Override public String getOutputXmlEncoding() { return getConfiguration().getOutputXmlEncoding(); } }; getConfiguration().getXmlSignature2Message().mapToMessage(refsAndObjects, out); } private NodeList getSignatureNodes(Document doc) throws XmlSignatureFormatException { // Find Signature element NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { throw new XmlSignatureFormatException( "Message is not a correct XML signature document: 'Signature' element is missing. Check the sent message."); } LOG.debug("{} signature elements found", nl.getLength()); return nl; } @SuppressWarnings("unchecked") protected boolean handleSignatureValidationFailed(DOMValidateContext valContext, XMLSignature signature) throws Exception { ValidationFailedHandler handler = getConfiguration().getValidationFailedHandler(); LOG.debug("handleSignatureValidationFailed called"); try { handler.start(); // first check signature value, see // https://www.isecpartners.com/media/12012/XMLDSIG_Command_Injection.pdf SignatureValue sigValue = signature.getSignatureValue(); boolean sv = sigValue.validate(valContext); if (!sv) { handler.signatureValueValidationFailed(sigValue); } // then the references! // check the validation status of each Reference for (Reference ref : signature.getSignedInfo().getReferences()) { boolean refValid = ref.validate(valContext); if (!refValid) { handler.referenceValidationFailed(ref); } } // validate Manifests, if property set if (Boolean.TRUE.equals(valContext.getProperty("org.jcp.xml.dsig.validateManifests"))) { for (XMLObject xo : signature.getObjects()) { List<XMLStructure> content = xo.getContent(); for (XMLStructure xs : content) { if (xs instanceof Manifest) { Manifest man = (Manifest) xs; for (Reference ref : man.getReferences()) { boolean refValid = ref.validate(valContext); if (!refValid) { handler.manifestReferenceValidationFailed(ref); } } } } } } boolean goon = handler.ignoreCoreValidationFailure(); LOG.debug("Ignore Core Validation failure: {}", goon); return goon; } finally { handler.end(); } } protected Document parseInput(InputStream is, Message message) throws Exception { try { ValidatorErrorHandler errorHandler = new DefaultValidationErrorHandler(); Schema schema = getSchema(message); DocumentBuilder db = XmlSignatureHelper.newDocumentBuilder(getConfiguration().getDisallowDoctypeDecl(), schema); db.setErrorHandler(errorHandler); Document doc = db.parse(is); errorHandler.handleErrors(message.getExchange(), schema, null); // throws ValidationException return doc; } catch (SAXException e) { throw new XmlSignatureFormatException( "Message has wrong format, it is not a XML signature document. Check the sent message.", e); } } static
XmlVerifierProcessor
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/streams/StreamFactoryRequirements.java
{ "start": 4001, "end": 4304 }
enum ____ { /** * Expect Unaudited GETs. * Disables auditor warning/errors about GET requests being * issued outside an audit span. */ ExpectUnauditedGetRequests, /** * Requires a future pool bound to the thread pool. */ RequiresFuturePool } }
Requirements
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 25624, "end": 26303 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { try { return dialect.getAggregateSupport() != null && dialect.getAggregateSupport().aggregateComponentCustomReadExpression( "", "", "", "", SqlTypes.JSON, new SqlTypedMappingImpl( "varchar", null, null, null, null, null, new BasicTypeImpl<>( StringJavaType.INSTANCE, VarcharJdbcType.INSTANCE ) ), new TypeConfiguration() ) != null; } catch (UnsupportedOperationException | IllegalArgumentException e) { return false; } } } public static
SupportsJsonAggregate
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/monitor/fs/FsHealthService.java
{ "start": 1972, "end": 5680 }
class ____ extends AbstractLifecycleComponent implements NodeHealthService { private static final Logger logger = LogManager.getLogger(FsHealthService.class); private static final StatusInfo HEALTHY_DISABLED = new StatusInfo(HEALTHY, "health check disabled"); private static final StatusInfo UNHEALTHY_BROKEN_NODE_LOCK = new StatusInfo(UNHEALTHY, "health check failed due to broken node lock"); private static final StatusInfo HEALTHY_SUCCESS = new StatusInfo(HEALTHY, "health check passed"); private final ThreadPool threadPool; private volatile boolean enabled; private volatile boolean brokenLock; private final TimeValue refreshInterval; private volatile TimeValue slowPathLoggingThreshold; private final NodeEnvironment nodeEnv; private final LongSupplier currentTimeMillisSupplier; private Scheduler.Cancellable scheduledFuture; // accesses all synchronized on AbstractLifecycleComponent#lifecycle @Nullable private volatile Set<Path> unhealthyPaths; public static final Setting<Boolean> ENABLED_SETTING = Setting.boolSetting( "monitor.fs.health.enabled", true, Setting.Property.NodeScope, Setting.Property.Dynamic ); public static final Setting<TimeValue> REFRESH_INTERVAL_SETTING = Setting.timeSetting( "monitor.fs.health.refresh_interval", TimeValue.timeValueSeconds(120), TimeValue.timeValueMillis(1), Setting.Property.NodeScope ); public static final Setting<TimeValue> SLOW_PATH_LOGGING_THRESHOLD_SETTING = Setting.timeSetting( "monitor.fs.health.slow_path_logging_threshold", TimeValue.timeValueSeconds(5), TimeValue.timeValueMillis(1), Setting.Property.NodeScope, Setting.Property.Dynamic ); public FsHealthService(Settings settings, ClusterSettings clusterSettings, ThreadPool threadPool, NodeEnvironment nodeEnv) { this.threadPool = threadPool; this.enabled = ENABLED_SETTING.get(settings); this.refreshInterval = REFRESH_INTERVAL_SETTING.get(settings); this.slowPathLoggingThreshold = SLOW_PATH_LOGGING_THRESHOLD_SETTING.get(settings); this.currentTimeMillisSupplier = threadPool.relativeTimeInMillisSupplier(); this.nodeEnv = nodeEnv; clusterSettings.addSettingsUpdateConsumer(SLOW_PATH_LOGGING_THRESHOLD_SETTING, this::setSlowPathLoggingThreshold); clusterSettings.addSettingsUpdateConsumer(ENABLED_SETTING, this::setEnabled); } @Override protected void doStart() { scheduledFuture = threadPool.scheduleWithFixedDelay(new FsHealthMonitor(), refreshInterval, threadPool.generic()); } @Override protected void doStop() { scheduledFuture.cancel(); } @Override protected void doClose() {} public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setSlowPathLoggingThreshold(TimeValue slowPathLoggingThreshold) { this.slowPathLoggingThreshold = slowPathLoggingThreshold; } @Override public StatusInfo getHealth() { if (enabled == false) { return HEALTHY_DISABLED; } if (brokenLock) { return UNHEALTHY_BROKEN_NODE_LOCK; } var unhealthyPaths = this.unhealthyPaths; // single volatile read if (unhealthyPaths != null) { assert unhealthyPaths.isEmpty() == false; return new StatusInfo( UNHEALTHY, "health check failed on [" + unhealthyPaths.stream().map(Path::toString).collect(Collectors.joining(",")) + "]" ); } return HEALTHY_SUCCESS; }
FsHealthService
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
{ "start": 8568, "end": 10366 }
class ____ { private final Set<String> terseExceptions = ConcurrentHashMap.newKeySet(); private final Set<String> suppressedExceptions = ConcurrentHashMap.newKeySet(); /** * Add exception classes for which server won't log stack traces. * Optimized for infrequent invocation. * @param exceptionClass exception classes */ void addTerseLoggingExceptions(Class<?>... exceptionClass) { terseExceptions.addAll(Arrays .stream(exceptionClass) .map(Class::toString) .collect(Collectors.toSet())); } /** * Add exception classes which server won't log at all. * Optimized for infrequent invocation. * @param exceptionClass exception classes */ void addSuppressedLoggingExceptions(Class<?>... exceptionClass) { suppressedExceptions.addAll(Arrays .stream(exceptionClass) .map(Class::toString) .collect(Collectors.toSet())); } boolean isTerseLog(Class<?> t) { return terseExceptions.contains(t.toString()); } boolean isSuppressedLog(Class<?> t) { return suppressedExceptions.contains(t.toString()); } } /** * If the user accidentally sends an HTTP GET to an IPC port, we detect this * and send back a nicer response. */ private static final ByteBuffer HTTP_GET_BYTES = ByteBuffer.wrap( "GET ".getBytes(StandardCharsets.UTF_8)); /** * An HTTP response to send back if we detect an HTTP request to our IPC * port. */ static final String RECEIVED_HTTP_REQ_RESPONSE = "HTTP/1.1 404 Not Found\r\n" + "Content-type: text/plain\r\n\r\n" + "It looks like you are making an HTTP request to a Hadoop IPC port. " + "This is not the correct port for the web
ExceptionsHandler
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToGeohashErrorTests.java
{ "start": 800, "end": 1408 }
class ____ extends ErrorsForCasesWithoutExamplesTestCase { @Override protected List<TestCaseSupplier> cases() { return paramsToSuppliers(ToGeohashTests.parameters()); } @Override protected Expression build(Source source, List<Expression> args) { return new ToGeohash(source, args.get(0)); } @Override protected Matcher<String> expectedTypeErrorMatcher(List<Set<DataType>> validPerPosition, List<DataType> signature) { return equalTo(typeErrorMessage(false, validPerPosition, signature, (v, p) -> "geohash or long or string")); } }
ToGeohashErrorTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/IncompatibleModifiersCheckerTest.java
{ "start": 2894, "end": 3195 }
class ____ {} """) .doTest(); } @Test public void annotationWithIncompatibleModifierOnFieldFails() { compilationHelper .addSourceLines( "test/IncompatibleModifiersTestCase.java", """ package test; import test.NotPrivateOrFinal; public
IncompatibleModifiersTestCase
java
apache__camel
components/camel-spring-parent/camel-spring-redis/src/main/java/org/apache/camel/component/redis/processor/idempotent/SpringRedisIdempotentRepository.java
{ "start": 1756, "end": 5769 }
class ____ extends ServiceSupport implements IdempotentRepository { private SetOperations<String, String> setOperations; @Metadata(description = "Name of repository", required = true) private String repositoryName; @Metadata(description = "Redis configuration") private RedisConfiguration redisConfiguration; private RedisTemplate<String, String> redisTemplate; @Metadata(label = "advanced", description = "Delete all keys of the currently selected database." + " Be careful if enabling this as all existing data will be deleted.") private boolean flushOnStartup; public SpringRedisIdempotentRepository() { } public SpringRedisIdempotentRepository(RedisTemplate<String, String> redisTemplate, String repositoryName) { this.setOperations = redisTemplate.opsForSet(); this.repositoryName = repositoryName; this.redisTemplate = redisTemplate; } public SpringRedisIdempotentRepository(String repositoryName) { this.repositoryName = repositoryName; } public static SpringRedisIdempotentRepository redisIdempotentRepository(String processorName) { return new SpringRedisIdempotentRepository(processorName); } public static SpringRedisIdempotentRepository redisIdempotentRepository( RedisTemplate<String, String> redisTemplate, String processorName) { return new SpringRedisIdempotentRepository(redisTemplate, processorName); } public boolean isFlushOnStartup() { return flushOnStartup; } /** * Delete all keys of the currently selected database. Be careful if enabling this as all existing data will be * deleted. */ public void setFlushOnStartup(boolean flushOnStartup) { this.flushOnStartup = flushOnStartup; } @Override @ManagedOperation(description = "Adds the key to the store") public boolean add(String key) { if (!contains(key)) { return setOperations.add(repositoryName, key) != null; } else { return false; } } @Override @ManagedOperation(description = "Does the store contain the given key") public boolean contains(String key) { return setOperations.isMember(repositoryName, key); } @Override @ManagedOperation(description = "Remove the key from the store") public boolean remove(String key) { return setOperations.remove(repositoryName, key) != null; } @Override @ManagedOperation(description = "Clear the store") public void clear() { redisTemplate.getConnectionFactory().getConnection().flushDb(); } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } @ManagedAttribute(description = "The repository name") public String getRepositoryName() { return repositoryName; } @Override public boolean confirm(String key) { return true; } @Override protected void doStart() throws Exception { if (redisConfiguration == null && this.redisTemplate == null) { // create configuration if no custom template has been configured redisConfiguration = new RedisConfiguration(); } if (this.redisTemplate == null) { this.redisTemplate = (RedisTemplate<String, String>) redisConfiguration.getRedisTemplate(); } ObjectHelper.notNull(this.redisTemplate, "redisTemplate", this); this.setOperations = redisTemplate.opsForSet(); if (flushOnStartup) { redisTemplate.getConnectionFactory().getConnection().flushDb(); } } @Override protected void doStop() throws Exception { // noop } @Override protected void doShutdown() throws Exception { super.doShutdown(); if (redisConfiguration != null) { redisConfiguration.stop(); } } }
SpringRedisIdempotentRepository
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/Saml2AuthenticationRequestResolver.java
{ "start": 1026, "end": 1250 }
interface ____ { String DEFAULT_AUTHENTICATION_REQUEST_URI = "/saml2/authenticate/{registrationId}"; <T extends AbstractSaml2AuthenticationRequest> T resolve(HttpServletRequest request); }
Saml2AuthenticationRequestResolver
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/support/DirtiesContextBeforeModesTestExecutionListener.java
{ "start": 1824, "end": 2531 }
class ____} set to * {@link ClassMode#BEFORE_EACH_TEST_METHOD BEFORE_EACH_TEST_METHOD} or * {@link ClassMode#BEFORE_CLASS BEFORE_CLASS}. For support for <em>AFTER</em> * modes, see {@link DirtiesContextTestExecutionListener}. * * <p>When {@linkplain TestExecutionListeners#mergeMode merging} * {@code TestExecutionListeners} with the defaults, this listener will * automatically be ordered before the {@link DependencyInjectionTestExecutionListener}; * otherwise, this listener must be manually configured to execute before the * {@code DependencyInjectionTestExecutionListener}. * * @author Sam Brannen * @since 4.2 * @see DirtiesContext * @see DirtiesContextTestExecutionListener */ public
mode
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/naming/EmbeddedColumnNamingTests.java
{ "start": 7463, "end": 7695 }
class ____ { @Id private Integer id; private String name; @Embedded private Address homeAddress; @Embedded private Address workAddress; } @Entity(name="GoodPerson") @Table(name="good_person") public static
BadPerson
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/catalog/stats/Date.java
{ "start": 1010, "end": 1812 }
class ____ { private final long daysSinceEpoch; public Date(long daysSinceEpoch) { this.daysSinceEpoch = daysSinceEpoch; } public long getDaysSinceEpoch() { return daysSinceEpoch; } public Date copy() { return new Date(daysSinceEpoch); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Date date = (Date) o; return daysSinceEpoch == date.daysSinceEpoch; } @Override public int hashCode() { return Objects.hash(daysSinceEpoch); } @Override public String toString() { return "Date{" + "daysSinceEpoch=" + daysSinceEpoch + '}'; } }
Date
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/common/breaker/TestCircuitBreaker.java
{ "start": 570, "end": 1152 }
class ____ extends NoopCircuitBreaker { private final AtomicBoolean shouldBreak = new AtomicBoolean(false); public TestCircuitBreaker() { super("test"); } @Override public void addEstimateBytesAndMaybeBreak(long bytes, String label) throws CircuitBreakingException { if (shouldBreak.get()) { throw new CircuitBreakingException("broken", getDurability()); } } public void startBreaking() { shouldBreak.set(true); } public void stopBreaking() { shouldBreak.set(false); } }
TestCircuitBreaker
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/ObjectUtils.java
{ "start": 2731, "end": 30500 }
class ____ implements Serializable { /** * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 * * @see java.io.Serializable */ private static final long serialVersionUID = 7092611880189329093L; /** * Restricted constructor - singleton. */ Null() { } /** * Ensures singleton after serialization. * * @return the singleton value. */ private Object readResolve() { return NULL; } } private static final char AT_SIGN = '@'; /** * Singleton used as a {@code null} placeholder where {@code null} has another meaning. * * <p> * For example, in a {@link HashMap} the {@link java.util.HashMap#get(Object)} method returns {@code null} if the {@link Map} contains {@code null} or if * there is no matching key. The {@code null} placeholder can be used to distinguish between these two cases. * </p> * * <p> * Another example is {@link Hashtable}, where {@code null} cannot be stored. * </p> * * <p> * This instance is Serializable. * </p> */ public static final Null NULL = new Null(); /** * Tests if all values in the array are not {@code nulls}. * * <p> * If any value is {@code null} or the array is {@code null} then {@code false} is returned. If all elements in array are not {@code null} or the array is * empty (contains no elements) {@code true} is returned. * </p> * * <pre> * ObjectUtils.allNotNull(*) = true * ObjectUtils.allNotNull(*, *) = true * ObjectUtils.allNotNull(null) = false * ObjectUtils.allNotNull(null, null) = false * ObjectUtils.allNotNull(null, *) = false * ObjectUtils.allNotNull(*, null) = false * ObjectUtils.allNotNull(*, *, null, *) = false * </pre> * * @param values the values to test, may be {@code null} or empty. * @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, {@code true} if all values in the array are * not {@code null}s or array contains no elements. * @since 3.5 */ public static boolean allNotNull(final Object... values) { return values != null && Stream.of(values).noneMatch(Objects::isNull); } /** * Tests if all values in the given array are {@code null}. * * <p> * If all the values are {@code null} or the array is {@code null} or empty, then {@code true} is returned, otherwise {@code false} is returned. * </p> * * <pre> * ObjectUtils.allNull(*) = false * ObjectUtils.allNull(*, null) = false * ObjectUtils.allNull(null, *) = false * ObjectUtils.allNull(null, null, *, *) = false * ObjectUtils.allNull(null) = true * ObjectUtils.allNull(null, null) = true * </pre> * * @param values the values to test, may be {@code null} or empty. * @return {@code true} if all values in the array are {@code null}s, {@code false} if there is at least one non-null value in the array. * @since 3.11 */ public static boolean allNull(final Object... values) { return !anyNotNull(values); } /** * Tests if any value in the given array is not {@code null}. * * <p> * If all the values are {@code null} or the array is {@code null} or empty then {@code false} is returned. Otherwise {@code true} is returned. * </p> * * <pre> * ObjectUtils.anyNotNull(*) = true * ObjectUtils.anyNotNull(*, null) = true * ObjectUtils.anyNotNull(null, *) = true * ObjectUtils.anyNotNull(null, null, *, *) = true * ObjectUtils.anyNotNull(null) = false * ObjectUtils.anyNotNull(null, null) = false * </pre> * * @param values the values to test, may be {@code null} or empty. * @return {@code true} if there is at least one non-null value in the array, {@code false} if all values in the array are {@code null}s. If the array is * {@code null} or empty {@code false} is also returned. * @since 3.5 */ public static boolean anyNotNull(final Object... values) { return firstNonNull(values) != null; } /** * Tests if any value in the given array is {@code null}. * * <p> * If any of the values are {@code null} or the array is {@code null}, then {@code true} is returned, otherwise {@code false} is returned. * </p> * * <pre> * ObjectUtils.anyNull(*) = false * ObjectUtils.anyNull(*, *) = false * ObjectUtils.anyNull(null) = true * ObjectUtils.anyNull(null, null) = true * ObjectUtils.anyNull(null, *) = true * ObjectUtils.anyNull(*, null) = true * ObjectUtils.anyNull(*, *, null, *) = true * </pre> * * @param values the values to test, may be {@code null} or empty. * @return {@code true} if there is at least one {@code null} value in the array, {@code false} if all the values are non-null. If the array is {@code null} * or empty, {@code true} is also returned. * @since 3.11 */ public static boolean anyNull(final Object... values) { return !allNotNull(values); } /** * Clones an object. * * @param <T> the type of the object. * @param obj the object to clone, null returns null. * @return the clone if the object implements {@link Cloneable} otherwise {@code null}. * @throws CloneFailedException if the object is cloneable and the clone operation fails. * @since 3.0 */ public static <T> T clone(final T obj) { if (obj instanceof Cloneable) { final Object result; final Class<?> objClass = obj.getClass(); if (isArray(obj)) { final Class<?> componentType = objClass.getComponentType(); if (componentType.isPrimitive()) { int length = Array.getLength(obj); result = Array.newInstance(componentType, length); while (length-- > 0) { Array.set(result, length, Array.get(obj, length)); } } else { result = ((Object[]) obj).clone(); } } else { try { result = objClass.getMethod("clone").invoke(obj); } catch (final ReflectiveOperationException e) { throw new CloneFailedException("Exception cloning Cloneable type " + objClass.getName(), e); } } return (T) result; } return null; } /** * Clones an object if possible. * * <p> * This method is similar to {@link #clone(Object)}, but will return the provided instance as the return value instead of {@code null} if the instance is * not cloneable. This is more convenient if the caller uses different implementations (e.g. of a service) and some of the implementations do not allow * concurrent processing or have state. In such cases the implementation can simply provide a proper clone implementation and the caller's code does not * have to change. * </p> * * @param <T> the type of the object. * @param obj the object to clone, null returns null. * @return the clone if the object implements {@link Cloneable} otherwise the object itself. * @throws CloneFailedException if the object is cloneable and the clone operation fails. * @since 3.0 */ public static <T> T cloneIfPossible(final T obj) { final T clone = clone(obj); return clone == null ? obj : clone; } /** * Null safe comparison of Comparables. {@code null} is assumed to be less than a non-{@code null} value. * <p> * TODO Move to ComparableUtils. * </p> * * @param <T> type of the values processed by this method. * @param c1 the first comparable, may be null. * @param c2 the second comparable, may be null. * @return a negative value if c1 &lt; c2, zero if c1 = c2 and a positive value if c1 &gt; c2. */ public static <T extends Comparable<? super T>> int compare(final T c1, final T c2) { return compare(c1, c2, false); } /** * Null safe comparison of Comparables. * <p> * TODO Move to ComparableUtils. * </p> * * @param <T> type of the values processed by this method. * @param c1 the first comparable, may be null. * @param c2 the second comparable, may be null. * @param nullGreater if true {@code null} is considered greater than a non-{@code null} value or if false {@code null} is considered less than a * Non-{@code null} value. * @return a negative value if c1 &lt; c2, zero if c1 = c2 and a positive value if c1 &gt; c2. * @see java.util.Comparator#compare(Object, Object) */ public static <T extends Comparable<? super T>> int compare(final T c1, final T c2, final boolean nullGreater) { if (c1 == c2) { return 0; } if (c1 == null) { return nullGreater ? 1 : -1; } if (c2 == null) { return nullGreater ? -1 : 1; } return c1.compareTo(c2); } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static boolean MAGIC_FLAG = ObjectUtils.CONST(true); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param v the boolean value to return. * @return the boolean v, unchanged. * @since 3.2 */ public static boolean CONST(final boolean v) { return v; } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static byte MAGIC_BYTE = ObjectUtils.CONST((byte) 127); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param v the byte value to return. * @return the byte v, unchanged. * @since 3.2 */ public static byte CONST(final byte v) { return v; } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static char MAGIC_CHAR = ObjectUtils.CONST('a'); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param v the char value to return. * @return the char v, unchanged. * @since 3.2 */ public static char CONST(final char v) { return v; } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static double MAGIC_DOUBLE = ObjectUtils.CONST(1.0); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param v the double value to return. * @return the double v, unchanged. * @since 3.2 */ public static double CONST(final double v) { return v; } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static float MAGIC_FLOAT = ObjectUtils.CONST(1.0f); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param v the float value to return. * @return the float v, unchanged. * @since 3.2 */ public static float CONST(final float v) { return v; } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static int MAGIC_INT = ObjectUtils.CONST(123); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param v the int value to return. * @return the int v, unchanged. * @since 3.2 */ public static int CONST(final int v) { return v; } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static long MAGIC_LONG = ObjectUtils.CONST(123L); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param v the long value to return. * @return the long v, unchanged. * @since 3.2 */ public static long CONST(final long v) { return v; } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static short MAGIC_SHORT = ObjectUtils.CONST((short) 123); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param v the short value to return. * @return the short v, unchanged. * @since 3.2 */ public static short CONST(final short v) { return v; } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static String MAGIC_STRING = ObjectUtils.CONST("abc"); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param <T> the Object type. * @param v the genericized Object value to return (typically a String). * @return the genericized Object v, unchanged (typically a String). * @since 3.2 */ public static <T> T CONST(final T v) { return v; } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static byte MAGIC_BYTE = ObjectUtils.CONST_BYTE(127); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param v the byte literal (as an int) value to return. * @throws IllegalArgumentException if the value passed to v is larger than a byte, that is, smaller than -128 or larger than 127. * @return the byte v, unchanged. * @since 3.2 */ public static byte CONST_BYTE(final int v) { if (v < Byte.MIN_VALUE || v > Byte.MAX_VALUE) { throw new IllegalArgumentException("Supplied value must be a valid byte literal between -128 and 127: [" + v + "]"); } return (byte) v; } /** * Returns the provided value unchanged. This can prevent javac from inlining a constant field, e.g., * * <pre> * public final static short MAGIC_SHORT = ObjectUtils.CONST_SHORT(127); * </pre> * * This way any jars that refer to this field do not have to recompile themselves if the field's value changes at some future date. * * @param v the short literal (as an int) value to return. * @throws IllegalArgumentException if the value passed to v is larger than a short, that is, smaller than -32768 or larger than 32767. * @return the byte v, unchanged. * @since 3.2 */ public static short CONST_SHORT(final int v) { if (v < Short.MIN_VALUE || v > Short.MAX_VALUE) { throw new IllegalArgumentException("Supplied value must be a valid byte literal between -32768 and 32767: [" + v + "]"); } return (short) v; } /** * Returns a default value if the object passed is {@code null}. * * <pre> * ObjectUtils.defaultIfNull(null, null) = null * ObjectUtils.defaultIfNull(null, "") = "" * ObjectUtils.defaultIfNull(null, "zz") = "zz" * ObjectUtils.defaultIfNull("abc", *) = "abc" * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE * </pre> * * @param <T> the type of the object. * @param object the {@link Object} to test, may be {@code null}. * @param defaultValue the default value to return, may be {@code null}. * @return {@code object} if it is not {@code null}, defaultValue otherwise. * @see #getIfNull(Object, Object) * @see #getIfNull(Object, Supplier) * @deprecated Use {@link #getIfNull(Object, Object)}. */ @Deprecated public static <T> T defaultIfNull(final T object, final T defaultValue) { return getIfNull(object, defaultValue); } // Null-safe equals/hashCode /** * Compares two objects for equality, where either one or both * objects may be {@code null}. * * <pre> * ObjectUtils.equals(null, null) = true * ObjectUtils.equals(null, "") = false * ObjectUtils.equals("", null) = false * ObjectUtils.equals("", "") = true * ObjectUtils.equals(Boolean.TRUE, null) = false * ObjectUtils.equals(Boolean.TRUE, "true") = false * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false * </pre> * * @param object1 the first object, may be {@code null}. * @param object2 the second object, may be {@code null}. * @return {@code true} if the values of both objects are the same. * @deprecated this method has been replaced by {@code java.util.Objects.equals(Object, Object)} in Java 7 and will * be removed from future releases. */ @Deprecated public static boolean equals(final Object object1, final Object object2) { return Objects.equals(object1, object2); } /** * Returns the first value in the array which is not {@code null}. * If all the values are {@code null} or the array is {@code null} * or empty then {@code null} is returned. * * <pre> * ObjectUtils.firstNonNull(null, null) = null * ObjectUtils.firstNonNull(null, "") = "" * ObjectUtils.firstNonNull(null, null, "") = "" * ObjectUtils.firstNonNull(null, "zz") = "zz" * ObjectUtils.firstNonNull("abc", *) = "abc" * ObjectUtils.firstNonNull(null, "xyz", *) = "xyz" * ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE * ObjectUtils.firstNonNull() = null * </pre> * * @param <T> the component type of the array. * @param values the values to test, may be {@code null} or empty. * @return the first value from {@code values} which is not {@code null}, * or {@code null} if there are no non-null values. * @since 3.0 */ @SafeVarargs public static <T> T firstNonNull(final T... values) { return Streams.of(values).filter(Objects::nonNull).findFirst().orElse(null); } /** * Delegates to {@link Object#getClass()} using generics. * * @param <T> The argument type or null. * @param object The argument. * @return The argument's Class or null. * @since 3.13.0 */ @SuppressWarnings("unchecked") public static <T> Class<T> getClass(final T object) { return object == null ? null : (Class<T>) object.getClass(); } /** * Executes the given suppliers in order and returns the first return value where a value other than {@code null} is returned. Once a non-{@code null} value * is obtained, all following suppliers are not executed anymore. If all the return values are {@code null} or no suppliers are provided then {@code null} * is returned. * * <pre>{@code * ObjectUtils.firstNonNullLazy(null, () -> null) = null * ObjectUtils.firstNonNullLazy(() -> null, () -> "") = "" * ObjectUtils.firstNonNullLazy(() -> "", () -> throw new IllegalStateException()) = "" * ObjectUtils.firstNonNullLazy(() -> null, () -> "zz) = "zz" * ObjectUtils.firstNonNullLazy() = null * }</pre> * <p> * See also {@link Consumers#accept(Consumer, Object)} and {@link Suppliers#get(Supplier)}. * </p> * * @param <T> the type of the return values. * @param suppliers the suppliers returning the values to test. {@code null} values are ignored. Suppliers may return {@code null} or a value of type * {@code T}. * @return the first return value from {@code suppliers} which is not {@code null}, or {@code null} if there are no non-null values. * @see Consumers#accept(Consumer, Object) * @see Suppliers#get(Supplier) * @since 3.10 */ @SafeVarargs public static <T> T getFirstNonNull(final Supplier<T>... suppliers) { return Streams.of(suppliers).filter(Objects::nonNull).map(Supplier::get).filter(Objects::nonNull).findFirst().orElse(null); } /** * Returns the given {@code object} is it is non-null, otherwise returns the Supplier's {@link Supplier#get()} * value. * * <p> * The caller responsible for thread-safety and exception handling of default value supplier. * </p> * * <pre>{@code * ObjectUtils.getIfNull(null, () -> null) = null * ObjectUtils.getIfNull(null, null) = null * ObjectUtils.getIfNull(null, () -> "") = "" * ObjectUtils.getIfNull(null, () -> "zz") = "zz" * ObjectUtils.getIfNull("abc", *) = "abc" * ObjectUtils.getIfNull(Boolean.TRUE, *) = Boolean.TRUE * }</pre> * <p> * See also {@link Consumers#accept(Consumer, Object)} and {@link Suppliers#get(Supplier)}. * </p> * * @param <T> the type of the object. * @param object the {@link Object} to test, may be {@code null}. * @param defaultSupplier the default value to return, may be {@code null}. * @return {@code object} if it is not {@code null}, {@code defaultValueSupplier.get()} otherwise. * @see #getIfNull(Object, Object) * @see Consumers#accept(Consumer, Object) * @see Suppliers#get(Supplier) * @since 3.10 */ public static <T> T getIfNull(final T object, final Supplier<T> defaultSupplier) { return object != null ? object : Suppliers.get(defaultSupplier); } /** * Returns a default value if the object passed is {@code null}. * * <pre> * ObjectUtils.getIfNull(null, null) = null * ObjectUtils.getIfNull(null, "") = "" * ObjectUtils.getIfNull(null, "zz") = "zz" * ObjectUtils.getIfNull("abc", *) = "abc" * ObjectUtils.getIfNull(Boolean.TRUE, *) = Boolean.TRUE * </pre> * <p> * See also {@link Consumers#accept(Consumer, Object)} and {@link Suppliers#get(Supplier)}. * </p> * * @param <T> the type of the object. * @param object the {@link Object} to test, may be {@code null}. * @param defaultValue the default value to return, may be {@code null}. * @return {@code object} if it is not {@code null}, defaultValue otherwise. * @see #getIfNull(Object, Supplier) * @see Consumers#accept(Consumer, Object) * @see Suppliers#get(Supplier) * @since 3.18.0 */ public static <T> T getIfNull(final T object, final T defaultValue) { return object != null ? object : defaultValue; } /** * Gets the hash code of an object returning zero when the object is {@code null}. * * <pre> * ObjectUtils.hashCode(null) = 0 * ObjectUtils.hashCode(obj) = obj.hashCode() * </pre> * * @param obj the object to obtain the hash code of, may be {@code null}. * @return the hash code of the object, or zero if null. * @since 2.1 * @deprecated this method has been replaced by {@code java.util.Objects.hashCode(Object)} in Java 7 and will be removed in future releases. */ @Deprecated public static int hashCode(final Object obj) { // hashCode(Object) for performance vs. hashCodeMulti(Object[]), as hash code is often critical return Objects.hashCode(obj); } /** * Returns the hexadecimal hash code for the given object per {@link Objects#hashCode(Object)}. * <p> * Short hand for {@code Integer.toHexString(Objects.hashCode(object))}. * </p> * * @param object object for which the hashCode is to be calculated. * @return Hash code in hexadecimal format. * @since 3.13.0 */ public static String hashCodeHex(final Object object) { return Integer.toHexString(Objects.hashCode(object)); } /** * Gets the hash code for multiple objects. * * <p> * This allows a hash code to be rapidly calculated for a number of objects. The hash code for a single object is the <em>not</em> same as * {@link #hashCode(Object)}. The hash code for multiple objects is the same as that calculated by an {@link ArrayList} containing the specified objects. * </p> * * <pre> * ObjectUtils.hashCodeMulti() = 1 * ObjectUtils.hashCodeMulti((Object[]) null) = 1 * ObjectUtils.hashCodeMulti(a) = 31 + a.hashCode() * ObjectUtils.hashCodeMulti(a,b) = (31 + a.hashCode()) * 31 + b.hashCode() * ObjectUtils.hashCodeMulti(a,b,c) = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode() * </pre> * * @param objects the objects to obtain the hash code of, may be {@code null}. * @return the hash code of the objects, or zero if null. * @since 3.0 * @deprecated this method has been replaced by {@code java.util.Objects.hash(Object...)} in Java 7 and will be removed in future releases. */ @Deprecated public static int hashCodeMulti(final Object... objects) { int hash = 1; if (objects != null) { for (final Object object : objects) { final int tmpHash = Objects.hashCode(object); hash = hash * 31 + tmpHash; } } return hash; } /** * Returns the hexadecimal hash code for the given object per {@link System#identityHashCode(Object)}. * <p> * Short hand for {@code Integer.toHexString(System.identityHashCode(object))}. * </p> * * @param object object for which the hashCode is to be calculated. * @return Hash code in hexadecimal format. * @since 3.13.0 */ public static String identityHashCodeHex(final Object object) { return Integer.toHexString(System.identityHashCode(object)); } /** * Appends the toString that would be produced by {@link Object} * if a
Null
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/ConsumerGroupHeartbeatRequest.java
{ "start": 1213, "end": 2332 }
class ____ extends AbstractRequest { /** * A member epoch of <code>-1</code> means that the member wants to leave the group. */ public static final int LEAVE_GROUP_MEMBER_EPOCH = -1; public static final int LEAVE_GROUP_STATIC_MEMBER_EPOCH = -2; /** * A member epoch of <code>0</code> means that the member wants to join the group. */ public static final int JOIN_GROUP_MEMBER_EPOCH = 0; /** * The version from which consumers are required to generate their own member id. * * <p>Starting from this version, member id must be generated by the consumer instance * instead of being provided by the server.</p> */ public static final int CONSUMER_GENERATED_MEMBER_ID_REQUIRED_VERSION = 1; public static final String REGEX_RESOLUTION_NOT_SUPPORTED_MSG = "The cluster does not support " + "regular expressions resolution on ConsumerGroupHeartbeat API version 0. It must be upgraded to use " + "ConsumerGroupHeartbeat API version >= 1 to allow to subscribe to a SubscriptionPattern."; public static
ConsumerGroupHeartbeatRequest
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/io/ClassPathResource.java
{ "start": 2835, "end": 3506 }
class ____ to load the resource with * @see ClassUtils#getDefaultClassLoader() */ public ClassPathResource(String path, @Nullable ClassLoader classLoader) { Assert.notNull(path, "Path must not be null"); String pathToUse = StringUtils.cleanPath(path); if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } this.path = pathToUse; this.absolutePath = pathToUse; this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); this.clazz = null; } /** * Create a new {@code ClassPathResource} for {@code Class} usage. * <p>The path can be relative to the given class, or absolute within * the
loader
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/batch/OptionalSecondaryTableBatchTest.java
{ "start": 3011, "end": 3413 }
class ____ { @Id private int id; @Version @Column( name = "ver" ) private int version; private String name; @Column(table = "company_tax") private Integer taxNumber; public Company() { } public Company(int id) { this.id = id; } public Company(int id, String name, Integer taxNumber) { this.id = id; this.name = name; this.taxNumber = taxNumber; } } }
Company
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetoone/OneToOneMapsIdJoinColumnTest.java
{ "start": 1966, "end": 2465 }
class ____ { @Id private String id; @OneToOne(mappedBy = "person", cascade = CascadeType.PERSIST, optional = false) private PersonDetails details; public Person() { } public Person(String id) { this.id = id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setDetails(PersonDetails details) { this.details = details; details.setPerson( this ); } } @Entity(name = "PersonDetails") public static
Person
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/IsRouterActiveServlet.java
{ "start": 1029, "end": 1387 }
class ____ extends IsActiveServlet { @Override protected boolean isActive() { final ServletContext context = getServletContext(); final Router router = RouterHttpServer.getRouterFromContext(context); final RouterServiceState routerState = router.getRouterState(); return routerState == RouterServiceState.RUNNING; } }
IsRouterActiveServlet
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerToManyWhereTest.java
{ "start": 1466, "end": 5620 }
class ____ { @AfterEach void dropTestData(SessionFactoryScope factoryScope) { factoryScope.dropData(); } @Test @JiraKey( value = "HHH-13011" ) public void testAssociatedWhereClause(SessionFactoryScope factoryScope) { var product = new Product(); var flowers = new Category(); flowers.id = 1; flowers.name = "flowers"; flowers.description = "FLOWERS"; product.categoriesOneToMany.add( flowers ); product.categoriesWithDescOneToMany.add( flowers ); product.categoriesManyToMany.add( flowers ); product.categoriesWithDescManyToMany.add( flowers ); product.categoriesWithDescIdLt4ManyToMany.add( flowers ); var vegetables = new Category(); vegetables.id = 2; vegetables.name = "vegetables"; vegetables.description = "VEGETABLES"; product.categoriesOneToMany.add( vegetables ); product.categoriesWithDescOneToMany.add( vegetables ); product.categoriesManyToMany.add( vegetables ); product.categoriesWithDescManyToMany.add( vegetables ); product.categoriesWithDescIdLt4ManyToMany.add( vegetables ); var dogs = new Category(); dogs.id = 3; dogs.name = "dogs"; dogs.description = null; product.categoriesOneToMany.add( dogs ); product.categoriesWithDescOneToMany.add( dogs ); product.categoriesManyToMany.add( dogs ); product.categoriesWithDescManyToMany.add( dogs ); product.categoriesWithDescIdLt4ManyToMany.add( dogs ); var building = new Category(); building.id = 4; building.name = "building"; building.description = "BUILDING"; product.categoriesOneToMany.add( building ); product.categoriesWithDescOneToMany.add( building ); product.categoriesManyToMany.add( building ); product.categoriesWithDescManyToMany.add( building ); product.categoriesWithDescIdLt4ManyToMany.add( building ); factoryScope.inTransaction( (session) -> { session.persist( flowers ); session.persist( vegetables ); session.persist( dogs ); session.persist( building ); session.persist( product ); } ); factoryScope.inTransaction( (session) -> { var p = session.find( Product.class, product.id ); assertNotNull( p ); assertEquals( 4, p.categoriesOneToMany.size() ); checkIds( p.categoriesOneToMany, new Integer[] { 1, 2, 3, 4 } ); assertEquals( 3, p.categoriesWithDescOneToMany.size() ); checkIds( p.categoriesWithDescOneToMany, new Integer[] { 1, 2, 4 } ); assertEquals( 4, p.categoriesManyToMany.size() ); checkIds( p.categoriesManyToMany, new Integer[] { 1, 2, 3, 4 } ); assertEquals( 3, p.categoriesWithDescManyToMany.size() ); checkIds( p.categoriesWithDescManyToMany, new Integer[] { 1, 2, 4 } ); assertEquals( 2, p.categoriesWithDescIdLt4ManyToMany.size() ); checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 1, 2 } ); } ); factoryScope.inTransaction( (session) -> { var c = session.find( Category.class, flowers.id ); assertNotNull( c ); c.inactive = 1; } ); factoryScope.inTransaction( (session) -> { var c = session.find( Category.class, flowers.id ); assertNull( c ); } ); factoryScope.inTransaction( (session) -> { var p = session.find( Product.class, product.id ); assertNotNull( p ); assertEquals( 3, p.categoriesOneToMany.size() ); checkIds( p.categoriesOneToMany, new Integer[] { 2, 3, 4 } ); assertEquals( 2, p.categoriesWithDescOneToMany.size() ); checkIds( p.categoriesWithDescOneToMany, new Integer[] { 2, 4 } ); assertEquals( 3, p.categoriesManyToMany.size() ); checkIds( p.categoriesManyToMany, new Integer[] { 2, 3, 4 } ); assertEquals( 2, p.categoriesWithDescManyToMany.size() ); checkIds( p.categoriesWithDescManyToMany, new Integer[] { 2, 4 } ); assertEquals( 1, p.categoriesWithDescIdLt4ManyToMany.size() ); checkIds( p.categoriesWithDescIdLt4ManyToMany, new Integer[] { 2 } ); } ); } private void checkIds(Set<Category> categories, Integer[] expectedIds) { final Set<Integer> expectedIdSet = new HashSet<>( Arrays.asList( expectedIds ) ); for ( Category category : categories ) { expectedIdSet.remove( category.id ); } assertTrue( expectedIdSet.isEmpty() ); } @Entity(name = "Product") public static
EagerToManyWhereTest
java
apache__flink
flink-core-api/src/main/java/org/apache/flink/api/common/state/v2/ListState.java
{ "start": 949, "end": 1851 }
interface ____ partitioned list state in Operations. The state is accessed and * modified by user functions, and checkpointed consistently by the system as part of the * distributed snapshots. * * <p>The state can be a keyed list state or an operator list state. * * <p>When it is a keyed list state, it is accessed by functions applied on a {@code KeyedStream}. * The key is automatically supplied by the system, so the function always sees the value mapped to * the key of the current element. That way, the system can handle stream and state partitioning * consistently together. * * <p>When it is an operator list state, the list is a collection of state items that are * independent from each other and eligible for redistribution across operator instances in case of * changed operator parallelism. * * @param <T> Type of values that this list state keeps. */ @Experimental public
for
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/inject/ExecutionHandle.java
{ "start": 1368, "end": 3532 }
interface ____<T, R> extends AnnotationMetadataDelegate { /** * The target of the method invocation. * * @return The target object */ T getTarget(); /** * @return The declaring type */ Class<T> getDeclaringType(); /** * @return The required argument types. */ Argument[] getArguments(); /** * Invokes the method. * * @param arguments The arguments * @return The result */ R invoke(Object... arguments); /** * Creates an {@link ExecutionHandle} for the give bean and method. * * @param bean The bean * @param method The method * @param <T2> The bean type * @param <R2> The method return type * @return The execution handle */ static <T2, R2> MethodExecutionHandle<T2, R2> of(T2 bean, ExecutableMethod<T2, R2> method) { return new MethodExecutionHandle<>() { @NonNull @Override public ExecutableMethod<T2, R2> getExecutableMethod() { return method; } @Override public T2 getTarget() { return bean; } @Override public Class<T2> getDeclaringType() { return (Class<T2>) bean.getClass(); } @Override public String getMethodName() { return method.getMethodName(); } @Override public Argument[] getArguments() { return method.getArguments(); } @Override public Method getTargetMethod() { return method.getTargetMethod(); } @Override public ReturnType getReturnType() { return method.getReturnType(); } @Override public R2 invoke(Object... arguments) { return method.invoke(bean, arguments); } @Override public AnnotationMetadata getAnnotationMetadata() { return method.getAnnotationMetadata(); } }; } }
ExecutionHandle
java
quarkusio__quarkus
extensions/spring-web/resteasy-reactive/tests/src/test/java/io/quarkus/spring/web/resteasy/reactive/test/BasicMappingTest.java
{ "start": 333, "end": 7874 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(SomeClass.class, Greeting.class, TestController.class, ResponseEntityController.class, ResponseStatusController.class, GreetingControllerWithNoRequestMapping.class)); @Test public void verifyGetWithQueryParam() { when().get(TestController.CONTROLLER_PATH + "/hello?name=people") .then() .statusCode(200) .contentType("text/plain") .body(is("hello people")); } @Test public void verifyRequestMappingWithNoMethod() { when().get(TestController.CONTROLLER_PATH + "/hello4?name=people") .then() .statusCode(200) .contentType("text/plain") .body(is("hello people")); } @Test public void verifyGetToMethodWithoutForwardSlash() { when().get(TestController.CONTROLLER_PATH + "/yolo") .then() .statusCode(200) .body(is("yolo")); } @Test public void verifyGetUsingDefaultValue() { when().get(TestController.CONTROLLER_PATH + "/hello2") .then() .statusCode(200) .body(is("hello world")); } @Test public void verifyGetUsingNonLatinChars() { when().get(TestController.CONTROLLER_PATH + "/hello3?name=Γιώργος") .then() .statusCode(200) .body(is("hello Γιώργος")); } @Test public void verifyPathWithWildcard() { when().get(TestController.CONTROLLER_PATH + "/wildcard/whatever/world") .then() .statusCode(200) .body(is("world")); } @Test public void verifyPathWithMultipleWildcards() { when().get(TestController.CONTROLLER_PATH + "/wildcard2/something/folks/somethingelse") .then() .statusCode(200) .body(is("folks")); } @Test public void verifyPathWithAntStyleWildCard() { when().get(TestController.CONTROLLER_PATH + "/antwildcard/whatever/we/want") .then() .statusCode(200) .body(is("ant")); } @Test public void verifyPathWithCharacterWildCard() { for (char c : new char[] { 't', 'r' }) { when().get(TestController.CONTROLLER_PATH + String.format("/ca%cs", c)) .then() .statusCode(200) .body(is("single")); } } @Test public void verifyPathWithMultipleCharacterWildCards() { for (String path : new String[] { "/cars/shop/info", "/cart/show/info" }) { when().get(TestController.CONTROLLER_PATH + path) .then() .statusCode(200) .body(is("multiple")); } } @Test public void verifyPathVariableTypeConversion() { when().get(TestController.CONTROLLER_PATH + "/int/9") .then() .statusCode(200) .body(is("10")); } @Test public void verifyJsonGetWithPathParamAndGettingMapping() { when().get(TestController.CONTROLLER_PATH + "/json/dummy") .then() .statusCode(200) .contentType("application/json") .body("message", is("dummy")); } @Test public void verifyJsonOnRequestMappingGetWithPathParamAndRequestMapping() { when().get(TestController.CONTROLLER_PATH + "/json2/dummy") .then() .statusCode(200) .contentType("application/json") .body("message", is("dummy")); } @Test public void verifyJsonPostWithPostMapping() { given().body("{\"message\": \"hi\"}") .contentType("application/json") .when().post(TestController.CONTROLLER_PATH + "/json") .then() .statusCode(200) .contentType("text/plain") .body(is("hi")); } @Test public void verifyJsonPostWithRequestMapping() { given().body("{\"message\": \"hi\"}") .contentType("application/json") .when().post(TestController.CONTROLLER_PATH + "/json2") .then() .statusCode(200) .contentType("text/plain") .body(is("hi")); } @Test public void verifyMultipleInputAndJsonResponse() { given().body("{\"message\": \"hi\"}") .contentType("application/json") .when().put(TestController.CONTROLLER_PATH + "/json3?suffix=!") .then() .statusCode(200) .contentType("application/json") .body("message", is("hi!")); } @Test public void verifyEmptyContentResponseEntity() { when().get(ResponseEntityController.CONTROLLER_PATH + "/noContent") .then() .statusCode(204); } @Test public void verifyStringContentResponseEntity() { when().get(ResponseEntityController.CONTROLLER_PATH + "/string") .then() .statusCode(200) .contentType("text/plain") .body(is("hello world")); } @Test public void verifyJsonContentResponseEntity() { when().get(ResponseEntityController.CONTROLLER_PATH + "/json") .then() .statusCode(200) .contentType("application/json") .body("message", is("dummy")) .header("custom-header", "somevalue"); } @Test public void verifyJsonContentResponseEntityWithoutType() { when().get(ResponseEntityController.CONTROLLER_PATH + "/json2") .then() .statusCode(200) .contentType("application/json") .body("message", is("dummy")); } @Test public void verifyJsonContentResponseEntityWithCustomJsonHeader() { when().get(ResponseEntityController.CONTROLLER_PATH + "/custom-json") .then() .statusCode(200) .contentType("application/jsontest") .header("custom-header", "somevalue"); } @Test public void verifyJsonContentResponseEntityWithContentType() { when().get(ResponseEntityController.CONTROLLER_PATH + "/content-type") .then() .statusCode(200) .contentType("application/jsontest") .header("custom-header", "somevalue"); } @Test public void verifyEmptyContentResponseStatus() { when().get(ResponseStatusController.CONTROLLER_PATH + "/noContent") .then() .statusCode(200); } @Test public void verifyStringResponseStatus() { when().get(ResponseStatusController.CONTROLLER_PATH + "/string") .then() .statusCode(202) .contentType("text/plain") .body(is("accepted")); } @Test public void verifyControllerWithoutRequestMapping() { when().get("/hello") .then() .statusCode(200) .contentType("text/plain") .body(is("hello world")); } }
BasicMappingTest
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/main/java/io/quarkus/opentelemetry/deployment/logging/LogHandlerProcessor.java
{ "start": 1105, "end": 2300 }
class ____ { private static final DotName LOG_RECORD_EXPORTER = DotName.createSimple(LogRecordExporter.class.getName()); private static final DotName LOG_RECORD_PROCESSOR = DotName.createSimple(LogRecordProcessor.class.getName()); @BuildStep void beanSupport(BuildProducer<UnremovableBeanBuildItem> unremovableProducer) { unremovableProducer.produce(UnremovableBeanBuildItem.beanTypes(LOG_RECORD_EXPORTER)); unremovableProducer.produce(UnremovableBeanBuildItem.beanTypes(LOG_RECORD_PROCESSOR)); } @BuildStep void nativeSupport(BuildProducer<ServiceProviderBuildItem> servicesProducer) { servicesProducer.produce( new ServiceProviderBuildItem(ConfigurableLogRecordExporterProvider.class.getName(), LogsExporterCDIProvider.class.getName())); } @BuildStep @Record(ExecutionTime.RUNTIME_INIT) @Consume(OpenTelemetrySdkBuildItem.class) LogHandlerBuildItem build(OpenTelemetryLogRecorder recorder, BeanContainerBuildItem beanContainerBuildItem) { return new LogHandlerBuildItem(recorder.initializeHandler(beanContainerBuildItem.getValue())); } }
LogHandlerProcessor
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/server/session/InMemoryWebSessionStoreTests.java
{ "start": 1244, "end": 6247 }
class ____ { private final InMemoryWebSessionStore store = new InMemoryWebSessionStore(); @Test void startsSessionExplicitly() { WebSession session = this.store.createWebSession().block(); assertThat(session).isNotNull(); session.start(); assertThat(session.isStarted()).isTrue(); } @Test void startsSessionImplicitly() { WebSession session = this.store.createWebSession().block(); assertThat(session).isNotNull(); // We intentionally do not invoke start(). // session.start(); session.getAttributes().put("foo", "bar"); assertThat(session.isStarted()).isTrue(); } @Test // gh-24027, gh-26958 void createSessionDoesNotBlock() { this.store.createWebSession() .doOnNext(session -> assertThat(Schedulers.isInNonBlockingThread()).isTrue()) .block(); } @Test void retrieveExpiredSession() { WebSession session = this.store.createWebSession().block(); assertThat(session).isNotNull(); session.getAttributes().put("foo", "bar"); session.save().block(); String id = session.getId(); WebSession retrieved = this.store.retrieveSession(id).block(); assertThat(retrieved).isNotNull(); assertThat(retrieved).isSameAs(session); // Fast-forward 31 minutes this.store.setClock(Clock.offset(this.store.getClock(), Duration.ofMinutes(31))); WebSession retrievedAgain = this.store.retrieveSession(id).block(); assertThat(retrievedAgain).isNull(); } @Test void lastAccessTimeIsUpdatedOnRetrieve() { WebSession session1 = this.store.createWebSession().block(); assertThat(session1).isNotNull(); String id = session1.getId(); Instant time1 = session1.getLastAccessTime(); session1.start(); session1.save().block(); // Fast-forward a few seconds this.store.setClock(Clock.offset(this.store.getClock(), Duration.ofSeconds(5))); WebSession session2 = this.store.retrieveSession(id).block(); assertThat(session2).isNotNull(); assertThat(session2).isSameAs(session1); Instant time2 = session2.getLastAccessTime(); assertThat(time1.isBefore(time2)).isTrue(); } @Test // SPR-17051 void sessionInvalidatedBeforeSave() { // Request 1 creates session WebSession session1 = this.store.createWebSession().block(); assertThat(session1).isNotNull(); String id = session1.getId(); session1.start(); session1.save().block(); // Request 2 retrieves session WebSession session2 = this.store.retrieveSession(id).block(); assertThat(session2).isNotNull(); assertThat(session2).isSameAs(session1); // Request 3 retrieves and invalidates WebSession session3 = this.store.retrieveSession(id).block(); assertThat(session3).isNotNull(); assertThat(session3).isSameAs(session1); session3.invalidate().block(); // Request 2 saves session after invalidated session2.save().block(); // Session should not be present WebSession session4 = this.store.retrieveSession(id).block(); assertThat(session4).isNull(); } @Test void expirationCheckPeriod() { // Create 100 sessions IntStream.rangeClosed(1, 100).forEach(i -> insertSession()); assertNumSessions(100); // Force a new clock (31 min later). Don't use setter which would clean expired sessions. DirectFieldAccessor accessor = new DirectFieldAccessor(this.store); accessor.setPropertyValue("clock", Clock.offset(this.store.getClock(), Duration.ofMinutes(31))); assertNumSessions(100); // Create 1 more which forces a time-based check (clock moved forward). insertSession(); assertNumSessions(1); } @Test void maxSessions() { this.store.setMaxSessions(10); IntStream.rangeClosed(1, 10).forEach(i -> insertSession()); assertThatIllegalStateException() .isThrownBy(this::insertSession) .withMessage("Max sessions limit reached: 10"); } @Test void updateSession() { WebSession session = insertSession(); StepVerifier.create(session.save()) .expectComplete() .verify(); } @Test // gh-35013 void updateSessionAfterMaxSessionLimitIsExceeded() { this.store.setMaxSessions(10); WebSession session = insertSession(); assertNumSessions(1); IntStream.rangeClosed(1, 9).forEach(i -> insertSession()); assertNumSessions(10); // Updating an existing session should succeed. StepVerifier.create(session.save()) .expectComplete() .verify(); assertNumSessions(10); // Saving an additional new session should fail. assertThatIllegalStateException() .isThrownBy(this::insertSession) .withMessage("Max sessions limit reached: 10"); assertNumSessions(10); // Updating an existing session again should still succeed. StepVerifier.create(session.save()) .expectComplete() .verify(); assertNumSessions(10); } private WebSession insertSession() { WebSession session = this.store.createWebSession().block(); assertThat(session).isNotNull(); session.start(); session.save().block(); return session; } private void assertNumSessions(int numSessions) { assertThat(store.getSessions()).hasSize(numSessions); } }
InMemoryWebSessionStoreTests
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/state/ChangelogRecoveryCachingITCase.java
{ "start": 4106, "end": 10127 }
class ____ extends TestLogger { private static final int ACCUMULATE_TIME_MILLIS = 500; // high enough to build some state private static final int PARALLELISM = 10; // high enough to trigger DSTL file multiplexing @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private OpenOnceFileSystem fileSystem; private MiniClusterWithClientResource cluster; @Before public void before() throws Exception { File tmpFolder = temporaryFolder.newFolder(); registerFileSystem(fileSystem = new OpenOnceFileSystem(), tmpFolder.toURI().getScheme()); Configuration configuration = new Configuration(); configuration.set(CACHE_IDLE_TIMEOUT, Duration.ofDays(365)); // cache forever FsStateChangelogStorageFactory.configure( configuration, tmpFolder, Duration.ofMinutes(1), 10); cluster = new MiniClusterWithClientResource( new MiniClusterResourceConfiguration.Builder() .setConfiguration(configuration) .setNumberTaskManagers(1) .setNumberSlotsPerTaskManager(PARALLELISM) .build()); cluster.before(); } @After public void after() throws Exception { if (cluster != null) { cluster.after(); cluster = null; } FileSystem.initialize(new Configuration(), null); } @Test public void test() throws Exception { JobID jobID1 = submit(configureJob(temporaryFolder.newFolder()), graph -> {}); Thread.sleep(ACCUMULATE_TIME_MILLIS); String cpLocation = checkpointAndCancel(jobID1); JobID jobID2 = submit( configureJob(temporaryFolder.newFolder()), graph -> graph.setSavepointRestoreSettings(forPath(cpLocation))); waitForAllTaskRunning(cluster.getMiniCluster(), jobID2, true); cluster.getClusterClient().cancel(jobID2).get(); checkState(fileSystem.hasOpenedPaths()); } private JobID submit(Configuration conf, Consumer<JobGraph> updateGraph) throws InterruptedException, ExecutionException { JobGraph jobGraph = createJobGraph(conf); updateGraph.accept(jobGraph); return cluster.getClusterClient().submitJob(jobGraph).get(); } private JobGraph createJobGraph(Configuration conf) { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf); env.fromSequence(Long.MIN_VALUE, Long.MAX_VALUE) .keyBy(num -> num % 1000) .map( new RichMapFunction<Long, Long>() { @Override public Long map(Long value) throws Exception { getRuntimeContext() .getState(new ValueStateDescriptor<>("state", Long.class)) .update(value); return value; } }) .sinkTo(new DiscardingSink<>()); return env.getStreamGraph().getJobGraph(); } private Configuration configureJob(File cpDir) { Configuration conf = new Configuration(); conf.set(CheckpointingOptions.EXTERNALIZED_CHECKPOINT_RETENTION, RETAIN_ON_CANCELLATION); conf.set(DEFAULT_PARALLELISM, PARALLELISM); conf.set(ENABLE_STATE_CHANGE_LOG, true); conf.set( CheckpointingOptions.CHECKPOINTING_CONSISTENCY_MODE, CheckpointingMode.EXACTLY_ONCE); conf.set(CheckpointingOptions.CHECKPOINTING_INTERVAL, Duration.ofMillis(10)); conf.set(CHECKPOINT_STORAGE, "filesystem"); conf.set(CHECKPOINTS_DIRECTORY, cpDir.toURI().toString()); conf.set(STATE_BACKEND, "hashmap"); conf.set(LOCAL_RECOVERY, false); // force download // tune changelog conf.set(PREEMPTIVE_PERSIST_THRESHOLD, MemorySize.ofMebiBytes(10)); conf.set(PERIODIC_MATERIALIZATION_ENABLED, false); conf.set(CheckpointingOptions.ENABLE_UNALIGNED, true); // speedup conf.set( CheckpointingOptions.ALIGNED_CHECKPOINT_TIMEOUT, Duration.ZERO); // prevent randomization conf.set( CheckpointingOptions.UNALIGNED_MAX_SUBTASKS_PER_CHANNEL_STATE_FILE, 1); // prevent file is opened multiple times conf.set(BUFFER_DEBLOAT_ENABLED, false); // prevent randomization conf.set(RESTART_STRATEGY, "none"); // not expecting any failures conf.set( FILE_MERGING_ENABLED, false); // TODO: remove file merging setting after FLINK-32085 return conf; } private String checkpointAndCancel(JobID jobID) throws Exception { waitForCheckpoint(jobID, cluster.getMiniCluster(), 1); cluster.getClusterClient().cancel(jobID).get(); checkStatus(jobID); return CommonTestUtils.getLatestCompletedCheckpointPath(jobID, cluster.getMiniCluster()) .<NoSuchElementException>orElseThrow( () -> { throw new NoSuchElementException("No checkpoint was created yet"); }); } private void checkStatus(JobID jobID) throws InterruptedException, ExecutionException { if (cluster.getClusterClient().getJobStatus(jobID).get().isGloballyTerminalState()) { cluster.getClusterClient() .requestJobResult(jobID) .get() .getSerializedThrowable() .ifPresent( serializedThrowable -> { throw new RuntimeException(serializedThrowable); }); } } private static
ChangelogRecoveryCachingITCase