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
spring-projects__spring-boot
module/spring-boot-elasticsearch/src/main/java/org/springframework/boot/elasticsearch/autoconfigure/ElasticsearchRestClientConfigurations.java
{ "start": 6281, "end": 6951 }
class ____ { @Bean @ConditionalOnMissingBean Sniffer elasticsearchSniffer(Rest5Client client, ElasticsearchProperties properties) { SnifferBuilder builder = Sniffer.builder(client); PropertyMapper map = PropertyMapper.get(); Duration interval = properties.getRestclient().getSniffer().getInterval(); map.from(interval).asInt(Duration::toMillis).to(builder::setSniffIntervalMillis); Duration delayAfterFailure = properties.getRestclient().getSniffer().getDelayAfterFailure(); map.from(delayAfterFailure).asInt(Duration::toMillis).to(builder::setSniffAfterFailureDelayMillis); return builder.build(); } } static
RestClientSnifferConfiguration
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.java
{ "start": 23351, "end": 23944 }
class ____ implements Advisor, Serializable { private final String beanName; private final String message; public PrototypePlaceholderAdvisor(String beanName) { this.beanName = beanName; this.message = "Placeholder for prototype Advisor/Advice with bean name '" + beanName + "'"; } public String getBeanName() { return this.beanName; } @Override public Advice getAdvice() { throw new UnsupportedOperationException("Cannot invoke methods: " + this.message); } @Override public String toString() { return this.message; } } }
PrototypePlaceholderAdvisor
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/results/graph/collection/internal/BagInitializerProducer.java
{ "start": 753, "end": 1991 }
class ____ implements CollectionInitializerProducer { private final PluralAttributeMapping bagDescriptor; private final @Nullable Fetch collectionIdFetch; private final Fetch elementFetch; public BagInitializerProducer( PluralAttributeMapping bagDescriptor, Fetch collectionIdFetch, Fetch elementFetch) { this.bagDescriptor = bagDescriptor; if ( bagDescriptor.getIdentifierDescriptor() != null ) { assert collectionIdFetch != null; this.collectionIdFetch = collectionIdFetch; } else { assert collectionIdFetch == null; this.collectionIdFetch = null; } this.elementFetch = elementFetch; } @Override public CollectionInitializer<?> produceInitializer( NavigablePath navigablePath, PluralAttributeMapping attribute, InitializerParent<?> parent, LockMode lockMode, DomainResult<?> collectionKeyResult, DomainResult<?> collectionValueKeyResult, boolean isResultInitializer, AssemblerCreationState creationState) { return new BagInitializer( navigablePath, bagDescriptor, parent, lockMode, collectionKeyResult, collectionValueKeyResult, isResultInitializer, creationState, elementFetch, collectionIdFetch ); } }
BagInitializerProducer
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/booleanarray/BooleanArrayAssert_usingElementComparator_Test.java
{ "start": 1087, "end": 1899 }
class ____ extends BooleanArrayAssertBaseTest { @Mock private Comparator<Boolean> comparator; @Override @Test @SuppressWarnings("deprecation") public void should_have_internal_effects() { assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> // in that, we don't care of the comparator, the point to check is that we can't use a comparator assertions.usingElementComparator(comparator)); } @Override @Test public void should_return_this() { // Disabled since this method throws an exception } @Override protected BooleanArrayAssert invoke_api_method() { // Not used in this test return null; } @Override protected void verify_internal_effects() { // Not used in this test } }
BooleanArrayAssert_usingElementComparator_Test
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/IdentifierNameTest.java
{ "start": 1947, "end": 2335 }
class ____ { // BUG: Diagnostic contains: acronyms private int misnamedRPCClient; int get() { return misnamedRPCClient; } } """) .doTest(); } @Test public void staticFields() { refactoringHelper .addInputLines( "Test.java", """
Test
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-jsonb/runtime/src/main/java/io/quarkus/resteasy/jsonb/vertx/VertxJson.java
{ "start": 5847, "end": 6181 }
class ____ implements JsonbDeserializer<JsonObject> { @Override public JsonObject deserialize(JsonParser parser, DeserializationContext context, Type type) { JsonObject object = new JsonObject(); copy(object, parser.getObject()); return object; } } }
JsonObjectDeserializer
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/introspect/TestAnnotationMerging.java
{ "start": 1277, "end": 3170 }
class ____ { protected Object value; @JsonCreator public TypeWrapper( @JsonProperty("value") @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) Object o) { value = o; } public Object getValue() { return value; } } /* /********************************************************** /* Unit tests /********************************************************** */ @Test public void testSharedNames() throws Exception { ObjectMapper mapper = new ObjectMapper(); assertEquals("{\"x\":6}", mapper.writeValueAsString(new SharedName(6))); } @Test public void testSharedNamesFromGetterToSetter() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(new SharedName2()); assertEquals("{\"x\":1}", json); SharedName2 result = mapper.readValue(json, SharedName2.class); assertNotNull(result); } @Test public void testSharedTypeInfo() throws Exception { final ObjectMapper mapper = jsonMapperBuilder() .polymorphicTypeValidator(new NoCheckSubTypeValidator()) .build(); String json = mapper.writeValueAsString(new Wrapper(13L)); Wrapper result = mapper.readValue(json, Wrapper.class); assertEquals(Long.class, result.value.getClass()); } @Test public void testSharedTypeInfoWithCtor() throws Exception { final ObjectMapper mapper = jsonMapperBuilder() .polymorphicTypeValidator(new NoCheckSubTypeValidator()) .build(); String json = mapper.writeValueAsString(new TypeWrapper(13L)); TypeWrapper result = mapper.readValue(json, TypeWrapper.class); assertEquals(Long.class, result.value.getClass()); } }
TypeWrapper
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/specialization/SpecializationUnsupportedTest.java
{ "start": 477, "end": 1162 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(SomeBean.class)) .assertException(t -> { Throwable rootCause = ExceptionUtil.getRootCause(t); assertTrue( rootCause.getMessage().contains( "Quarkus does not support CDI Full @Specializes annotation"), t.toString()); }); @Test public void trigger() { Assertions.fail(); } @ApplicationScoped @Specializes public static
SpecializationUnsupportedTest
java
google__guice
extensions/servlet/test/com/google/inject/servlet/ServletUtilsTest.java
{ "start": 356, "end": 2724 }
class ____ extends TestCase { public void testGetContextRelativePath() { assertEquals( "/test.html", getContextRelativePath("/a_context_path", "/a_context_path/test.html")); assertEquals("/test.html", getContextRelativePath("", "/test.html")); assertEquals("/test.html", getContextRelativePath("", "/foo/../test.html")); assertEquals("/test.html", getContextRelativePath("", "/././foo/../test.html")); assertEquals("/test.html", getContextRelativePath("", "/foo/../../../../test.html")); assertEquals("/test.html", getContextRelativePath("", "/foo/%2E%2E/test.html")); // %2E == '.' assertEquals("/test.html", getContextRelativePath("", "/foo/%2E%2E/test.html")); // %2F == '/' assertEquals("/foo/%2F/test.html", getContextRelativePath("", "/foo/%2F/test.html")); // %66 == 'f' assertEquals("/foo.html", getContextRelativePath("", "/%66oo.html")); } public void testGetContextRelativePath_preserveQuery() { assertEquals("/foo?q=f", getContextRelativePath("", "/foo?q=f")); assertEquals("/foo?q=%20+%20", getContextRelativePath("", "/foo?q=%20+%20")); } public void testGetContextRelativePathWithWrongPath() { assertNull(getContextRelativePath("/a_context_path", "/test.html")); } public void testGetContextRelativePathWithRootPath() { assertEquals("/", getContextRelativePath("/a_context_path", "/a_context_path")); } public void testGetContextRelativePathWithEmptyPath() { assertNull(getContextRelativePath("", "")); } public void testNormalizePath() { assertEquals("foobar", ServletUtils.normalizePath("foobar")); assertEquals("foo+bar", ServletUtils.normalizePath("foo+bar")); assertEquals("foo%20bar", ServletUtils.normalizePath("foo bar")); assertEquals("foo%25-bar", ServletUtils.normalizePath("foo%-bar")); assertEquals("foo%25+bar", ServletUtils.normalizePath("foo%+bar")); assertEquals("foo%25-0bar", ServletUtils.normalizePath("foo%-0bar")); } private String getContextRelativePath(String contextPath, String requestPath) { HttpServletRequest mock = mock(HttpServletRequest.class); when(mock.getContextPath()).thenReturn(contextPath); when(mock.getRequestURI()).thenReturn(requestPath); String contextRelativePath = ServletUtils.getContextRelativePath(mock); return contextRelativePath; } }
ServletUtilsTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
{ "start": 3499, "end": 3719 }
class ____ { private static final String SUBSCRIPTION_EXCEPTION_MESSAGE = "Subscription to topics, partitions and pattern are mutually exclusive"; private final Logger log; private
SubscriptionState
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/SlowDiskTracker.java
{ "start": 2146, "end": 2299 }
class ____ information from {@link SlowDiskReports} received via * heartbeats. */ @InterfaceAudience.Private @InterfaceStability.Unstable public
aggregates
java
spring-projects__spring-boot
module/spring-boot-data-rest/src/test/java/org/springframework/boot/data/rest/autoconfigure/DataRestAutoConfigurationTests.java
{ "start": 7299, "end": 7412 }
class ____ { } @Import({ TestConfiguration.class, TestRepositoryRestConfigurer.class }) static
TestConfiguration
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/cfg/DefaultCacheProvider.java
{ "start": 4377, "end": 8415 }
class ____ { /** * Maximum Size of the {@link LookupCache} instance created by {@link #forDeserializerCache(DeserializationConfig)}. * Corresponds to {@link DefaultCacheProvider#_maxDeserializerCacheSize}. */ private int _maxDeserializerCacheSize; /** * Maximum Size of the {@link LookupCache} instance created by {@link #forSerializerCache(SerializationConfig)} * Corresponds to {@link DefaultCacheProvider#_maxSerializerCacheSize}. */ private int _maxSerializerCacheSize; /** * Maximum Size of the {@link LookupCache} instance created by {@link #forTypeFactory()}. * Corresponds to {@link DefaultCacheProvider#_maxTypeFactoryCacheSize}. */ private int _maxTypeFactoryCacheSize; Builder() { } /** * Define the maximum size of the {@link LookupCache} instance constructed by {@link #forDeserializerCache(DeserializationConfig)} * and {@link #_buildCache(int)}. * <p> * Note that specifying a maximum size of zero prevents values from being retained in the cache. * * @param maxDeserializerCacheSize Size for the {@link LookupCache} to use within {@link DeserializerCache} * @return this builder * @throws IllegalArgumentException if {@code maxDeserializerCacheSize} is negative */ public Builder maxDeserializerCacheSize(int maxDeserializerCacheSize) { if (maxDeserializerCacheSize < 0) { throw new IllegalArgumentException("Cannot set maxDeserializerCacheSize to a negative value"); } _maxDeserializerCacheSize = maxDeserializerCacheSize; return this; } /** * Define the maximum size of the {@link LookupCache} instance constructed by {@link #forSerializerCache(SerializationConfig)} * and {@link #_buildCache(int)} * <p> * Note that specifying a maximum size of zero prevents values from being retained in the cache. * * @param maxSerializerCacheSize Size for the {@link LookupCache} to use within {@link SerializerCache} * @return this builder * @throws IllegalArgumentException if {@code maxSerializerCacheSize} is negative */ public Builder maxSerializerCacheSize(int maxSerializerCacheSize) { if (maxSerializerCacheSize < 0) { throw new IllegalArgumentException("Cannot set maxSerializerCacheSize to a negative value"); } _maxSerializerCacheSize = maxSerializerCacheSize; return this; } /** * Define the maximum size of the {@link LookupCache} instance constructed by {@link #forTypeFactory()} * and {@link #_buildCache(int)} * <p> * Note that specifying a maximum size of zero prevents values from being retained in the cache. * * @param maxTypeFactoryCacheSize Size for the {@link LookupCache} to use within {@link tools.jackson.databind.type.TypeFactory} * @return this builder * @throws IllegalArgumentException if {@code maxTypeFactoryCacheSize} is negative */ public Builder maxTypeFactoryCacheSize(int maxTypeFactoryCacheSize) { if (maxTypeFactoryCacheSize < 0) { throw new IllegalArgumentException("Cannot set maxTypeFactoryCacheSize to a negative value"); } _maxTypeFactoryCacheSize = maxTypeFactoryCacheSize; return this; } /** * Constructs a {@link DefaultCacheProvider} with the provided configuration values, using defaults where not specified. * * @return A {@link DefaultCacheProvider} instance with the specified configuration */ public DefaultCacheProvider build() { return new DefaultCacheProvider(_maxDeserializerCacheSize, _maxSerializerCacheSize, _maxTypeFactoryCacheSize); } } }
Builder
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/convert/internal/AbstractConverterDescriptor.java
{ "start": 908, "end": 3701 }
class ____<X,Y> implements ConverterDescriptor<X,Y> { private final Class<? extends AttributeConverter<X,Y>> converterClass; private final ResolvedType domainType; private final ResolvedType jdbcType; private final AutoApplicableConverterDescriptor autoApplicableDescriptor; AbstractConverterDescriptor( Class<? extends AttributeConverter<X, Y>> converterClass, Boolean forceAutoApply, ClassmateContext classmateContext) { this.converterClass = converterClass; final var converterParamTypes = resolveConverterClassParamTypes( converterClass, classmateContext ); domainType = converterParamTypes.get( 0 ); jdbcType = converterParamTypes.get( 1 ); autoApplicableDescriptor = resolveAutoApplicableDescriptor( converterClass, forceAutoApply ); } private AutoApplicableConverterDescriptor resolveAutoApplicableDescriptor( Class<? extends AttributeConverter<?,?>> converterClass, Boolean forceAutoApply) { return isAutoApply( converterClass, forceAutoApply ) ? new AutoApplicableConverterDescriptorStandardImpl( this ) : AutoApplicableConverterDescriptorBypassedImpl.INSTANCE; } private static boolean isAutoApply(Class<? extends AttributeConverter<?, ?>> converterClass, Boolean forceAutoApply) { if ( forceAutoApply != null ) { // if the caller explicitly specified whether to auto-apply, honor that return forceAutoApply; } else { // otherwise, look at the converter's @Converter annotation final Converter annotation = converterClass.getAnnotation( Converter.class ); return annotation != null && annotation.autoApply(); } } @Override public Class<? extends AttributeConverter<X,Y>> getAttributeConverterClass() { return converterClass; } @Override public ResolvedType getDomainValueResolvedType() { return domainType; } @Override public ResolvedType getRelationalValueResolvedType() { return jdbcType; } @Override public AutoApplicableConverterDescriptor getAutoApplyDescriptor() { return autoApplicableDescriptor; } @Override public JpaAttributeConverter<X,Y> createJpaAttributeConverter(JpaAttributeConverterCreationContext context) { return new AttributeConverterBean<>( createManagedBean( context ), context.getJavaTypeRegistry().resolveDescriptor( converterClass ), getDomainClass(), getRelationalClass(), context ); } @SuppressWarnings("unchecked") private Class<Y> getRelationalClass() { return (Class<Y>) getRelationalValueResolvedType().getErasedType(); } @SuppressWarnings("unchecked") private Class<X> getDomainClass() { return (Class<X>) getDomainValueResolvedType().getErasedType(); } protected abstract ManagedBean<? extends AttributeConverter<X,Y>> createManagedBean(JpaAttributeConverterCreationContext context); }
AbstractConverterDescriptor
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/event/ApplicationEventsTestExecutionListener.java
{ "start": 2297, "end": 5758 }
class ____ the given test context is annotated with * {@link RecordApplicationEvents @RecordApplicationEvents}. * <p>Permissible values include {@link Boolean#TRUE} and {@link Boolean#FALSE}. */ private static final String RECORD_APPLICATION_EVENTS = Conventions.getQualifiedAttributeName( ApplicationEventsTestExecutionListener.class, "recordApplicationEvents"); private static final Object applicationEventsMonitor = new Object(); /** * Returns {@value #ORDER}, which ensures that the {@code ApplicationEventsTestExecutionListener} * is ordered after the * {@link org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener * DirtiesContextBeforeModesTestExecutionListener} and before the * {@link org.springframework.test.context.bean.override.BeanOverrideTestExecutionListener * BeanOverrideTestExecutionListener} and the * {@link org.springframework.test.context.support.DependencyInjectionTestExecutionListener * DependencyInjectionTestExecutionListener}. */ @Override public final int getOrder() { return ORDER; } @Override public void prepareTestInstance(TestContext testContext) throws Exception { if (recordApplicationEvents(testContext)) { registerListenerAndResolvableDependencyIfNecessary(testContext.getApplicationContext()); ApplicationEventsHolder.registerApplicationEvents(); } } @Override public void beforeTestMethod(TestContext testContext) throws Exception { if (recordApplicationEvents(testContext)) { // Register a new ApplicationEvents instance for the current thread // in case the test instance is shared -- for example, in TestNG or // JUnit Jupiter with @TestInstance(PER_CLASS) semantics. ApplicationEventsHolder.registerApplicationEventsIfNecessary(); } } @Override public void afterTestMethod(TestContext testContext) throws Exception { if (recordApplicationEvents(testContext)) { ApplicationEventsHolder.unregisterApplicationEvents(); } } private boolean recordApplicationEvents(TestContext testContext) { return testContext.computeAttribute(RECORD_APPLICATION_EVENTS, name -> TestContextAnnotationUtils.hasAnnotation(testContext.getTestClass(), RecordApplicationEvents.class)); } private void registerListenerAndResolvableDependencyIfNecessary(ApplicationContext applicationContext) { Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext, "The ApplicationContext for the test must be an AbstractApplicationContext"); AbstractApplicationContext aac = (AbstractApplicationContext) applicationContext; // Synchronize to avoid race condition in parallel test execution synchronized(applicationEventsMonitor) { boolean notAlreadyRegistered = aac.getApplicationListeners().stream() .map(Object::getClass) .noneMatch(ApplicationEventsApplicationListener.class::equals); if (notAlreadyRegistered) { // Register a new ApplicationEventsApplicationListener. aac.addApplicationListener(new ApplicationEventsApplicationListener()); // Register ApplicationEvents as a resolvable dependency for @Autowired support in test classes. ConfigurableListableBeanFactory beanFactory = aac.getBeanFactory(); beanFactory.registerResolvableDependency(ApplicationEvents.class, new ApplicationEventsObjectFactory()); } } } /** * Factory that exposes the current {@link ApplicationEvents} object on demand. */ @SuppressWarnings("serial") private static
for
java
spring-projects__spring-security
oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtClaimNames.java
{ "start": 1000, "end": 2117 }
class ____ { /** * {@code iss} - the Issuer claim identifies the principal that issued the JWT */ public static final String ISS = "iss"; /** * {@code sub} - the Subject claim identifies the principal that is the subject of the * JWT */ public static final String SUB = "sub"; /** * {@code aud} - the Audience claim identifies the recipient(s) that the JWT is * intended for */ public static final String AUD = "aud"; /** * {@code exp} - the Expiration time claim identifies the expiration time on or after * which the JWT MUST NOT be accepted for processing */ public static final String EXP = "exp"; /** * {@code nbf} - the Not Before claim identifies the time before which the JWT MUST * NOT be accepted for processing */ public static final String NBF = "nbf"; /** * {@code iat} - The Issued at claim identifies the time at which the JWT was issued */ public static final String IAT = "iat"; /** * {@code jti} - The JWT ID claim provides a unique identifier for the JWT */ public static final String JTI = "jti"; private JwtClaimNames() { } }
JwtClaimNames
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/producer/internals/RecordAccumulatorTest.java
{ "start": 88007, "end": 90425 }
class ____ { final int numSplit; final int numBatches; BatchDrainedResult(int numSplit, int numBatches) { this.numBatches = numBatches; this.numSplit = numSplit; } } /** * Return the offset delta. */ private int expectedNumAppends(int batchSize) { int size = 0; int offsetDelta = 0; while (true) { int recordSize = DefaultRecord.sizeInBytes(offsetDelta, 0, key.length, value.length, Record.EMPTY_HEADERS); if (size + recordSize > batchSize) return offsetDelta; offsetDelta += 1; size += recordSize; } } private RecordAccumulator createTestRecordAccumulator(int batchSize, long totalSize, Compression compression, int lingerMs) { int deliveryTimeoutMs = 3200; return createTestRecordAccumulator(deliveryTimeoutMs, batchSize, totalSize, compression, lingerMs); } private RecordAccumulator createTestRecordAccumulator(int deliveryTimeoutMs, int batchSize, long totalSize, Compression compression, int lingerMs) { return createTestRecordAccumulator(null, deliveryTimeoutMs, batchSize, totalSize, compression, lingerMs); } /** * Return a test RecordAccumulator instance */ private RecordAccumulator createTestRecordAccumulator( TransactionManager txnManager, int deliveryTimeoutMs, int batchSize, long totalSize, Compression compression, int lingerMs ) { long retryBackoffMs = 100L; long retryBackoffMaxMs = 1000L; String metricGrpName = "producer-metrics"; return new RecordAccumulator( logContext, batchSize, compression, lingerMs, retryBackoffMs, retryBackoffMaxMs, deliveryTimeoutMs, metrics, metricGrpName, time, txnManager, new BufferPool(totalSize, batchSize, metrics, time, metricGrpName)) { @Override BuiltInPartitioner createBuiltInPartitioner(LogContext logContext, String topic, int stickyBatchSize) { return new SequentialPartitioner(logContext, topic, stickyBatchSize); } }; } private
BatchDrainedResult
java
quarkusio__quarkus
extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/OidcRequestAndResponseFilterTest.java
{ "start": 31698, "end": 32018 }
class ____ extends CallableFilterParent implements OidcRequestFilter { @Override public void filter(OidcRequestContext requestContext) { called(); } } @TenantFeature("response-my-code-tenant") @ApplicationScoped public static
RequestTenantFeatureBearerTokenRequestFilter
java
apache__kafka
connect/api/src/main/java/org/apache/kafka/connect/health/TaskState.java
{ "start": 949, "end": 2467 }
class ____ extends AbstractState { private final int taskId; /** * Provides an instance of {@link TaskState}. * * @param taskId the id associated with the connector task * @param state the status of the task, may not be {@code null} or empty * @param workerId id of the worker the task is associated with, may not be {@code null} or empty * @param trace error message if that task had failed or errored out, may be {@code null} or empty */ public TaskState(int taskId, String state, String workerId, String trace) { super(state, workerId, trace); this.taskId = taskId; } /** * Provides the ID of the task. * * @return the task ID */ public int taskId() { return taskId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; TaskState taskState = (TaskState) o; return taskId == taskState.taskId; } @Override public int hashCode() { return Objects.hash(super.hashCode(), taskId); } @Override public String toString() { return "TaskState{" + "taskId='" + taskId + '\'' + "state='" + state() + '\'' + ", traceMessage='" + traceMessage() + '\'' + ", workerId='" + workerId() + '\'' + '}'; } }
TaskState
java
alibaba__druid
core/src/main/java/com/alibaba/druid/support/profile/ProfileEntryStat.java
{ "start": 787, "end": 1981 }
class ____ { private volatile long executeCount; private volatile long executeTimeNanos; private static final AtomicLongFieldUpdater<ProfileEntryStat> executeCountUpdater; private static final AtomicLongFieldUpdater<ProfileEntryStat> executeTimeNanosUpdater; static { executeCountUpdater = AtomicLongFieldUpdater.newUpdater(ProfileEntryStat.class, "executeCount"); executeTimeNanosUpdater = AtomicLongFieldUpdater.newUpdater(ProfileEntryStat.class, "executeTimeNanos"); } public ProfileEntryStatValue getValue(boolean reset) { ProfileEntryStatValue val = new ProfileEntryStatValue(); val.setExecuteCount(get(this, executeCountUpdater, reset)); val.setExecuteTimeNanos(get(this, executeTimeNanosUpdater, reset)); return val; } public long getExecuteCount() { return executeCount; } public void addExecuteCount(long delta) { executeCountUpdater.addAndGet(this, delta); } public long getExecuteTimeNanos() { return executeTimeNanos; } public void addExecuteTimeNanos(long delta) { executeTimeNanosUpdater.addAndGet(this, delta); } }
ProfileEntryStat
java
apache__spark
sql/catalyst/src/test/java/org/apache/spark/sql/catalyst/JavaTypeInferenceBeans.java
{ "start": 1036, "end": 1221 }
class ____<T> extends JavaBeanWithGenericsA<String> { public T getPropertyB() { return null; } public void setPropertyB(T a) { } } static
JavaBeanWithGenericsAB
java
quarkusio__quarkus
independent-projects/resteasy-reactive/client/processor/src/main/java/org/jboss/resteasy/reactive/client/processor/beanparam/PathParamItem.java
{ "start": 72, "end": 634 }
class ____ extends Item { private final String pathParamName; private final String paramType; public PathParamItem(String fieldName, String pathParamName, String paramType, boolean encoded, ValueExtractor valueExtractor) { super(fieldName, ItemType.PATH_PARAM, encoded, valueExtractor); this.pathParamName = pathParamName; this.paramType = paramType; } public String getPathParamName() { return pathParamName; } public String getParamType() { return paramType; } }
PathParamItem
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/access/expression/AbstractSecurityExpressionHandlerTests.java
{ "start": 2587, "end": 2720 }
class ____ { @Bean Integer number10() { return 10; } @Bean Integer number20() { return 20; } } }
TestConfiguration
java
spring-projects__spring-boot
module/spring-boot-pulsar/src/main/java/org/springframework/boot/pulsar/autoconfigure/PulsarPropertiesMapper.java
{ "start": 2028, "end": 2210 }
class ____ to map {@link PulsarProperties} to various builder customizers. * * @author Chris Bono * @author Phillip Webb * @author Swamy Mavuri * @author Vedran Pavic */ final
used
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/ExecutionOptionsTestImpl.java
{ "start": 409, "end": 1120 }
class ____ implements ExecutionOptions, ExceptionHandler { /** * Singleton access for standard cases. Returns an empty map of configuration values, * true that namespaces should be managed and it always re-throws command exceptions */ public static final ExecutionOptionsTestImpl INSTANCE = new ExecutionOptionsTestImpl(); @Override public Map<String,Object> getConfigurationValues() { return Collections.emptyMap(); } @Override public boolean shouldManageNamespaces() { return true; } @Override public ExceptionHandler getExceptionHandler() { return this; } @Override public void handleException(CommandAcceptanceException exception) { throw exception; } }
ExecutionOptionsTestImpl
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/MiniDFSNNTopology.java
{ "start": 6650, "end": 7041 }
class ____ { private final String id; private final List<NNConf> nns = Lists.newArrayList(); public NSConf(String id) { this.id = id; } public NSConf addNN(NNConf nn) { this.nns.add(nn); return this; } public String getId() { return id; } public List<NNConf> getNNs() { return nns; } } public static
NSConf
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/disallowdotsonnames/Person.java
{ "start": 745, "end": 1301 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String firstName; private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
Person
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/MinFloatAggregatorFunctionTests.java
{ "start": 783, "end": 1612 }
class ____ extends AggregatorFunctionTestCase { @Override protected SourceOperator simpleInput(BlockFactory blockFactory, int size) { return new SequenceFloatBlockSourceOperator(blockFactory, LongStream.range(0, size).mapToObj(l -> ESTestCase.randomFloat())); } @Override protected AggregatorFunctionSupplier aggregatorFunction() { return new MinFloatAggregatorFunctionSupplier(); } @Override protected String expectedDescriptionOfAggregator() { return "min of floats"; } @Override protected void assertSimpleOutput(List<Page> input, Block result) { Float min = input.stream().flatMap(p -> allFloats(p.getBlock(0))).min(floatComparator()).get(); assertThat(((FloatBlock) result).getFloat(0), equalTo(min)); } }
MinFloatAggregatorFunctionTests
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/ExtraInfoUtil.java
{ "start": 1108, "end": 13296 }
class ____ { private static final String NORMAL_TOPIC = "0"; private static final String RETRY_TOPIC = "1"; private static final String RETRY_TOPIC_V2 = "2"; private static final String QUEUE_OFFSET = "qo"; public static String[] split(String extraInfo) { if (extraInfo == null) { throw new IllegalArgumentException("split extraInfo is null"); } return extraInfo.split(MessageConst.KEY_SEPARATOR); } public static Long getCkQueueOffset(String[] extraInfoStrs) { if (extraInfoStrs == null || extraInfoStrs.length < 1) { throw new IllegalArgumentException("getCkQueueOffset fail, extraInfoStrs length " + (extraInfoStrs == null ? 0 : extraInfoStrs.length)); } return Long.valueOf(extraInfoStrs[0]); } public static Long getPopTime(String[] extraInfoStrs) { if (extraInfoStrs == null || extraInfoStrs.length < 2) { throw new IllegalArgumentException("getPopTime fail, extraInfoStrs length " + (extraInfoStrs == null ? 0 : extraInfoStrs.length)); } return Long.valueOf(extraInfoStrs[1]); } public static Long getInvisibleTime(String[] extraInfoStrs) { if (extraInfoStrs == null || extraInfoStrs.length < 3) { throw new IllegalArgumentException("getInvisibleTime fail, extraInfoStrs length " + (extraInfoStrs == null ? 0 : extraInfoStrs.length)); } return Long.valueOf(extraInfoStrs[2]); } public static int getReviveQid(String[] extraInfoStrs) { if (extraInfoStrs == null || extraInfoStrs.length < 4) { throw new IllegalArgumentException("getReviveQid fail, extraInfoStrs length " + (extraInfoStrs == null ? 0 : extraInfoStrs.length)); } return Integer.parseInt(extraInfoStrs[3]); } public static String getRealTopic(String[] extraInfoStrs, String topic, String cid) { if (extraInfoStrs == null || extraInfoStrs.length < 5) { throw new IllegalArgumentException("getRealTopic fail, extraInfoStrs length " + (extraInfoStrs == null ? 0 : extraInfoStrs.length)); } if (RETRY_TOPIC.equals(extraInfoStrs[4])) { return KeyBuilder.buildPopRetryTopicV1(topic, cid); } else if (RETRY_TOPIC_V2.equals(extraInfoStrs[4])) { return KeyBuilder.buildPopRetryTopicV2(topic, cid); } else { return topic; } } public static String getRealTopic(String topic, String cid, String retry) { if (retry.equals(NORMAL_TOPIC)) { return topic; } else if (retry.equals(RETRY_TOPIC)) { return KeyBuilder.buildPopRetryTopicV1(topic, cid); } else if (retry.equals(RETRY_TOPIC_V2)) { return KeyBuilder.buildPopRetryTopicV2(topic, cid); } else { throw new IllegalArgumentException("getRetry fail, format is wrong"); } } public static String getRetry(String[] extraInfoStrs) { if (extraInfoStrs == null || extraInfoStrs.length < 5) { throw new IllegalArgumentException("getRetry fail, extraInfoStrs length " + (extraInfoStrs == null ? 0 : extraInfoStrs.length)); } return extraInfoStrs[4]; } public static String getBrokerName(String[] extraInfoStrs) { if (extraInfoStrs == null || extraInfoStrs.length < 6) { throw new IllegalArgumentException("getBrokerName fail, extraInfoStrs length " + (extraInfoStrs == null ? 0 : extraInfoStrs.length)); } return extraInfoStrs[5]; } public static int getQueueId(String[] extraInfoStrs) { if (extraInfoStrs == null || extraInfoStrs.length < 7) { throw new IllegalArgumentException("getQueueId fail, extraInfoStrs length " + (extraInfoStrs == null ? 0 : extraInfoStrs.length)); } return Integer.parseInt(extraInfoStrs[6]); } public static long getQueueOffset(String[] extraInfoStrs) { if (extraInfoStrs == null || extraInfoStrs.length < 8) { throw new IllegalArgumentException("getQueueOffset fail, extraInfoStrs length " + (extraInfoStrs == null ? 0 : extraInfoStrs.length)); } return Long.parseLong(extraInfoStrs[7]); } public static String buildExtraInfo(long ckQueueOffset, long popTime, long invisibleTime, int reviveQid, String topic, String brokerName, int queueId) { String t = getRetry(topic); return ckQueueOffset + MessageConst.KEY_SEPARATOR + popTime + MessageConst.KEY_SEPARATOR + invisibleTime + MessageConst.KEY_SEPARATOR + reviveQid + MessageConst.KEY_SEPARATOR + t + MessageConst.KEY_SEPARATOR + brokerName + MessageConst.KEY_SEPARATOR + queueId; } public static String buildExtraInfo(long ckQueueOffset, long popTime, long invisibleTime, int reviveQid, String topic, String brokerName, int queueId, long msgQueueOffset) { String t = getRetry(topic); return ckQueueOffset + MessageConst.KEY_SEPARATOR + popTime + MessageConst.KEY_SEPARATOR + invisibleTime + MessageConst.KEY_SEPARATOR + reviveQid + MessageConst.KEY_SEPARATOR + t + MessageConst.KEY_SEPARATOR + brokerName + MessageConst.KEY_SEPARATOR + queueId + MessageConst.KEY_SEPARATOR + msgQueueOffset; } public static void buildStartOffsetInfo(StringBuilder stringBuilder, String topic, int queueId, long startOffset) { if (stringBuilder == null) { stringBuilder = new StringBuilder(64); } if (stringBuilder.length() > 0) { stringBuilder.append(";"); } stringBuilder.append(getRetry(topic)) .append(MessageConst.KEY_SEPARATOR).append(queueId) .append(MessageConst.KEY_SEPARATOR).append(startOffset); } public static void buildQueueIdOrderCountInfo(StringBuilder stringBuilder, String topic, int queueId, int orderCount) { if (stringBuilder == null) { stringBuilder = new StringBuilder(64); } if (stringBuilder.length() > 0) { stringBuilder.append(";"); } stringBuilder.append(getRetry(topic)) .append(MessageConst.KEY_SEPARATOR).append(queueId) .append(MessageConst.KEY_SEPARATOR).append(orderCount); } public static void buildQueueOffsetOrderCountInfo(StringBuilder stringBuilder, String topic, long queueId, long queueOffset, int orderCount) { if (stringBuilder == null) { stringBuilder = new StringBuilder(64); } if (stringBuilder.length() > 0) { stringBuilder.append(";"); } stringBuilder.append(getRetry(topic)) .append(MessageConst.KEY_SEPARATOR).append(getQueueOffsetKeyValueKey(queueId, queueOffset)) .append(MessageConst.KEY_SEPARATOR).append(orderCount); } public static void buildMsgOffsetInfo(StringBuilder stringBuilder, String topic, int queueId, List<Long> msgOffsets) { if (stringBuilder == null) { stringBuilder = new StringBuilder(64); } if (stringBuilder.length() > 0) { stringBuilder.append(";"); } stringBuilder.append(getRetry(topic)) .append(MessageConst.KEY_SEPARATOR).append(queueId) .append(MessageConst.KEY_SEPARATOR); for (int i = 0; i < msgOffsets.size(); i++) { stringBuilder.append(msgOffsets.get(i)); if (i < msgOffsets.size() - 1) { stringBuilder.append(","); } } } public static Map<String, List<Long>> parseMsgOffsetInfo(String msgOffsetInfo) { if (msgOffsetInfo == null || msgOffsetInfo.length() == 0) { return null; } Map<String, List<Long>> msgOffsetMap = new HashMap<>(4); String[] array; if (msgOffsetInfo.indexOf(";") < 0) { array = new String[]{msgOffsetInfo}; } else { array = msgOffsetInfo.split(";"); } for (String one : array) { String[] split = one.split(MessageConst.KEY_SEPARATOR); if (split.length != 3) { throw new IllegalArgumentException("parse msgOffsetMap error, " + msgOffsetMap); } String key = split[0] + "@" + split[1]; if (msgOffsetMap.containsKey(key)) { throw new IllegalArgumentException("parse msgOffsetMap error, duplicate, " + msgOffsetMap); } msgOffsetMap.put(key, new ArrayList<>(8)); String[] msgOffsets = split[2].split(","); for (String msgOffset : msgOffsets) { msgOffsetMap.get(key).add(Long.valueOf(msgOffset)); } } return msgOffsetMap; } public static Map<String, Long> parseStartOffsetInfo(String startOffsetInfo) { if (startOffsetInfo == null || startOffsetInfo.length() == 0) { return null; } Map<String, Long> startOffsetMap = new HashMap<>(4); String[] array; if (startOffsetInfo.indexOf(";") < 0) { array = new String[]{startOffsetInfo}; } else { array = startOffsetInfo.split(";"); } for (String one : array) { String[] split = one.split(MessageConst.KEY_SEPARATOR); if (split.length != 3) { throw new IllegalArgumentException("parse startOffsetInfo error, " + startOffsetInfo); } String key = split[0] + "@" + split[1]; if (startOffsetMap.containsKey(key)) { throw new IllegalArgumentException("parse startOffsetInfo error, duplicate, " + startOffsetInfo); } startOffsetMap.put(key, Long.valueOf(split[2])); } return startOffsetMap; } public static Map<String, Integer> parseOrderCountInfo(String orderCountInfo) { if (orderCountInfo == null || orderCountInfo.length() == 0) { return null; } Map<String, Integer> startOffsetMap = new HashMap<>(4); String[] array; if (orderCountInfo.indexOf(";") < 0) { array = new String[]{orderCountInfo}; } else { array = orderCountInfo.split(";"); } for (String one : array) { String[] split = one.split(MessageConst.KEY_SEPARATOR); if (split.length != 3) { throw new IllegalArgumentException("parse orderCountInfo error, " + orderCountInfo); } String key = split[0] + "@" + split[1]; if (startOffsetMap.containsKey(key)) { throw new IllegalArgumentException("parse orderCountInfo error, duplicate, " + orderCountInfo); } startOffsetMap.put(key, Integer.valueOf(split[2])); } return startOffsetMap; } public static String getStartOffsetInfoMapKey(String topic, long key) { return getRetry(topic) + "@" + key; } public static String getStartOffsetInfoMapKey(String topic, String popCk, long key) { return getRetry(topic, popCk) + "@" + key; } public static String getQueueOffsetKeyValueKey(long queueId, long queueOffset) { return QUEUE_OFFSET + queueId + "%" + queueOffset; } public static String getQueueOffsetMapKey(String topic, long queueId, long queueOffset) { return getRetry(topic) + "@" + getQueueOffsetKeyValueKey(queueId, queueOffset); } public static boolean isOrder(String[] extraInfo) { return ExtraInfoUtil.getReviveQid(extraInfo) == KeyBuilder.POP_ORDER_REVIVE_QUEUE; } private static String getRetry(String topic) { String t = NORMAL_TOPIC; if (KeyBuilder.isPopRetryTopicV2(topic)) { t = RETRY_TOPIC_V2; } else if (topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) { t = RETRY_TOPIC; } return t; } private static String getRetry(String topic, String popCk) { if (popCk != null) { return getRetry(split(popCk)); } return getRetry(topic); } }
ExtraInfoUtil
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/bigintegers/BigIntegers_assertGreaterThan_Test.java
{ "start": 1496, "end": 4269 }
class ____ extends BigIntegersBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertGreaterThan(someInfo(), null, ONE)) .withMessage(actualIsNull()); } @Test void should_pass_if_actual_is_greater_than_other() { numbers.assertGreaterThan(someInfo(), TEN, ONE); } @Test void should_fail_if_actual_is_equal_to_other() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> numbers.assertGreaterThan(info, TEN, TEN)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeGreater(TEN, TEN)); } @Test void should_fail_if_actual_is_equal_to_other_by_comparison() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> numbers.assertGreaterThan(info, TEN, new BigInteger("10"))); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeGreater(TEN, new BigInteger("10"))); } @Test void should_fail_if_actual_is_less_than_other() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> numbers.assertGreaterThan(info, ONE, TEN)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeGreater(ONE, TEN)); } // ------------------------------------------------------------------------------------------------------------------ // tests using a custom comparison strategy // ------------------------------------------------------------------------------------------------------------------ @Test void should_pass_if_actual_is_greater_than_other_according_to_custom_comparison_strategy() { numbersWithAbsValueComparisonStrategy.assertGreaterThan(someInfo(), TEN.negate(), ONE); } @Test void should_fail_if_actual_is_equal_to_other_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> numbersWithAbsValueComparisonStrategy.assertGreaterThan(info, TEN.negate(), TEN)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeGreater(TEN.negate(), TEN, absValueComparisonStrategy)); } @Test void should_fail_if_actual_is_less_than_other_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> numbersWithAbsValueComparisonStrategy.assertGreaterThan(info, ONE, TEN.negate())); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeGreater(ONE, TEN.negate(), absValueComparisonStrategy)); } }
BigIntegers_assertGreaterThan_Test
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java
{ "start": 17093, "end": 17647 }
class ____ implements ConstraintValidator<NotXList, List<String>> { @Override public boolean isValid(List<String> list, ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); boolean valid = true; for (int i = 0; i < list.size(); i++) { if ("X".equals(list.get(i))) { context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()) .addBeanNode().inIterable().atIndex(i).addConstraintViolation(); valid = false; } } return valid; } } }
NotXListValidator
java
apache__camel
test-infra/camel-test-infra-nats/src/test/java/org/apache/camel/test/infra/nats/services/NatsLocalContainerTLSAuthService.java
{ "start": 1022, "end": 1917 }
class ____ extends NatsLocalContainerService implements NatsService { /*Certificates used for tests with TLS authentication come from: *https://github.com/nats-io/jnats/tree/master/src/test/resources */ protected GenericContainer initContainer(String imageName, String containerName) { GenericContainer container = super.initContainer(imageName, containerName); container .waitingFor(Wait.forLogMessage(".*Server.*is.*ready.*", 1)) .withClasspathResourceMapping("org/apache/camel/test/infra/nats/services", "/nats", BindMode.READ_ONLY) .withCommand("--tls", "--tlscert=/nats/server.pem", "--tlskey=/nats/key.pem", "--tlsverify", "--tlscacert=/nats/ca.pem"); return container; } }
NatsLocalContainerTLSAuthService
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/isolation/SynchronizationTest.java
{ "start": 11579, "end": 11832 }
class ____ parent"); // STEP 3: Resume T1 and have it enter the PluginClassLoader dclBreakpoint.testAwait(); // T1 enters PluginClassLoader::loadClass dumpThreads("step 3, T1 entered PluginClassLoader and is/was loading
from
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3331ModulePathNormalizationTest.java
{ "start": 1074, "end": 2853 }
class ____ extends AbstractMavenIntegrationTestCase { @Test public void testitMNG3331a() throws Exception { // testMNG3331ModuleWithSpaces File testDir = extractResources("/mng-3331/with-spaces"); Verifier verifier; verifier = newVerifier(testDir.getAbsolutePath()); verifier.addCliArgument("initialize"); verifier.execute(); /* * This is the simplest way to check a build * succeeded. It is also the simplest way to create * an IT test: make the build pass when the test * should pass, and make the build fail when the * test should fail. There are other methods * supported by the verifier. They can be seen here: * http://maven.apache.org/shared/maven-verifier/apidocs/index.html */ verifier.verifyErrorFreeLog(); } @Test public void testitMNG3331b() throws Exception { // testMNG3331ModuleWithRelativeParentDirRef File testDir = extractResources("/mng-3331/with-relative-parentDir-ref"); Verifier verifier; verifier = newVerifier(new File(testDir, "parent").getAbsolutePath()); verifier.addCliArgument("initialize"); verifier.execute(); /* * This is the simplest way to check a build * succeeded. It is also the simplest way to create * an IT test: make the build pass when the test * should pass, and make the build fail when the * test should fail. There are other methods * supported by the verifier. They can be seen here: * http://maven.apache.org/shared/maven-verifier/apidocs/index.html */ verifier.verifyErrorFreeLog(); } }
MavenITmng3331ModulePathNormalizationTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Server.java
{ "start": 118129, "end": 118286 }
class ____ connection * @return the serviceClass */ public int getServiceClass() { return serviceClass; } /** * Set service
for
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/RoleMappingMetadataTests.java
{ "start": 941, "end": 2815 }
class ____ extends AbstractWireSerializingTestCase<RoleMappingMetadata> { @Override protected RoleMappingMetadata createTestInstance() { return new RoleMappingMetadata(randomSet(0, 3, () -> randomRoleMapping(true))); } @Override protected RoleMappingMetadata mutateInstance(RoleMappingMetadata instance) throws IOException { Set<ExpressionRoleMapping> mutatedRoleMappings = new HashSet<>(instance.getRoleMappings()); boolean mutated = false; if (mutatedRoleMappings.isEmpty() == false && randomBoolean()) { mutated = true; mutatedRoleMappings.remove(randomFrom(mutatedRoleMappings)); } if (randomBoolean() || mutated == false) { mutatedRoleMappings.add(randomRoleMapping(true)); } return new RoleMappingMetadata(mutatedRoleMappings); } @Override protected Writeable.Reader<RoleMappingMetadata> instanceReader() { return RoleMappingMetadata::new; } @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { return new NamedWriteableRegistry(new XPackClientPlugin().getNamedWriteables()); } public void testEquals() { Set<ExpressionRoleMapping> roleMappings1 = randomSet(0, 3, () -> randomRoleMapping(true)); Set<ExpressionRoleMapping> roleMappings2 = randomSet(0, 3, () -> randomRoleMapping(true)); assumeFalse("take 2 different role mappings", roleMappings1.equals(roleMappings2)); assertThat(new RoleMappingMetadata(roleMappings1).equals(new RoleMappingMetadata(roleMappings2)), is(false)); assertThat(new RoleMappingMetadata(roleMappings1).equals(new RoleMappingMetadata(roleMappings1)), is(true)); assertThat(new RoleMappingMetadata(roleMappings2).equals(new RoleMappingMetadata(roleMappings2)), is(true)); } }
RoleMappingMetadataTests
java
apache__flink
flink-core/src/main/java/org/apache/flink/util/TaskManagerExceptionUtils.java
{ "start": 3136, "end": 3992 }
class ____ leak in user code or some of its dependencies " + "which has to be investigated and fixed. The task executor has to be shutdown...", TaskManagerOptions.JVM_METASPACE.key()); private TaskManagerExceptionUtils() {} /** * Tries to enrich the passed exception or its causes with additional information. * * <p>This method improves error messages for direct and metaspace {@link OutOfMemoryError}. It * adds descriptions about possible causes and ways of resolution. * * @param root The Throwable of which the cause tree shall be traversed. */ public static void tryEnrichTaskManagerError(@Nullable Throwable root) { tryEnrichOutOfMemoryError( root, TM_METASPACE_OOM_ERROR_MESSAGE, TM_DIRECT_OOM_ERROR_MESSAGE, null); } }
loading
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java
{ "start": 99008, "end": 100949 }
class ____ implements InFlightMetadataCollector.DelayedPropertyReferenceHandler { public final String referencedEntityName; public final String referencedPropertyName; public final boolean isUnique; private final String sourceElementSynopsis; public final Origin propertyRefOrigin; public DelayedPropertyReferenceHandlerImpl( String referencedEntityName, String referencedPropertyName, boolean isUnique, String sourceElementSynopsis, Origin propertyRefOrigin) { this.referencedEntityName = referencedEntityName; this.referencedPropertyName = referencedPropertyName; this.isUnique = isUnique; this.sourceElementSynopsis = sourceElementSynopsis; this.propertyRefOrigin = propertyRefOrigin; } public void process(InFlightMetadataCollector metadataCollector) { BOOT_LOGGER.tracef( "Performing delayed property-ref handling [%s, %s, %s]", referencedEntityName, referencedPropertyName, sourceElementSynopsis ); final var entityBinding = metadataCollector.getEntityBinding( referencedEntityName ); if ( entityBinding == null ) { throw new MappingException( String.format( Locale.ENGLISH, "property-ref [%s] referenced an unmapped entity [%s]", sourceElementSynopsis, referencedEntityName ), propertyRefOrigin ); } final var propertyBinding = entityBinding.getReferencedProperty( referencedPropertyName ); if ( propertyBinding == null ) { throw new MappingException( String.format( Locale.ENGLISH, "property-ref [%s] referenced an unknown entity property [%s#%s]", sourceElementSynopsis, referencedEntityName, referencedPropertyName ), propertyRefOrigin ); } if ( isUnique ) { ( (SimpleValue) propertyBinding.getValue() ).setAlternateUniqueKey( true ); } } } private abstract
DelayedPropertyReferenceHandlerImpl
java
spring-projects__spring-security
webauthn/src/main/java/org/springframework/security/web/webauthn/api/PublicKeyCredentialUserEntity.java
{ "start": 1361, "end": 2262 }
interface ____ extends Serializable { /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialentity-name">name</a> * property is a human-palatable identifier for a user account. * @return the name */ String getName(); /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialuserentity-id">id</a> is * the user handle of the user account. A user handle is an opaque byte sequence with * a maximum size of 64 bytes, and is not meant to be displayed to the user. * @return the user handle of the user account */ Bytes getId(); /** * The <a href= * "https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialuserentity-displayname">displayName</a> * is a human-palatable name for the user account, intended only for display. * @return the display name */ @Nullable String getDisplayName(); }
PublicKeyCredentialUserEntity
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/concurrent/locks/LockingVisitors.java
{ "start": 8028, "end": 19102 }
interface ____ * Java 8. */ private final L lock; /** * The guarded object. */ private final O object; /** * Supplies the read lock, usually from the lock object. */ private final Supplier<Lock> readLockSupplier; /** * Supplies the write lock, usually from the lock object. */ private final Supplier<Lock> writeLockSupplier; /** * Constructs an instance from a builder. * * @param builder The builder. */ private LockVisitor(final LVBuilder<O, L, ?> builder) { this.object = Objects.requireNonNull(builder.object, "object"); this.lock = Objects.requireNonNull(builder.lock, "lock"); this.readLockSupplier = Objects.requireNonNull(builder.readLockSupplier, "readLockSupplier"); this.writeLockSupplier = Objects.requireNonNull(builder.writeLockSupplier, "writeLockSupplier"); } /** * Constructs an instance. * * @param object The object to guard. * @param lock The locking object. * @param readLockSupplier Supplies the read lock, usually from the lock object. * @param writeLockSupplier Supplies the write lock, usually from the lock object. */ protected LockVisitor(final O object, final L lock, final Supplier<Lock> readLockSupplier, final Supplier<Lock> writeLockSupplier) { this.object = Objects.requireNonNull(object, "object"); this.lock = Objects.requireNonNull(lock, "lock"); this.readLockSupplier = Objects.requireNonNull(readLockSupplier, "readLockSupplier"); this.writeLockSupplier = Objects.requireNonNull(writeLockSupplier, "writeLockSupplier"); } /** * Provides read (shared, non-exclusive) access to The object to protect. More precisely, what the method * will do (in the given order): * * <ol> * <li>Obtain a read (shared) lock on The object to protect. The current thread may block, until such a * lock is granted.</li> * <li>Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.</li> * <li>Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the * lock will be released anyways.</li> * </ol> * * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the * consumers parameter. * @see #acceptWriteLocked(FailableConsumer) * @see #applyReadLocked(FailableFunction) */ public void acceptReadLocked(final FailableConsumer<O, ?> consumer) { lockAcceptUnlock(readLockSupplier, consumer); } /** * Provides write (exclusive) access to The object to protect. More precisely, what the method will do (in * the given order): * * <ol> * <li>Obtain a write (shared) lock on The object to protect. The current thread may block, until such a * lock is granted.</li> * <li>Invokes the given {@link FailableConsumer consumer}, passing the locked object as the parameter.</li> * <li>Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the * lock will be released anyways.</li> * </ol> * * @param consumer The consumer, which is being invoked to use the hidden object, which will be passed as the * consumers parameter. * @see #acceptReadLocked(FailableConsumer) * @see #applyWriteLocked(FailableFunction) */ public void acceptWriteLocked(final FailableConsumer<O, ?> consumer) { lockAcceptUnlock(writeLockSupplier, consumer); } /** * Provides read (shared, non-exclusive) access to The object to protect for the purpose of computing a * result object. More precisely, what the method will do (in the given order): * * <ol> * <li>Obtain a read (shared) lock on The object to protect. The current thread may block, until such a * lock is granted.</li> * <li>Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, * receiving the functions result.</li> * <li>Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the * lock will be released anyways.</li> * <li>Return the result object, that has been received from the functions invocation.</li> * </ol> * <p> * <em>Example:</em> Consider that the hidden object is a list, and we wish to know the current size of the * list. This might be achieved with the following: * </p> * <pre>{@code * private Lock<List<Object>> listLock; * * public int getCurrentListSize() { * final Integer sizeInteger = listLock.applyReadLocked(list -> Integer.valueOf(list.size)); * return sizeInteger.intValue(); * } * } * </pre> * * @param <T> The result type (both the functions, and this method's.) * @param function The function, which is being invoked to compute the result. The function will receive the * hidden object. * @return The result object, which has been returned by the functions invocation. * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend * access to the hidden object beyond this methods lifetime and will therefore be prevented. * @see #acceptReadLocked(FailableConsumer) * @see #applyWriteLocked(FailableFunction) */ public <T> T applyReadLocked(final FailableFunction<O, T, ?> function) { return lockApplyUnlock(readLockSupplier, function); } /** * Provides write (exclusive) access to The object to protect for the purpose of computing a result object. * More precisely, what the method will do (in the given order): * * <ol> * <li>Obtain a read (shared) lock on The object to protect. The current thread may block, until such a * lock is granted.</li> * <li>Invokes the given {@link FailableFunction function}, passing the locked object as the parameter, * receiving the functions result.</li> * <li>Release the lock, as soon as the consumers invocation is done. If the invocation results in an error, the * lock will be released anyways.</li> * <li>Return the result object, that has been received from the functions invocation.</li> * </ol> * * @param <T> The result type (both the functions, and this method's.) * @param function The function, which is being invoked to compute the result. The function will receive the * hidden object. * @return The result object, which has been returned by the functions invocation. * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend * access to the hidden object beyond this methods lifetime and will therefore be prevented. * @see #acceptReadLocked(FailableConsumer) * @see #applyWriteLocked(FailableFunction) */ public <T> T applyWriteLocked(final FailableFunction<O, T, ?> function) { return lockApplyUnlock(writeLockSupplier, function); } /** * Gets the lock. * * @return the lock. */ public L getLock() { return lock; } /** * Gets the guarded object. * * @return the object. */ public O getObject() { return object; } /** * This method provides the default implementation for {@link #acceptReadLocked(FailableConsumer)}, and * {@link #acceptWriteLocked(FailableConsumer)}. * * @param lockSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used * internally.) * @param consumer The consumer, which is to be given access to The object to protect, which will be passed * as a parameter. * @see #acceptReadLocked(FailableConsumer) * @see #acceptWriteLocked(FailableConsumer) */ protected void lockAcceptUnlock(final Supplier<Lock> lockSupplier, final FailableConsumer<O, ?> consumer) { final Lock lock = Objects.requireNonNull(Suppliers.get(lockSupplier), "lock"); lock.lock(); try { Failable.accept(consumer, object); } finally { lock.unlock(); } } /** * This method provides the actual implementation for {@link #applyReadLocked(FailableFunction)}, and * {@link #applyWriteLocked(FailableFunction)}. * * @param <T> The result type (both the functions, and this method's.) * @param lockSupplier A supplier for the lock. (This provides, in fact, a long, because a {@link StampedLock} is used * internally.) * @param function The function, which is being invoked to compute the result object. This function will receive * The object to protect as a parameter. * @return The result object, which has been returned by the functions invocation. * @throws IllegalStateException The result object would be, in fact, the hidden object. This would extend * access to the hidden object beyond this methods lifetime and will therefore be prevented. * @see #applyReadLocked(FailableFunction) * @see #applyWriteLocked(FailableFunction) */ protected <T> T lockApplyUnlock(final Supplier<Lock> lockSupplier, final FailableFunction<O, T, ?> function) { final Lock lock = Objects.requireNonNull(Suppliers.get(lockSupplier), "lock"); lock.lock(); try { return Failable.apply(function, object); } finally { lock.unlock(); } } } /** * Wraps a {@link ReadWriteLock} and object to protect. To access the object, use the methods {@link #acceptReadLocked(FailableConsumer)}, * {@link #acceptWriteLocked(FailableConsumer)}, {@link #applyReadLocked(FailableFunction)}, and {@link #applyWriteLocked(FailableFunction)}. The visitor * holds the lock while the consumer or function is called. * * @param <O> The type of the object to protect. * @see LockingVisitors#create(Object, ReadWriteLock) */ public static
in
java
google__dagger
javatests/dagger/android/support/functional/AllControllersAreDirectChildrenOfApplication.java
{ "start": 5710, "end": 5822 }
interface ____ extends AndroidInjector<TestParentFragment> { @Module abstract
ParentFragmentSubcomponent
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/source/OnEventTestWatermarkGenerator.java
{ "start": 1055, "end": 1366 }
class ____<T> implements WatermarkGenerator<T> { @Override public void onEvent(T event, long eventTimestamp, WatermarkOutput output) { output.emitWatermark(new Watermark(eventTimestamp)); } @Override public void onPeriodicEmit(WatermarkOutput output) {} }
OnEventTestWatermarkGenerator
java
quarkusio__quarkus
extensions/kafka-client/runtime-dev/src/main/java/io/quarkus/kafka/client/runtime/dev/ui/model/response/KafkaNode.java
{ "start": 71, "end": 576 }
class ____ { private String host; private int port; private String id; public KafkaNode() { } public KafkaNode(String host, int port, String id) { this.host = host; this.port = port; this.id = id; } public String getHost() { return host; } public int getPort() { return port; } public String getId() { return id; } public String asFullNodeName() { return host + ":" + port; } }
KafkaNode
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleServletPostProcessor.java
{ "start": 2891, "end": 4920 }
class ____ implements DestructionAwareBeanPostProcessor, ServletContextAware, ServletConfigAware { private boolean useSharedServletConfig = true; private @Nullable ServletContext servletContext; private @Nullable ServletConfig servletConfig; /** * Set whether to use the shared ServletConfig object passed in * through {@code setServletConfig}, if available. * <p>Default is "true". Turn this setting to "false" to pass in * a mock ServletConfig object with the bean name as servlet name, * holding the current ServletContext. * @see #setServletConfig */ public void setUseSharedServletConfig(boolean useSharedServletConfig) { this.useSharedServletConfig = useSharedServletConfig; } @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void setServletConfig(ServletConfig servletConfig) { this.servletConfig = servletConfig; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof Servlet servlet) { ServletConfig config = this.servletConfig; if (config == null || !this.useSharedServletConfig) { config = new DelegatingServletConfig(beanName, this.servletContext); } try { servlet.init(config); } catch (ServletException ex) { throw new BeanInitializationException("Servlet.init threw exception", ex); } } return bean; } @Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { if (bean instanceof Servlet servlet) { servlet.destroy(); } } @Override public boolean requiresDestruction(Object bean) { return (bean instanceof Servlet); } /** * Internal implementation of the {@link ServletConfig} interface, * to be passed to the wrapped servlet. */ private static
SimpleServletPostProcessor
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ext/javatime/ser/DurationSerializer.java
{ "start": 1777, "end": 7247 }
class ____ extends JSR310FormattedSerializerBase<Duration> { public static final DurationSerializer INSTANCE = new DurationSerializer(); /** * When defined (not {@code null}) duration values will be converted into integers * with the unit configured for the converter. * Only available when {@link SerializationFeature#WRITE_DURATIONS_AS_TIMESTAMPS} is enabled * and {@link SerializationFeature#WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS} is not enabled * since the duration converters do not support fractions * @since 2.12 */ private DurationUnitConverter _durationUnitConverter; protected DurationSerializer() { // was private before 2.12 super(Duration.class); } protected DurationSerializer(DurationSerializer base, DateTimeFormatter dtf, Boolean useTimestamp) { super(base, dtf, useTimestamp, null, null); } protected DurationSerializer(DurationSerializer base, DateTimeFormatter dtf, Boolean useTimestamp, Boolean useNanoseconds) { super(base, dtf, useTimestamp, useNanoseconds, null); } protected DurationSerializer(DurationSerializer base, DurationUnitConverter converter) { super(base, base._formatter, base._useTimestamp, base._useNanoseconds, base._shape); _durationUnitConverter = converter; } @Override protected DurationSerializer withFormat(DateTimeFormatter dtf, Boolean useTimestamp, JsonFormat.Shape shape) { return new DurationSerializer(this, dtf, useTimestamp); } protected DurationSerializer withConverter(DurationUnitConverter converter) { return new DurationSerializer(this, converter); } // @since 2.10 @Override protected DateTimeFeature getTimestampsFeature() { return DateTimeFeature.WRITE_DURATIONS_AS_TIMESTAMPS; } @Override public ValueSerializer<?> createContextual(SerializationContext ctxt, BeanProperty property) { DurationSerializer ser = (DurationSerializer) super.createContextual(ctxt, property); JsonFormat.Value format = findFormatOverrides(ctxt, property, handledType()); if (format != null && format.hasPattern()) { final String pattern = format.getPattern(); DurationUnitConverter p = DurationUnitConverter.from(pattern); if (p == null) { ctxt.reportBadDefinition(handledType(), String.format( "Bad 'pattern' definition (\"%s\") for `Duration`: expected one of [%s]", pattern, DurationUnitConverter.descForAllowed())); } ser = ser.withConverter(p); } return ser; } @Override public void serialize(Duration duration, JsonGenerator generator, SerializationContext ctxt) throws JacksonException { if (useTimestamp(ctxt)) { // 03-Aug-2022, tatu: As per [modules-java8#224] need to consider // Pattern first, and only then nano-seconds/millis difference if (_durationUnitConverter != null) { generator.writeNumber(_durationUnitConverter.convert(duration)); } else if (useNanoseconds(ctxt)) { generator.writeNumber(_toNanos(duration)); } else { generator.writeNumber(duration.toMillis()); } } else { generator.writeString(duration.toString()); } } // 20-Oct-2020, tatu: [modules-java8#165] Need to take care of // negative values too, and without work-around values // returned are wonky wrt conversions private BigDecimal _toNanos(Duration duration) { BigDecimal bd; if (duration.isNegative()) { duration = duration.abs(); bd = DecimalUtils.toBigDecimal(duration.getSeconds(), duration.getNano()) .negate(); } else { bd = DecimalUtils.toBigDecimal(duration.getSeconds(), duration.getNano()); } return bd; } @Override protected void _acceptTimestampVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) { JsonIntegerFormatVisitor v2 = visitor.expectIntegerFormat(typeHint); if (v2 != null) { v2.numberType(JsonParser.NumberType.LONG); SerializationContext ctxt = visitor.getContext(); if ((ctxt != null) && useNanoseconds(ctxt)) { // big number, no more specific qualifier to use... } else { // otherwise good old Unix timestamp, in milliseconds v2.format(JsonValueFormat.UTC_MILLISEC); } } } @Override protected JsonToken serializationShape(SerializationContext ctxt) { if (useTimestamp(ctxt)) { if (useNanoseconds(ctxt)) { return JsonToken.VALUE_NUMBER_FLOAT; } return JsonToken.VALUE_NUMBER_INT; } return JsonToken.VALUE_STRING; } @Override protected JSR310FormattedSerializerBase<?> withFeatures(Boolean writeZoneId, Boolean writeNanoseconds) { return new DurationSerializer(this, _formatter, _useTimestamp, writeNanoseconds); } @Override protected DateTimeFormatter _useDateTimeFormatter(SerializationContext ctxt, JsonFormat.Value format) { return null; } }
DurationSerializer
java
spring-projects__spring-boot
module/spring-boot-liquibase/src/main/java/org/springframework/boot/liquibase/autoconfigure/LiquibaseProperties.java
{ "start": 9051, "end": 9411 }
enum ____ { /** * Log the summary. */ LOG, /** * Output the summary to the console. */ CONSOLE, /** * Log the summary and output it to the console. */ ALL } /** * Enumeration of types of UIService. Values are the same as those on * {@link UIServiceEnum}. To maximize backwards compatibility, the Liquibase
ShowSummaryOutput
java
junit-team__junit5
platform-tooling-support-tests/projects/vintage/src/test/java/DefaultPackageTest.java
{ "start": 481, "end": 564 }
class ____ extends VintageTest { void packagePrivateMethod() { } }
DefaultPackageTest
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.java
{ "start": 28105, "end": 30434 }
class ____ { /** * Specifies that a new session should be created, but the session attributes from * the original {@link HttpSession} should not be retained. * @return the {@link SessionManagementConfigurer} for further customizations */ public SessionManagementConfigurer<H> newSession() { SessionFixationProtectionStrategy sessionFixationProtectionStrategy = new SessionFixationProtectionStrategy(); sessionFixationProtectionStrategy.setMigrateSessionAttributes(false); setSessionFixationAuthenticationStrategy(sessionFixationProtectionStrategy); return SessionManagementConfigurer.this; } /** * Specifies that a new session should be created and the session attributes from * the original {@link HttpSession} should be retained. * @return the {@link SessionManagementConfigurer} for further customizations */ public SessionManagementConfigurer<H> migrateSession() { setSessionFixationAuthenticationStrategy(new SessionFixationProtectionStrategy()); return SessionManagementConfigurer.this; } /** * Specifies that the Servlet container-provided session fixation protection * should be used. When a session authenticates, the Servlet method * {@code HttpServletRequest#changeSessionId()} is called to change the session ID * and retain all session attributes. * @return the {@link SessionManagementConfigurer} for further customizations */ public SessionManagementConfigurer<H> changeSessionId() { setSessionFixationAuthenticationStrategy(new ChangeSessionIdAuthenticationStrategy()); return SessionManagementConfigurer.this; } /** * Specifies that no session fixation protection should be enabled. This may be * useful when utilizing other mechanisms for protecting against session fixation. * For example, if application container session fixation protection is already in * use. Otherwise, this option is not recommended. * @return the {@link SessionManagementConfigurer} for further customizations */ public SessionManagementConfigurer<H> none() { setSessionFixationAuthenticationStrategy(new NullAuthenticatedSessionStrategy()); return SessionManagementConfigurer.this; } } /** * Allows configuring controlling of multiple sessions. * * @author Rob Winch */ public final
SessionFixationConfigurer
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/bean/BeanInfoTest.java
{ "start": 7593, "end": 7665 }
interface ____ { String method(); } static
IMethodInterface
java
spring-projects__spring-boot
module/spring-boot-liquibase/src/main/java/org/springframework/boot/liquibase/actuate/endpoint/LiquibaseEndpoint.java
{ "start": 7811, "end": 8055 }
class ____ { private final Set<String> contexts; public ContextExpressionDescriptor(Set<String> contexts) { this.contexts = contexts; } public Set<String> getContexts() { return this.contexts; } } }
ContextExpressionDescriptor
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/JpqlQueryBuilderUnitTests.java
{ "start": 11559, "end": 11671 }
class ____ { @Id Long id; String name; String productType; } @jakarta.persistence.Entity static
Product
java
apache__camel
components/camel-cassandraql/src/test/java/org/apache/camel/component/cassandra/integration/CassandraComponentProducerUnpreparedIT.java
{ "start": 1644, "end": 4923 }
class ____ extends BaseCassandra { static final String CQL = "insert into camel_user(login, first_name, last_name) values (?, ?, ?)"; static final String NO_PARAMETER_CQL = "select login, first_name, last_name from camel_user"; @Produce("direct:input") ProducerTemplate producerTemplate; @Produce("direct:inputNoParameter") ProducerTemplate noParameterProducerTemplate; @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:input") .toF("cql://%s/%s?cql=%s&prepareStatements=false", getUrl(), KEYSPACE_NAME, CQL); from("direct:inputNoParameter") .toF("cql://%s/%s?cql=%s&prepareStatements=false", getUrl(), KEYSPACE_NAME, NO_PARAMETER_CQL); } }; } @Test public void testRequestUriCql() { producerTemplate.requestBody(Arrays.asList("w_jiang", "Willem", "Jiang")); ResultSet resultSet = getSession() .execute("select login, first_name, last_name from camel_user where login = ?", "w_jiang"); Row row = resultSet.one(); assertNotNull(row); assertEquals("Willem", row.getString("first_name")); assertEquals("Jiang", row.getString("last_name")); } @Test public void testRequestNoParameterNull() { Object response = noParameterProducerTemplate.requestBody(null); assertNotNull(response); assertIsInstanceOf(List.class, response); } @Test public void testRequestNoParameterEmpty() { Object response = noParameterProducerTemplate.requestBody(null); assertNotNull(response); assertIsInstanceOf(List.class, response); } @Test public void testRequestMessageCql() { producerTemplate.requestBodyAndHeader(new Object[] { "Claus 2", "Ibsen 2", "c_ibsen" }, CassandraConstants.CQL_QUERY, "update camel_user set first_name=?, last_name=? where login=?"); ResultSet resultSet = getSession() .execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen"); Row row = resultSet.one(); assertNotNull(row); assertEquals("Claus 2", row.getString("first_name")); assertEquals("Ibsen 2", row.getString("last_name")); } /** * Test with incoming message containing a header with RegularStatement. */ @Test public void testRequestMessageStatement() { Update update = QueryBuilder.update("camel_user") .setColumn("first_name", literal("Claus 2")) .setColumn("last_name", literal("Ibsen 2")) .whereColumn("login").isEqualTo(literal("c_ibsen")); producerTemplate.requestBodyAndHeader(null, CassandraConstants.CQL_QUERY, update.build()); ResultSet resultSet = getSession() .execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen"); Row row = resultSet.one(); assertNotNull(row); assertEquals("Claus 2", row.getString("first_name")); assertEquals("Ibsen 2", row.getString("last_name")); } }
CassandraComponentProducerUnpreparedIT
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/retryReasonCategories/ClientErrorRetryReason.java
{ "start": 1075, "end": 1528 }
class ____ extends RetryReasonCategory { @Override Boolean canCapture(final Exception ex, final Integer statusCode, final String serverErrorMessage) { if (statusCode == null || statusCode / HTTP_STATUS_CATEGORY_QUOTIENT != 4) { return false; } return true; } @Override String getAbbreviation(final Integer statusCode, final String serverErrorMessage) { return statusCode + ""; } }
ClientErrorRetryReason
java
hibernate__hibernate-orm
hibernate-micrometer/src/main/java/org/hibernate/stat/HibernateQueryMetrics.java
{ "start": 1129, "end": 3264 }
class ____ implements MeterBinder { private static final String SESSION_FACTORY_TAG_NAME = "entityManagerFactory"; private final Iterable<Tag> tags; private final SessionFactory sessionFactory; /** * Create {@code HibernateQueryMetrics} and bind to the specified meter registry. * * @param registry meter registry to use * @param sessionFactory session factory to use * @param sessionFactoryName session factory name as a tag value * @param tags additional tags */ public static void monitor( MeterRegistry registry, SessionFactory sessionFactory, String sessionFactoryName, String... tags) { monitor( registry, sessionFactory, sessionFactoryName, Tags.of( tags ) ); } /** * Create {@code HibernateQueryMetrics} and bind to the specified meter registry. * * @param registry meter registry to use * @param sessionFactory session factory to use * @param sessionFactoryName session factory name as a tag value * @param tags additional tags */ public static void monitor( MeterRegistry registry, SessionFactory sessionFactory, String sessionFactoryName, Iterable<Tag> tags) { new HibernateQueryMetrics( sessionFactory, sessionFactoryName, tags ).bindTo( registry ); } /** * Create a {@code HibernateQueryMetrics}. * * @param sessionFactory session factory to use * @param sessionFactoryName session factory name as a tag value * @param tags additional tags */ public HibernateQueryMetrics(SessionFactory sessionFactory, String sessionFactoryName, Iterable<Tag> tags) { this.tags = Tags.concat( tags, SESSION_FACTORY_TAG_NAME, sessionFactoryName ); this.sessionFactory = sessionFactory; } @Override public void bindTo(MeterRegistry meterRegistry) { if ( sessionFactory instanceof SessionFactoryImplementor ) { EventListenerRegistry eventListenerRegistry = ( (SessionFactoryImplementor) sessionFactory ).getEventEngine().getListenerRegistry(); MetricsEventHandler metricsEventHandler = new MetricsEventHandler( meterRegistry ); eventListenerRegistry.appendListeners( EventType.POST_LOAD, metricsEventHandler ); } }
HibernateQueryMetrics
java
resilience4j__resilience4j
resilience4j-spring-boot2/src/test/java/io/github/resilience4j/bulkhead/autoconfigure/BulkheadAutoConfigurationCustomizerTest.java
{ "start": 8543, "end": 9390 }
class ____ { @Bean public BulkheadConfigCustomizer backendWithoutSharedConfigCustomizer() { return BulkheadConfigCustomizer.of("backendWithoutSharedConfig", builder -> builder.maxConcurrentCalls(1000) ); } @Bean public BulkheadConfigCustomizer backendWithSharedConfigCustomizer() { return BulkheadConfigCustomizer.of("backendWithSharedConfig", builder -> builder.maxConcurrentCalls(2000) ); } @Bean public BulkheadConfigCustomizer backendWithoutInstanceConfigCustomizer() { return BulkheadConfigCustomizer.of("backendWithoutInstanceConfig", builder -> builder.maxConcurrentCalls(3000) ); } } @Configuration public static
CustomizerConfiguration
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/AbstractInternalTerms.java
{ "start": 2144, "end": 2241 }
class ____ terms and multi_terms aggregation that handles common reduce logic */ public abstract
for
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/fgl/TestFSNLockBenchmarkThroughput.java
{ "start": 1345, "end": 3693 }
class ____ { @Test public void testFineGrainedLockingBenchmarkThroughput1() throws Exception { testBenchmarkThroughput(true, 20, 100, 1000); } @Test public void testFineGrainedLockingBenchmarkThroughput2() throws Exception { testBenchmarkThroughput(true, 20, 1000, 1000); } @Test public void testFineGrainedLockingBenchmarkThroughput3() throws Exception { testBenchmarkThroughput(true, 10, 100, 100); } @Test public void testGlobalLockingBenchmarkThroughput1() throws Exception { testBenchmarkThroughput(false, 20, 100, 1000); } @Test public void testGlobalLockingBenchmarkThroughput2() throws Exception { testBenchmarkThroughput(false, 20, 1000, 1000); } @Test public void testGlobalLockingBenchmarkThroughput3() throws Exception { testBenchmarkThroughput(false, 10, 100, 100); } private void testBenchmarkThroughput(boolean enableFGL, int readWriteRatio, int testingCount, int numClients) throws Exception { MiniQJMHACluster qjmhaCluster = null; try { Configuration conf = new HdfsConfiguration(); conf.setBoolean(DFSConfigKeys.DFS_HA_TAILEDITS_INPROGRESS_KEY, true); conf.setInt(DFSConfigKeys.DFS_QJOURNAL_SELECT_INPUT_STREAMS_TIMEOUT_KEY, 500); if (enableFGL) { conf.setClass(DFSConfigKeys.DFS_NAMENODE_LOCK_MODEL_PROVIDER_KEY, FineGrainedFSNamesystemLock.class, FSNLockManager.class); } else { conf.setClass(DFSConfigKeys.DFS_NAMENODE_LOCK_MODEL_PROVIDER_KEY, GlobalFSNamesystemLock.class, FSNLockManager.class); } MiniQJMHACluster.Builder builder = new MiniQJMHACluster.Builder(conf); builder.getDfsBuilder().numDataNodes(10); qjmhaCluster = builder.build(); MiniDFSCluster cluster = qjmhaCluster.getDfsCluster(); cluster.transitionToActive(0); cluster.waitActive(0); FileSystem fileSystem = cluster.getFileSystem(0); String[] args = new String[]{"/tmp/fsnlock/benchmark/throughput", String.valueOf(readWriteRatio), String.valueOf(testingCount), String.valueOf(numClients)}; assertEquals(0, ToolRunner.run(conf, new FSNLockBenchmarkThroughput(fileSystem), args)); } finally { if (qjmhaCluster != null) { qjmhaCluster.shutdown(); } } } }
TestFSNLockBenchmarkThroughput
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/annotations/AttributeAccessor.java
{ "start": 1924, "end": 2072 }
class ____ {@link PropertyAccessStrategy}. */ Class<? extends PropertyAccessStrategy> strategy() default PropertyAccessStrategy.class; }
implementing
java
square__moshi
moshi/src/test/java/com/squareup/moshi/JsonQualifiersTest.java
{ "start": 9879, "end": 10655 }
class ____ { Date a; @Millis Date b; } @Test public void annotationWithoutJsonQualifierIsRejectedOnRegistration() throws Exception { JsonAdapter<Date> jsonAdapter = new JsonAdapter<Date>() { @Override public Date fromJson(JsonReader reader) throws IOException { throw new AssertionError(); } @Override public void toJson(JsonWriter writer, Date value) throws IOException { throw new AssertionError(); } }; try { new Moshi.Builder().add(Date.class, Millis.class, jsonAdapter); fail(); } catch (IllegalArgumentException expected) { assertThat(expected) .hasMessageThat() .isEqualTo( "
DateAndMillisDate
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/BadInstanceof.java
{ "start": 1832, "end": 3584 }
class ____ extends BugChecker implements InstanceOfTreeMatcher { @Override public Description matchInstanceOf(InstanceOfTree tree, VisitorState state) { if (!isSubtype(getType(tree.getExpression()), getType(tree.getType()), state)) { return NO_MATCH; } String subType = SuggestedFixes.prettyType(getType(tree.getExpression()), state); String expression = state.getSourceForNode(tree.getExpression()); String superType = state.getSourceForNode(tree.getType()); if (isNonNullUsingDataflow().matches(tree.getExpression(), state)) { return buildDescription(tree) .setMessage( String.format( "`%s` is a non-null instance of %s which is a subtype of %s, so this check is" + " always true.", expression, subType, superType)) .build(); } return buildDescription(tree) .setMessage( String.format( "`%s` is an instance of %s which is a subtype of %s, so this is equivalent to a" + " null check.", expression, subType, superType)) .addFix(getFix(tree, state)) .build(); } private static SuggestedFix getFix(InstanceOfTree tree, VisitorState state) { Tree parent = state.getPath().getParentPath().getLeaf(); Tree grandParent = state.getPath().getParentPath().getParentPath().getLeaf(); if (parent instanceof ParenthesizedTree && grandParent.getKind() == Kind.LOGICAL_COMPLEMENT) { return SuggestedFix.replace( grandParent, state.getSourceForNode(tree.getExpression()) + " == null"); } return SuggestedFix.replace(tree, state.getSourceForNode(tree.getExpression()) + " != null"); } }
BadInstanceof
java
netty__netty
example/src/main/java/io/netty/example/udt/echo/rendezvousBytes/ByteEchoPeerHandler.java
{ "start": 1098, "end": 2044 }
class ____ extends SimpleChannelInboundHandler<ByteBuf> { private final ByteBuf message; public ByteEchoPeerHandler(final int messageSize) { super(false); message = Unpooled.buffer(messageSize); for (int i = 0; i < message.capacity(); i++) { message.writeByte((byte) i); } } @Override public void channelActive(ChannelHandlerContext ctx) { System.err.println("ECHO active " + NioUdtProvider.socketUDT(ctx.channel()).toStringOptions()); ctx.writeAndFlush(message); } @Override public void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) { ctx.write(buf); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
ByteEchoPeerHandler
java
google__guava
android/guava-tests/test/com/google/common/reflect/InvokableTest.java
{ "start": 25120, "end": 25172 }
class ____ { {
LocalClassInInstanceInitializer
java
micronaut-projects__micronaut-core
context/src/test/groovy/io/micronaut/runtime/event/annotation/itfce/ThingCreatedEventListener.java
{ "start": 773, "end": 893 }
interface ____ { @Async @EventListener void onThingCreated(ThingCreatedEvent event); }
ThingCreatedEventListener
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/FluxNameFuseableTest.java
{ "start": 1013, "end": 2164 }
class ____ { @Test public void scanOperator() throws Exception { Tuple2<String, String> tag1 = Tuples.of("foo", "oof"); Tuple2<String, String> tag2 = Tuples.of("bar", "rab"); List<Tuple2<String, String>> tags = Arrays.asList(tag1, tag2); Flux<Integer> source = Flux.range(1, 4).map(i -> i); FluxNameFuseable<Integer> test = new FluxNameFuseable<>(source, "foo", tags); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(source); assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(-1); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); assertThat(test.scan(Scannable.Attr.NAME)).isEqualTo("foo"); //noinspection unchecked final Stream<Tuple2<String, String>> scannedTags = test.scan(Scannable.Attr.TAGS); assertThat(scannedTags).isNotNull(); assertThat(scannedTags).containsExactlyInAnyOrder(tag1, tag2); } @Test public void scanOperatorNullTags() throws Exception { Flux<Integer> source = Flux.range(1, 4); FluxNameFuseable<Integer> test = new FluxNameFuseable<>(source, "foo", null); assertThat(test.scan(Scannable.Attr.TAGS)).isNull(); } }
FluxNameFuseableTest
java
apache__camel
components/camel-ai/camel-langchain4j-agent-api/src/main/java/org/apache/camel/component/langchain4j/agent/api/AgentConfiguration.java
{ "start": 13749, "end": 13869 }
class ____ its fully qualified name using reflection. * * <p> * This method attempts to load the specified
by
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/detached/RemoveUninitializedLazyCollectionTest.java
{ "start": 2541, "end": 3510 }
class ____ { private Long id; private String name; private List<Child1> child1 = new ArrayList<>(); private List<Child2> child2 = new ArrayList<>(); public Parent() { } public Parent(Long id, String name) { this.id = id; this.name = name; } @Id public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "parent") public List<Child1> getChild1() { return child1; } public void setChild1(List<Child1> child1) { this.child1 = child1; } @OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "parent") public List<Child2> getChild2() { return child2; } public void setChild2(List<Child2> child2) { this.child2 = child2; } } @Entity(name = "Child1") public static
Parent
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/ResourceManager.java
{ "start": 65023, "end": 67313 }
class ____ implements HeartbeatListener<TaskExecutorHeartbeatPayload, Void> { @Override public void notifyHeartbeatTimeout(final ResourceID resourceID) { final String message = String.format( "The heartbeat of TaskManager with id %s timed out.", resourceID.getStringWithMetadata()); log.info(message); handleTaskManagerConnectionLoss(resourceID, new TimeoutException(message)); } private void handleTaskManagerConnectionLoss(ResourceID resourceID, Exception cause) { validateRunsInMainThread(); closeTaskManagerConnection(resourceID, cause) .ifPresent(ResourceManager.this::stopWorkerIfSupported); } @Override public void notifyTargetUnreachable(ResourceID resourceID) { final String message = String.format( "TaskManager with id %s is no longer reachable.", resourceID.getStringWithMetadata()); log.info(message); handleTaskManagerConnectionLoss(resourceID, new ResourceManagerException(message)); } @Override public void reportPayload( final ResourceID resourceID, final TaskExecutorHeartbeatPayload payload) { validateRunsInMainThread(); final WorkerRegistration<WorkerType> workerRegistration = taskExecutors.get(resourceID); if (workerRegistration == null) { log.debug( "Received slot report from TaskManager {} which is no longer registered.", resourceID.getStringWithMetadata()); } else { InstanceID instanceId = workerRegistration.getInstanceID(); slotManager.reportSlotStatus(instanceId, payload.getSlotReport()); clusterPartitionTracker.processTaskExecutorClusterPartitionReport( resourceID, payload.getClusterPartitionReport()); } } @Override public Void retrievePayload(ResourceID resourceID) { return null; } } private
TaskManagerHeartbeatListener
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/exception/AbstractExceptionTest.java
{ "start": 912, "end": 980 }
class ____ testing {@link Exception} descendants */ public abstract
for
java
netty__netty
handler/src/test/java/io/netty/handler/ssl/SslContextTest.java
{ "start": 1474, "end": 13937 }
class ____ { @Test public void testUnencryptedEmptyPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey( ResourcesUtil.getFile(getClass(), "test2_unencrypted.pem"), ""); } }); } @Test public void testUnEncryptedNullPassword() throws Exception { PrivateKey key = SslContext.toPrivateKey( ResourcesUtil.getFile(getClass(), "test2_unencrypted.pem"), null); assertNotNull(key); } @Test public void testEncryptedEmptyPassword() throws Exception { PrivateKey key = SslContext.toPrivateKey( ResourcesUtil.getFile(getClass(), "test_encrypted_empty_pass.pem"), ""); assertNotNull(key); } @Test public void testEncryptedNullPassword() throws Exception { assertThrows(InvalidKeySpecException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey( ResourcesUtil.getFile(getClass(), "test_encrypted_empty_pass.pem"), null); } }); } @Test public void testSslContextWithEncryptedPrivateKey() throws SSLException { File keyFile = ResourcesUtil.getFile(getClass(), "test_encrypted.pem"); File crtFile = ResourcesUtil.getFile(getClass(), "test.crt"); ReferenceCountUtil.release(newSslContext(crtFile, keyFile, "12345")); } @Test public void testSslContextWithEncryptedPrivateKey2() throws SSLException { File keyFile = ResourcesUtil.getFile(getClass(), "test2_encrypted.pem"); File crtFile = ResourcesUtil.getFile(getClass(), "test2.crt"); ReferenceCountUtil.release(newSslContext(crtFile, keyFile, "12345")); } @Test public void testSslContextWithUnencryptedPrivateKey() throws SSLException { File keyFile = ResourcesUtil.getFile(getClass(), "test_unencrypted.pem"); File crtFile = ResourcesUtil.getFile(getClass(), "test.crt"); ReferenceCountUtil.release(newSslContext(crtFile, keyFile, null)); } @Test public void testSslContextWithUnencryptedPrivateKeyEmptyPass() throws SSLException { final File keyFile = ResourcesUtil.getFile(getClass(), "test_unencrypted.pem"); final File crtFile = ResourcesUtil.getFile(getClass(), "test.crt"); assertThrows(SSLException.class, new Executable() { @Override public void execute() throws Throwable { newSslContext(crtFile, keyFile, ""); } }); } @Test public void testSupportedCiphers() throws KeyManagementException, NoSuchAlgorithmException, SSLException { SSLContext jdkSslContext = SSLContext.getInstance("TLS"); jdkSslContext.init(null, null, null); SSLEngine sslEngine = jdkSslContext.createSSLEngine(); String unsupportedCipher = "TLS_DH_anon_WITH_DES_CBC_SHA"; IllegalArgumentException exception = null; try { sslEngine.setEnabledCipherSuites(new String[] {unsupportedCipher}); } catch (IllegalArgumentException e) { exception = e; } assumeTrue(exception != null); File keyFile = ResourcesUtil.getFile(getClass(), "test_unencrypted.pem"); File crtFile = ResourcesUtil.getFile(getClass(), "test.crt"); SslContext sslContext = newSslContext(crtFile, keyFile, null); assertFalse(sslContext.cipherSuites().contains(unsupportedCipher)); ReferenceCountUtil.release(sslContext); } @Test public void testUnsupportedParams() throws CertificateException { assertThrows(CertificateException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toX509Certificates( new File(getClass().getResource("ec_params_unsupported.pem").getFile())); } }); } protected abstract SslContext newSslContext(File crtFile, File keyFile, String pass) throws SSLException; @Test public void testPkcs1UnencryptedRsa() throws Exception { PrivateKey key = SslContext.toPrivateKey( new File(getClass().getResource("rsa_pkcs1_unencrypted.key").getFile()), null); assertNotNull(key); } @Test public void testPkcs8UnencryptedRsa() throws Exception { PrivateKey key = SslContext.toPrivateKey( new File(getClass().getResource("rsa_pkcs8_unencrypted.key").getFile()), null); assertNotNull(key); } @Test public void testPkcs8AesEncryptedRsa() throws Exception { PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs8_aes_encrypted.key") .getFile()), "example"); assertNotNull(key); } @Test public void testPkcs8Des3EncryptedRsa() throws Exception { PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs8_des3_encrypted.key") .getFile()), "example"); assertNotNull(key); } @Test public void testPkcs8Pbes2() throws Exception { PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("rsa_pbes2_enc_pkcs8.key") .getFile()), "12345678", false); assertNotNull(key); } @Test public void testPkcs1UnencryptedRsaEmptyPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey( new File(getClass().getResource("rsa_pkcs1_unencrypted.key").getFile()), ""); } }); } @Test public void testPkcs1Des3EncryptedRsa() throws Exception { PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_des3_encrypted.key") .getFile()), "example"); assertNotNull(key); } @Test public void testPkcs1AesEncryptedRsa() throws Exception { PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_aes_encrypted.key") .getFile()), "example"); assertNotNull(key); } @Test public void testPkcs1Des3EncryptedRsaNoPassword() throws Exception { assertThrows(InvalidKeySpecException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_des3_encrypted.key") .getFile()), null); } }); } @Test public void testPkcs1AesEncryptedRsaNoPassword() throws Exception { assertThrows(InvalidKeySpecException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_aes_encrypted.key") .getFile()), null); } }); } @Test public void testPkcs1Des3EncryptedRsaEmptyPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_des3_encrypted.key") .getFile()), ""); } }); } @Test public void testPkcs1AesEncryptedRsaEmptyPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_aes_encrypted.key") .getFile()), ""); } }); } @Test public void testPkcs1Des3EncryptedRsaWrongPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_des3_encrypted.key") .getFile()), "wrong"); } }); } @Test public void testPkcs1AesEncryptedRsaWrongPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("rsa_pkcs1_aes_encrypted.key") .getFile()), "wrong"); } }); } @Test public void testPkcs1UnencryptedDsa() throws Exception { PrivateKey key = SslContext.toPrivateKey( new File(getClass().getResource("dsa_pkcs1_unencrypted.key").getFile()), null); assertNotNull(key); } @Test public void testPkcs1UnencryptedDsaEmptyPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { PrivateKey key = SslContext.toPrivateKey( new File(getClass().getResource("dsa_pkcs1_unencrypted.key").getFile()), ""); } }); } @Test public void testPkcs1Des3EncryptedDsa() throws Exception { PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("dsa_pkcs1_des3_encrypted.key") .getFile()), "example"); assertNotNull(key); } @Test public void testPkcs1AesEncryptedDsa() throws Exception { PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("dsa_pkcs1_aes_encrypted.key") .getFile()), "example"); assertNotNull(key); } @Test public void testPkcs1Des3EncryptedDsaNoPassword() throws Exception { assertThrows(InvalidKeySpecException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("dsa_pkcs1_des3_encrypted.key") .getFile()), null); } }); } @Test public void testPkcs1AesEncryptedDsaNoPassword() throws Exception { assertThrows(InvalidKeySpecException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("dsa_pkcs1_aes_encrypted.key") .getFile()), null); } }); } @Test public void testPkcs1Des3EncryptedDsaEmptyPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("dsa_pkcs1_des3_encrypted.key") .getFile()), ""); } }); } @Test public void testPkcs1AesEncryptedDsaEmptyPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("dsa_pkcs1_aes_encrypted.key") .getFile()), ""); } }); } @Test public void testPkcs1Des3EncryptedDsaWrongPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("dsa_pkcs1_des3_encrypted.key") .getFile()), "wrong"); } }); } @Test public void testPkcs1AesEncryptedDsaWrongPassword() throws Exception { assertThrows(IOException.class, new Executable() { @Override public void execute() throws Throwable { SslContext.toPrivateKey(new File(getClass().getResource("dsa_pkcs1_aes_encrypted.key") .getFile()), "wrong"); } }); } }
SslContextTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerReapContext.java
{ "start": 1201, "end": 2511 }
class ____ { private Container builderContainer; private String builderUser; public Builder() { } /** * Set the container within the context. * * @param container the {@link Container}. * @return the Builder with the container set. */ public Builder setContainer(Container container) { this.builderContainer = container; return this; } /** * Set the set within the context. * * @param user the user. * @return the Builder with the user set. */ public Builder setUser(String user) { this.builderUser = user; return this; } /** * Builds the context with the attributes set. * * @return the context. */ public ContainerReapContext build() { return new ContainerReapContext(this); } } private ContainerReapContext(Builder builder) { this.container = builder.builderContainer; this.user = builder.builderUser; } /** * Get the container set for the context. * * @return the {@link Container} set in the context. */ public Container getContainer() { return container; } /** * Get the user set for the context. * * @return the user set in the context. */ public String getUser() { return user; } }
Builder
java
apache__camel
components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/model/SearchCriteria.java
{ "start": 949, "end": 2298 }
class ____ implements Serializable { private static final long serialVersionUID = 1002576245120313648L; private Integer page; private Integer perPage; private String search; private Order order; private List<Integer> exclude; private List<Integer> include; public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getPerPage() { return perPage; } public void setPerPage(Integer perPage) { this.perPage = perPage; } public String getSearch() { return search; } public void setSearch(String search) { this.search = search; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public List<Integer> getExclude() { return exclude; } public void setExclude(List<Integer> exclude) { this.exclude = exclude; } public List<Integer> getInclude() { return include; } public void setInclude(List<Integer> include) { this.include = include; } @Override public String toString() { return "SearchCriteria{Query=" + search + ", Page=" + page + ", Per Page=" + perPage + ", " + order + "}"; } }
SearchCriteria
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java
{ "start": 170096, "end": 170577 }
class ____ { public static CustomMap<String, TestBean> testBeanMap() { CustomMap<String, TestBean> tbm = new CustomHashMap<>(); tbm.put("testBean1", new TestBean("tb1")); tbm.put("testBean2", new TestBean("tb2")); return tbm; } public static CustomSet<TestBean> testBeanSet() { CustomSet<TestBean> tbs = new CustomHashSet<>(); tbs.add(new TestBean("tb1")); tbs.add(new TestBean("tb2")); return tbs; } } public static
CustomCollectionFactoryMethods
java
apache__camel
components/camel-jms/src/main/java/org/apache/camel/component/jms/reply/JmsReplyHelper.java
{ "start": 921, "end": 1506 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(JmsReplyHelper.class); private JmsReplyHelper() { } static String getMessageSelector(String fixedMessageSelector, MessageSelectorCreator creator) { // override this method and return the appropriate selector String id = null; if (fixedMessageSelector != null) { id = fixedMessageSelector; } else if (creator != null) { id = creator.get(); } LOG.trace("Using MessageSelector[{}]", id); return id; } }
JmsReplyHelper
java
apache__maven
compat/maven-model-builder/src/main/java/org/apache/maven/model/path/DefaultModelUrlNormalizer.java
{ "start": 1439, "end": 2530 }
class ____ implements ModelUrlNormalizer { @Inject private UrlNormalizer urlNormalizer; public DefaultModelUrlNormalizer setUrlNormalizer(UrlNormalizer urlNormalizer) { this.urlNormalizer = urlNormalizer; return this; } @Override public void normalize(Model model, ModelBuildingRequest request) { if (model == null) { return; } model.setUrl(normalize(model.getUrl())); Scm scm = model.getScm(); if (scm != null) { scm.setUrl(normalize(scm.getUrl())); scm.setConnection(normalize(scm.getConnection())); scm.setDeveloperConnection(normalize(scm.getDeveloperConnection())); } DistributionManagement dist = model.getDistributionManagement(); if (dist != null) { Site site = dist.getSite(); if (site != null) { site.setUrl(normalize(site.getUrl())); } } } private String normalize(String url) { return urlNormalizer.normalize(url); } }
DefaultModelUrlNormalizer
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/ListFieldTest3.java
{ "start": 793, "end": 846 }
class ____ { public int width; } public static
Image
java
grpc__grpc-java
benchmarks/src/generated/main/grpc/io/grpc/benchmarks/proto/ReportQpsScenarioServiceGrpc.java
{ "start": 5744, "end": 6127 }
class ____ implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return ReportQpsScenarioServiceGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service ReportQpsScenarioService. */ public static final
ReportQpsScenarioServiceImplBase
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/errors/RetriableException.java
{ "start": 943, "end": 1349 }
class ____ extends ApiException { private static final long serialVersionUID = 1L; public RetriableException(String message, Throwable cause) { super(message, cause); } public RetriableException(String message) { super(message); } public RetriableException(Throwable cause) { super(cause); } public RetriableException() { } }
RetriableException
java
redisson__redisson
redisson-hibernate/redisson-hibernate-5/src/test/java/org/redisson/hibernate/TransactionalTest.java
{ "start": 533, "end": 6098 }
class ____ extends BaseCoreFunctionalTestCase { @Override protected Class<?>[] getAnnotatedClasses() { return new Class[] { ItemTransactional.class}; } @Override protected void configure(Configuration cfg) { super.configure(cfg); cfg.setProperty(Environment.DRIVER, org.h2.Driver.class.getName()); cfg.setProperty(Environment.URL, "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;"); cfg.setProperty(Environment.USER, "sa"); cfg.setProperty(Environment.PASS, ""); cfg.setProperty(Environment.CACHE_REGION_PREFIX, ""); cfg.setProperty(Environment.GENERATE_STATISTICS, "true"); cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true"); cfg.setProperty(Environment.USE_QUERY_CACHE, "true"); cfg.setProperty(Environment.CACHE_REGION_FACTORY, RedissonRegionFactory.class.getName()); } @Before public void before() { sessionFactory().getCache().evictEntityRegions(); sessionFactory().getStatistics().clear(); } @Test public void testQuery() { Statistics stats = sessionFactory().getStatistics(); Session s = openSession(); s.beginTransaction(); ItemTransactional item = new ItemTransactional("data"); item.getEntries().addAll(Arrays.asList("a", "b", "c")); s.save(item); s.flush(); s.getTransaction().commit(); s = openSession(); s.beginTransaction(); Query query = s.getNamedQuery("testQuery"); query.setCacheable(true); query.setCacheRegion("myTestQuery"); query.setParameter("name", "data"); item = (ItemTransactional) query.uniqueResult(); s.getTransaction().commit(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getPutCount()); s = openSession(); s.beginTransaction(); Query query2 = s.getNamedQuery("testQuery"); query2.setCacheable(true); query2.setCacheRegion("myTestQuery"); query2.setParameter("name", "data"); item = (ItemTransactional) query2.uniqueResult(); s.delete(item); s.getTransaction().commit(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getHitCount()); stats.logSummary(); } @Test public void testCollection() { Long id = null; Statistics stats = sessionFactory().getStatistics(); Session s = openSession(); s.beginTransaction(); ItemTransactional item = new ItemTransactional("data"); item.getEntries().addAll(Arrays.asList("a", "b", "c")); id = (Long) s.save(item); s.flush(); s.getTransaction().commit(); s = openSession(); s.beginTransaction(); item = (ItemTransactional) s.get(ItemTransactional.class, id); assertThat(item.getEntries()).containsExactly("a", "b", "c"); s.getTransaction().commit(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item_entries").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemTransactional) s.get(ItemTransactional.class, id); assertThat(item.getEntries()).containsExactly("a", "b", "c"); s.delete(item); s.getTransaction().commit(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item_entries").getHitCount()); } @Test public void testNaturalId() { Statistics stats = sessionFactory().getStatistics(); Session s = openSession(); s.beginTransaction(); ItemTransactional item = new ItemTransactional("data"); item.setNid("123"); s.save(item); s.flush(); s.getTransaction().commit(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount()); Assert.assertEquals(1, stats.getNaturalIdCacheStatistics("item##NaturalId").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemTransactional) s.bySimpleNaturalId(ItemTransactional.class).load("123"); assertThat(item).isNotNull(); s.delete(item); s.getTransaction().commit(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount()); Assert.assertEquals(1, stats.getNaturalIdCacheStatistics("item##NaturalId").getHitCount()); sessionFactory().getStatistics().logSummary(); } @Test public void testUpdateWithRefreshThenRollback() { Statistics stats = sessionFactory().getStatistics(); Long id = null; Session s = openSession(); s.beginTransaction(); ItemTransactional item = new ItemTransactional( "data" ); id = (Long) s.save( item ); s.flush(); s.getTransaction().commit(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount()); s = openSession(); s.beginTransaction(); item = (ItemTransactional) s.get(ItemTransactional.class, id); item.setName("newdata"); s.update(item); s.flush(); s.refresh(item); s.getTransaction().rollback(); s.clear(); s.close(); Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount()); } }
TransactionalTest
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/rules/action/ListQueryRulesetsAction.java
{ "start": 3610, "end": 4949 }
class ____ extends ActionResponse implements ToXContentObject { public static final ParseField RESULT_FIELD = new ParseField("results"); final QueryPage<QueryRulesetListItem> queryPage; public Response(StreamInput in) throws IOException { this.queryPage = new QueryPage<>(in, QueryRulesetListItem::new); } public Response(List<QueryRulesetListItem> items, Long totalResults) { this.queryPage = new QueryPage<>(items, totalResults, RESULT_FIELD); } @Override public void writeTo(StreamOutput out) throws IOException { queryPage.writeTo(out); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return queryPage.toXContent(builder, params); } public QueryPage<QueryRulesetListItem> queryPage() { return queryPage; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Response that = (Response) o; return queryPage.equals(that.queryPage); } @Override public int hashCode() { return queryPage.hashCode(); } } }
Response
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchCollector.java
{ "start": 2153, "end": 19550 }
class ____<K, V> { private final Logger log; private final ConsumerMetadata metadata; private final SubscriptionState subscriptions; private final FetchConfig fetchConfig; private final Deserializers<K, V> deserializers; private final FetchMetricsManager metricsManager; private final Time time; public FetchCollector(final LogContext logContext, final ConsumerMetadata metadata, final SubscriptionState subscriptions, final FetchConfig fetchConfig, final Deserializers<K, V> deserializers, final FetchMetricsManager metricsManager, final Time time) { this.log = logContext.logger(FetchCollector.class); this.metadata = metadata; this.subscriptions = subscriptions; this.fetchConfig = fetchConfig; this.deserializers = deserializers; this.metricsManager = metricsManager; this.time = time; } /** * Return the fetched {@link ConsumerRecord records}, empty the {@link FetchBuffer record buffer}, and * update the consumed position. * * </p> * * NOTE: returning an {@link Fetch#empty() empty} fetch guarantees the consumed position is not updated. * * @param fetchBuffer {@link FetchBuffer} from which to retrieve the {@link ConsumerRecord records} * * @return A {@link Fetch} for the requested partitions * @throws OffsetOutOfRangeException If there is OffsetOutOfRange error in fetchResponse and * the defaultResetPolicy is NONE * @throws TopicAuthorizationException If there is TopicAuthorization error in fetchResponse. */ public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) { final Fetch<K, V> fetch = Fetch.empty(); final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>(); int recordsRemaining = fetchConfig.maxPollRecords; try { while (recordsRemaining > 0) { final CompletedFetch nextInLineFetch = fetchBuffer.nextInLineFetch(); if (nextInLineFetch == null || nextInLineFetch.isConsumed()) { final CompletedFetch completedFetch = fetchBuffer.peek(); if (completedFetch == null) break; if (!completedFetch.isInitialized()) { try { fetchBuffer.setNextInLineFetch(initialize(completedFetch)); } catch (Exception e) { // Remove a completedFetch upon a parse with exception if (1) it contains no completedFetch, and // (2) there are no fetched completedFetch with actual content preceding this exception. // The first condition ensures that the completedFetches is not stuck with the same completedFetch // in cases such as the TopicAuthorizationException, and the second condition ensures that no // potential data loss due to an exception in a following record. if (fetch.isEmpty() && FetchResponse.recordsOrFail(completedFetch.partitionData).sizeInBytes() == 0) fetchBuffer.poll(); throw e; } } else { fetchBuffer.setNextInLineFetch(completedFetch); } fetchBuffer.poll(); } else if (subscriptions.isPaused(nextInLineFetch.partition)) { // when the partition is paused we add the records back to the completedFetches queue instead of draining // them so that they can be returned on a subsequent poll if the partition is resumed at that time log.debug("Skipping fetching records for assigned partition {} because it is paused", nextInLineFetch.partition); pausedCompletedFetches.add(nextInLineFetch); fetchBuffer.setNextInLineFetch(null); } else { final Fetch<K, V> nextFetch = fetchRecords(nextInLineFetch, recordsRemaining); recordsRemaining -= nextFetch.numRecords(); fetch.add(nextFetch); } } } catch (KafkaException e) { if (fetch.isEmpty()) throw e; } finally { // add any polled completed fetches for paused partitions back to the completed fetches queue to be // re-evaluated in the next poll fetchBuffer.addAll(pausedCompletedFetches); } return fetch; } private Fetch<K, V> fetchRecords(final CompletedFetch nextInLineFetch, int maxRecords) { final TopicPartition tp = nextInLineFetch.partition; if (!subscriptions.isAssigned(tp)) { // this can happen when a rebalance happened before fetched records are returned to the consumer's poll call log.debug("Not returning fetched records for partition {} since it is no longer assigned", tp); } else if (!subscriptions.isFetchable(tp)) { // this can happen when a partition is paused before fetched records are returned to the consumer's // poll call or if the offset is being reset. // It can also happen under the Consumer rebalance protocol, when the consumer changes its subscription. // Until the consumer receives an updated assignment from the coordinator, it can hold assigned partitions // that are not in the subscription anymore, so we make them not fetchable. log.debug("Not returning fetched records for assigned partition {} since it is no longer fetchable", tp); } else { SubscriptionState.FetchPosition position = subscriptions.position(tp); if (position == null) throw new IllegalStateException("Missing position for fetchable partition " + tp); if (nextInLineFetch.nextFetchOffset() == position.offset) { List<ConsumerRecord<K, V>> partRecords = nextInLineFetch.fetchRecords(fetchConfig, deserializers, maxRecords); log.trace("Returning {} fetched records at offset {} for assigned partition {}", partRecords.size(), position, tp); boolean positionAdvanced = false; if (nextInLineFetch.nextFetchOffset() > position.offset) { SubscriptionState.FetchPosition nextPosition = new SubscriptionState.FetchPosition( nextInLineFetch.nextFetchOffset(), nextInLineFetch.lastEpoch(), position.currentLeader); log.trace("Updating fetch position from {} to {} for partition {} and returning {} records from `poll()`", position, nextPosition, tp, partRecords.size()); subscriptions.position(tp, nextPosition); positionAdvanced = true; } Long partitionLag = subscriptions.partitionLag(tp, fetchConfig.isolationLevel); if (partitionLag != null) metricsManager.recordPartitionLag(tp, partitionLag); Long lead = subscriptions.partitionLead(tp); if (lead != null) { metricsManager.recordPartitionLead(tp, lead); } return Fetch.forPartition(tp, partRecords, positionAdvanced, new OffsetAndMetadata(nextInLineFetch.nextFetchOffset(), nextInLineFetch.lastEpoch(), "")); } else { // these records aren't next in line based on the last consumed position, ignore them // they must be from an obsolete request log.debug("Ignoring fetched records for {} at offset {} since the current position is {}", tp, nextInLineFetch.nextFetchOffset(), position); } } log.trace("Draining fetched records for partition {}", tp); nextInLineFetch.drain(); return Fetch.empty(); } /** * Initialize a CompletedFetch object. */ protected CompletedFetch initialize(final CompletedFetch completedFetch) { final TopicPartition tp = completedFetch.partition; final Errors error = Errors.forCode(completedFetch.partitionData.errorCode()); boolean recordMetrics = true; try { if (!subscriptions.hasValidPosition(tp)) { // this can happen when a rebalance happened while fetch is still in-flight log.debug("Ignoring fetched records for partition {} since it no longer has valid position", tp); return null; } else if (error == Errors.NONE) { final CompletedFetch ret = handleInitializeSuccess(completedFetch); recordMetrics = ret == null; return ret; } else { handleInitializeErrors(completedFetch, error); return null; } } finally { if (recordMetrics) { completedFetch.recordAggregatedMetrics(0, 0); } if (error != Errors.NONE) // we move the partition to the end if there was an error. This way, it's more likely that partitions for // the same topic can remain together (allowing for more efficient serialization). subscriptions.movePartitionToEnd(tp); } } private CompletedFetch handleInitializeSuccess(final CompletedFetch completedFetch) { final TopicPartition tp = completedFetch.partition; final long fetchOffset = completedFetch.nextFetchOffset(); // we are interested in this fetch only if the beginning offset matches the // current consumed position SubscriptionState.FetchPosition position = subscriptions.positionOrNull(tp); if (position == null || position.offset != fetchOffset) { log.debug("Discarding stale fetch response for partition {} since its offset {} does not match " + "the expected offset {} or the partition has been unassigned", tp, fetchOffset, position); return null; } final FetchResponseData.PartitionData partition = completedFetch.partitionData; log.trace("Preparing to read {} bytes of data for partition {} with offset {}", FetchResponse.recordsSize(partition), tp, position); Iterator<? extends RecordBatch> batches = FetchResponse.recordsOrFail(partition).batches().iterator(); if (!batches.hasNext() && FetchResponse.recordsSize(partition) > 0) { // This should not happen with brokers that support FetchRequest/Response V4 or higher (i.e. KIP-74) throw new KafkaException("Failed to make progress reading messages at " + tp + "=" + fetchOffset + ". Received a non-empty fetch response from the server, but no " + "complete records were found."); } if (!updatePartitionState(partition, tp)) { return null; } completedFetch.setInitialized(); return completedFetch; } private boolean updatePartitionState(final FetchResponseData.PartitionData partitionData, final TopicPartition tp) { if (partitionData.highWatermark() >= 0) { log.trace("Updating high watermark for partition {} to {}", tp, partitionData.highWatermark()); if (!subscriptions.tryUpdatingHighWatermark(tp, partitionData.highWatermark())) { return false; } } if (partitionData.logStartOffset() >= 0) { log.trace("Updating log start offset for partition {} to {}", tp, partitionData.logStartOffset()); if (!subscriptions.tryUpdatingLogStartOffset(tp, partitionData.logStartOffset())) { return false; } } if (partitionData.lastStableOffset() >= 0) { log.trace("Updating last stable offset for partition {} to {}", tp, partitionData.lastStableOffset()); if (!subscriptions.tryUpdatingLastStableOffset(tp, partitionData.lastStableOffset())) { return false; } } if (FetchResponse.isPreferredReplica(partitionData)) { return subscriptions.tryUpdatingPreferredReadReplica( tp, partitionData.preferredReadReplica(), () -> { long expireTimeMs = time.milliseconds() + metadata.metadataExpireMs(); log.debug("Updating preferred read replica for partition {} to {}, set to expire at {}", tp, partitionData.preferredReadReplica(), expireTimeMs); return expireTimeMs; }); } return true; } private void handleInitializeErrors(final CompletedFetch completedFetch, final Errors error) { final TopicPartition tp = completedFetch.partition; final long fetchOffset = completedFetch.nextFetchOffset(); if (error == Errors.NOT_LEADER_OR_FOLLOWER || error == Errors.REPLICA_NOT_AVAILABLE || error == Errors.KAFKA_STORAGE_ERROR || error == Errors.FENCED_LEADER_EPOCH || error == Errors.OFFSET_NOT_AVAILABLE) { log.debug("Error in fetch for partition {}: {}", tp, error.exceptionName()); requestMetadataUpdate(metadata, subscriptions, tp); } else if (error == Errors.UNKNOWN_TOPIC_OR_PARTITION) { log.warn("Received unknown topic or partition error in fetch for partition {}", tp); requestMetadataUpdate(metadata, subscriptions, tp); } else if (error == Errors.UNKNOWN_TOPIC_ID) { log.warn("Received unknown topic ID error in fetch for partition {}", tp); requestMetadataUpdate(metadata, subscriptions, tp); } else if (error == Errors.INCONSISTENT_TOPIC_ID) { log.warn("Received inconsistent topic ID error in fetch for partition {}", tp); requestMetadataUpdate(metadata, subscriptions, tp); } else if (error == Errors.OFFSET_OUT_OF_RANGE) { Optional<Integer> clearedReplicaId = subscriptions.clearPreferredReadReplica(tp); if (clearedReplicaId.isEmpty()) { // If there's no preferred replica to clear, we're fetching from the leader so handle this error normally SubscriptionState.FetchPosition position = subscriptions.positionOrNull(tp); if (position == null || fetchOffset != position.offset) { log.debug("Discarding stale fetch response for partition {} since the fetched offset {} " + "does not match the current offset {} or the partition has been unassigned", tp, fetchOffset, position); } else { String errorMessage = "Fetch position " + position + " is out of range for partition " + tp; if (subscriptions.hasDefaultOffsetResetPolicy()) { log.info("{}, resetting offset", errorMessage); subscriptions.requestOffsetResetIfPartitionAssigned(tp); } else { log.info("{}, raising error to the application since no reset policy is configured", errorMessage); throw new OffsetOutOfRangeException(errorMessage, Collections.singletonMap(tp, position.offset)); } } } else { log.debug("Unset the preferred read replica {} for partition {} since we got {} when fetching {}", clearedReplicaId.get(), tp, error, fetchOffset); } } else if (error == Errors.TOPIC_AUTHORIZATION_FAILED) { //we log the actual partition and not just the topic to help with ACL propagation issues in large clusters log.warn("Not authorized to read from partition {}.", tp); throw new TopicAuthorizationException(Collections.singleton(tp.topic())); } else if (error == Errors.UNKNOWN_LEADER_EPOCH) { log.debug("Received unknown leader epoch error in fetch for partition {}", tp); } else if (error == Errors.UNKNOWN_SERVER_ERROR) { log.warn("Unknown server error while fetching offset {} for topic-partition {}", fetchOffset, tp); } else if (error == Errors.CORRUPT_MESSAGE) { throw new KafkaException("Encountered corrupt message when fetching offset " + fetchOffset + " for topic-partition " + tp); } else { throw new IllegalStateException("Unexpected error code " + error.code() + " while fetching at offset " + fetchOffset + " from topic-partition " + tp); } } }
FetchCollector
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/UnnecessarilyUsedValueTest.java
{ "start": 5696, "end": 6110 }
class ____ { public void varNotUnused() throws Exception { try (java.io.Closeable unused = getCloseable()) {} } @com.google.errorprone.annotations.CanIgnoreReturnValue private java.io.Closeable getCloseable() { return null; } } """) .expectUnchanged() .doTest(); } }
Client
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/logging/Log.java
{ "start": 2711, "end": 3161 }
class ____ * @param message the message * @param t the throwable */ public static void trace(String loggerFqcn, Object message, Throwable t) { if (shouldFail) { throw fail(); } Logger.getLogger(stackWalker.getCallerClass()).trace(loggerFqcn, message, t); } /** * Issue a log message with parameters and a throwable with a level of TRACE. * * @param loggerFqcn the logger
name
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsTests.java
{ "start": 5940, "end": 14853 }
class ____ { @Test void returnsPrimitiveVoid() throws Exception { Class<?> clazz = ClassWithVoidAndNonVoidMethods.class; assertTrue(ReflectionUtils.returnsPrimitiveVoid(clazz.getDeclaredMethod("voidMethod"))); assertFalse(ReflectionUtils.returnsPrimitiveVoid(clazz.getDeclaredMethod("methodReturningVoidReference"))); assertFalse(ReflectionUtils.returnsPrimitiveVoid(clazz.getDeclaredMethod("methodReturningObject"))); assertFalse(ReflectionUtils.returnsPrimitiveVoid(clazz.getDeclaredMethod("methodReturningPrimitive"))); } @SuppressWarnings("DataFlowIssue") @Test void getAllAssignmentCompatibleClassesWithNullClass() { assertPreconditionViolationFor(() -> ReflectionUtils.getAllAssignmentCompatibleClasses(null)); } @Test void getAllAssignmentCompatibleClasses() { var superclasses = ReflectionUtils.getAllAssignmentCompatibleClasses(B.class); assertThat(superclasses).containsExactly(B.class, InterfaceC.class, InterfaceA.class, InterfaceB.class, A.class, InterfaceD.class, Object.class); assertTrue(superclasses.stream().allMatch(clazz -> clazz.isAssignableFrom(B.class))); } @SuppressWarnings("DataFlowIssue") @Test void newInstance() { // @formatter:off assertThat(ReflectionUtils.newInstance(C.class, "one", "two")).isNotNull(); assertThat(ReflectionUtils.newInstance(C.class)).isNotNull(); assertPreconditionViolationFor(() -> ReflectionUtils.newInstance(C.class, "one", null)); assertPreconditionViolationFor(() -> ReflectionUtils.newInstance(C.class, null, "two")); assertPreconditionViolationFor(() -> ReflectionUtils.newInstance(C.class, null, null)); assertPreconditionViolationFor(() -> ReflectionUtils.newInstance(C.class, ((Object[]) null))); var exception = assertThrows(RuntimeException.class, () -> ReflectionUtils.newInstance(Exploder.class)); assertThat(exception).hasMessage("boom"); // @formatter:on } @Test void wideningConversion() { // byte assertTrue(isWideningConversion(byte.class, short.class)); assertTrue(isWideningConversion(byte.class, int.class)); assertTrue(isWideningConversion(byte.class, long.class)); assertTrue(isWideningConversion(byte.class, float.class)); assertTrue(isWideningConversion(byte.class, double.class)); // Byte assertTrue(isWideningConversion(Byte.class, short.class)); assertTrue(isWideningConversion(Byte.class, int.class)); assertTrue(isWideningConversion(Byte.class, long.class)); assertTrue(isWideningConversion(Byte.class, float.class)); assertTrue(isWideningConversion(Byte.class, double.class)); // short assertTrue(isWideningConversion(short.class, int.class)); assertTrue(isWideningConversion(short.class, long.class)); assertTrue(isWideningConversion(short.class, float.class)); assertTrue(isWideningConversion(short.class, double.class)); // Short assertTrue(isWideningConversion(Short.class, int.class)); assertTrue(isWideningConversion(Short.class, long.class)); assertTrue(isWideningConversion(Short.class, float.class)); assertTrue(isWideningConversion(Short.class, double.class)); // char assertTrue(isWideningConversion(char.class, int.class)); assertTrue(isWideningConversion(char.class, long.class)); assertTrue(isWideningConversion(char.class, float.class)); assertTrue(isWideningConversion(char.class, double.class)); // Character assertTrue(isWideningConversion(Character.class, int.class)); assertTrue(isWideningConversion(Character.class, long.class)); assertTrue(isWideningConversion(Character.class, float.class)); assertTrue(isWideningConversion(Character.class, double.class)); // int assertTrue(isWideningConversion(int.class, long.class)); assertTrue(isWideningConversion(int.class, float.class)); assertTrue(isWideningConversion(int.class, double.class)); // Integer assertTrue(isWideningConversion(Integer.class, long.class)); assertTrue(isWideningConversion(Integer.class, float.class)); assertTrue(isWideningConversion(Integer.class, double.class)); // long assertTrue(isWideningConversion(long.class, float.class)); assertTrue(isWideningConversion(long.class, double.class)); // Long assertTrue(isWideningConversion(Long.class, float.class)); assertTrue(isWideningConversion(Long.class, double.class)); // float assertTrue(isWideningConversion(float.class, double.class)); // Float assertTrue(isWideningConversion(Float.class, double.class)); // double and Double --> nothing to test // Unsupported assertFalse(isWideningConversion(int.class, byte.class)); // narrowing assertFalse(isWideningConversion(float.class, int.class)); // narrowing assertFalse(isWideningConversion(int.class, int.class)); // direct match assertFalse(isWideningConversion(String.class, int.class)); // neither a primitive nor a wrapper } @Test void getWrapperType() { assertEquals(Boolean.class, ReflectionUtils.getWrapperType(boolean.class)); assertEquals(Byte.class, ReflectionUtils.getWrapperType(byte.class)); assertEquals(Character.class, ReflectionUtils.getWrapperType(char.class)); assertEquals(Short.class, ReflectionUtils.getWrapperType(short.class)); assertEquals(Integer.class, ReflectionUtils.getWrapperType(int.class)); assertEquals(Long.class, ReflectionUtils.getWrapperType(long.class)); assertEquals(Float.class, ReflectionUtils.getWrapperType(float.class)); assertEquals(Double.class, ReflectionUtils.getWrapperType(double.class)); assertNull(ReflectionUtils.getWrapperType(Object.class)); } @Test void getAllClasspathRootDirectories(@TempDir Path tempDirectory) throws Exception { var root1 = tempDirectory.resolve("root1").toAbsolutePath(); var root2 = tempDirectory.resolve("root2").toAbsolutePath(); var testClassPath = root1 + File.pathSeparator + root2; var originalClassPath = System.setProperty("java.class.path", testClassPath); try { createDirectories(root1, root2); assertThat(ReflectionUtils.getAllClasspathRootDirectories()).containsOnly(root1, root2); } finally { System.setProperty("java.class.path", originalClassPath); } } private static void createDirectories(Path... paths) throws IOException { for (var path : paths) { Files.createDirectory(path); } } @SuppressWarnings("DataFlowIssue") @Test void getDeclaredConstructorPreconditions() { // @formatter:off assertPreconditionViolationFor(() -> ReflectionUtils.getDeclaredConstructor(null)); assertPreconditionViolationFor(() -> ReflectionUtils.getDeclaredConstructor(ClassWithTwoConstructors.class)); // @formatter:on } @Test void getDeclaredConstructor() { Constructor<?> constructor = ReflectionUtils.getDeclaredConstructor(getClass()); assertNotNull(constructor); assertEquals(getClass(), constructor.getDeclaringClass()); constructor = ReflectionUtils.getDeclaredConstructor(ClassWithOneCustomConstructor.class); assertNotNull(constructor); assertEquals(ClassWithOneCustomConstructor.class, constructor.getDeclaringClass()); assertEquals(String.class, constructor.getParameterTypes()[0]); } @Test void isGeneric() { for (var method : Generic.class.getMethods()) { assertTrue(ReflectionUtils.isGeneric(method)); } for (var method : NonGenericClass.class.getMethods()) { assertFalse(ReflectionUtils.isGeneric(method)); } } /** * @see <a href="https://github.com/junit-team/junit-framework/issues/3684">#3684</a> */ @Test void getInterfaceMethodIfPossible() throws Exception { // "anonymous" because it's implemented as an anonymous class. InputStream anonymousInputStream = InputStream.nullInputStream(); Class<?> targetType = anonymousInputStream.getClass(); assertThat(targetType.isAnonymousClass()).isTrue(); Method method = targetType.getMethod("close"); assertThat(method).isNotNull(); assertThat(method.getDeclaringClass()).isEqualTo(targetType); Method interfaceMethod = ReflectionUtils.getInterfaceMethodIfPossible(method, targetType); assertThat(interfaceMethod).isNotNull().isNotEqualTo(method); // InputStream implements Closeable directly, so we find the `close` method // in Closeable instead of AutoCloseable. assertThat(interfaceMethod.getDeclaringClass()).isEqualTo(Closeable.class); } @Test void isRecordObject() { assertTrue(ReflectionUtils.isRecordObject(new SomeRecord(1))); assertFalse(ReflectionUtils.isRecordObject(new ClassWithOneCustomConstructor(""))); assertFalse(ReflectionUtils.isRecordObject(null)); } @Test void isRecordClass() { assertTrue(ReflectionUtils.isRecordClass(SomeRecord.class)); assertFalse(ReflectionUtils.isRecordClass(ClassWithOneCustomConstructor.class)); assertFalse(ReflectionUtils.isRecordClass(Object.class)); } record SomeRecord(int n) { } static
MiscellaneousTests
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/functional/RemoteIterators.java
{ "start": 10675, "end": 12135 }
class ____<T> implements RemoteIterator<T>, IOStatisticsSource { /** * Single entry. */ private final T singleton; /** Has the entry been processed? */ private boolean processed; /** * Instantiate. * @param singleton single value...may be null */ private SingletonIterator(@Nullable T singleton) { this.singleton = singleton; // if the entry is null, consider it processed. this.processed = singleton == null; } @Override public boolean hasNext() throws IOException { return !processed; } @SuppressWarnings("NewExceptionWithoutArguments") @Override public T next() throws IOException { if (hasNext()) { processed = true; return singleton; } else { throw new NoSuchElementException(); } } @Override public IOStatistics getIOStatistics() { return retrieveIOStatistics(singleton); } @Override public String toString() { return "SingletonIterator{" + (singleton != null ? singleton : "") + '}'; } } /** * Create a remote iterator from a simple java.util.Iterator, or * an iterable. * <p> </p> * If the iterator is a source of statistics that is passed through. * <p></p> * The {@link #close()} will close the source iterator if it is * Closeable; * @param <T> iterator type. */ private static final
SingletonIterator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CheckReturnValueWellKnownLibrariesTest.java
{ "start": 5600, "end": 6450 }
class ____ { void f(Foo foo) { try { foo.f(); org.junit.Assert.fail("message"); } catch (Exception expected) { } try { foo.f(); junit.framework.Assert.fail("message"); } catch (Exception expected) { } try { foo.f(); junit.framework.TestCase.fail("message"); } catch (Exception expected) { } } } """) .doTest(); } @Test public void ignoreInThrowingRunnables() { compilationHelper .addSourceLines( "Foo.java", """ @com.google.errorprone.annotations.CheckReturnValue public
Test
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/internal/Integers.java
{ "start": 1254, "end": 2025 }
class ____ on {@link StandardComparisonStrategy}. */ public static Integers instance() { return INSTANCE; } // TODO reduce the visibility of the fields annotated with @VisibleForTesting Integers() { super(); } public Integers(ComparisonStrategy comparisonStrategy) { super(comparisonStrategy); } @Override protected Integer zero() { return 0; } @Override protected Integer one() { return 1; } @Override protected Integer absDiff(Integer actual, Integer other) { return Math.abs(actual - other); } @Override protected boolean isGreaterThan(Integer value, Integer other) { return value > other; } @Override public boolean isEven(Integer number) { return (number & one()) == zero(); } }
based
java
micronaut-projects__micronaut-core
http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/MiscTest.java
{ "start": 8842, "end": 10611 }
class ____ { @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Post("/without-body-annotation") String withoutBodyAnnotation(MessageCreate messageCreate) { return "{\"message\":\"Hello " + messageCreate.getMessage() + "\"}"; } @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Post String save(@Body MessageCreate messageCreate) { return "{\"message\":\"Hello " + messageCreate.getMessage() + "\"}"; } @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Post("/nested-attribute") String save(@Body("message") String value) { return "{\"message\":\"Hello " + value + "\"}"; } @Consumes(MediaType.APPLICATION_JSON) @Post("/json-without-body-annotation") String jsonWithoutBody(MessageCreate messageCreate) { return "{\"message\":\"Hello " + messageCreate.getMessage() + "\"}"; } @Consumes(MediaType.APPLICATION_JSON) @Post("/json-nested-attribute") String jsonNestedAttribute(@Body("message") String value) { return "{\"message\":\"Hello " + value + "\"}"; } @Consumes(MediaType.APPLICATION_JSON) @Post("/json-nested-attribute-with-map-return") Map<String, String> jsonNestedAttributeWithMapReturn(@Body("message") String value) { return Collections.singletonMap("message", "Hello " + value); } @Consumes(MediaType.APPLICATION_JSON) @Post("/json-with-body-annotation-and-with-object-return") MyResponse jsonNestedAttributeWithObjectReturn(@Body MessageCreate messageCreate) { return new MyResponse("Hello " + messageCreate.getMessage()); } } }
FormController
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java
{ "start": 12800, "end": 12969 }
class ____ { @Bean String foo() { return "foo"; } } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty("some.property") static
MultiValuesConfig
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/JavaRecordBuilderFactory.java
{ "start": 2816, "end": 5715 }
class ____ { private final Object[] args; JavaRecordBuilder() { if (defaultConstructorArgs == null) { args = new Object[canonicalConstructor.getParameterCount()]; } else { args = Arrays.copyOf(defaultConstructorArgs, defaultConstructorArgs.length); } } T build() { try { return canonicalConstructor.newInstance(args); } catch (Exception e) { throw new RuntimeException("Could not instantiate record", e); } } /** * Set record field by index. If parameter index mapping is provided, the index is mapped, * otherwise it is used as is. * * @param i index of field to be set * @param value field value */ void setField(int i, Object value) { if (paramIndexMapping != null) { args[paramIndexMapping[i]] = value; } else { args[i] = value; } } } static <T> JavaRecordBuilderFactory<T> create(Class<T> clazz, Field[] fields) { try { Object[] recordComponents = (Object[]) Class.class.getMethod("getRecordComponents").invoke(clazz); Class<?>[] componentTypes = new Class[recordComponents.length]; List<String> componentNames = new ArrayList<>(recordComponents.length); // We need to use reflection to access record components as they are not available in // before Java 14 Method getType = Class.forName("java.lang.reflect.RecordComponent").getMethod("getType"); Method getName = Class.forName("java.lang.reflect.RecordComponent").getMethod("getName"); for (int i = 0; i < recordComponents.length; i++) { componentNames.add((String) getName.invoke(recordComponents[i])); componentTypes[i] = (Class<?>) getType.invoke(recordComponents[i]); } Constructor<T> recordConstructor = clazz.getDeclaredConstructor(componentTypes); recordConstructor.setAccessible(true); List<String> previousFields = Arrays.stream(fields) // There may be (removed) null fields due to schema evolution .filter(Objects::nonNull) .map(Field::getName) .collect(Collectors.toList()); // If the field names / order changed we know that we are migrating the records and arg // index remapping may be necessary boolean migrating = !previousFields.equals(componentNames); if (migrating) { // If the order / index of arguments changed in the new record
JavaRecordBuilder
java
elastic__elasticsearch
x-pack/plugin/profiling/src/main/java/org/elasticsearch/xpack/profiling/action/SubGroupCollector.java
{ "start": 3924, "end": 4044 }
interface ____ { String getKey(); long getCount(); Agg getAggregations(); } static
Bucket
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 45130, "end": 45512 }
class ____ { @SuppressWarnings("Immutable") final int[] xs = {1}; } """) .doTest(); } @Test public void suppressOnOneField() { compilationHelper .addSourceLines( "Test.java", """ import com.google.errorprone.annotations.Immutable; @Immutable
Test
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/AnEnum.java
{ "start": 809, "end": 854 }
enum ____ { A, B, C, D, E, F }
AnEnum
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/tier/remote/RemoteCacheManagerTest.java
{ "start": 1735, "end": 4265 }
class ____ { @Test void testStartAndFinishSegment() { TieredStoragePartitionId partitionId = TieredStorageIdMappingUtils.convertId(new ResultPartitionID()); int subpartitionId = 0; int segmentId = 0; AtomicInteger numReceivedBuffers = new AtomicInteger(0); TestingPartitionFileWriter partitionFileWriter = new TestingPartitionFileWriter.Builder() .setWriteFunction( (ignoredPartitionId, bufferContexts) -> { numReceivedBuffers.addAndGet( bufferContexts .get(subpartitionId) .getSegmentBufferContexts() .get(segmentId) .getBufferAndIndexes() .size()); return FutureUtils.completedVoidFuture(); }) .build(); RemoteCacheManager cacheManager = new RemoteCacheManager( partitionId, 1, new TestingTieredStorageMemoryManager.Builder().build(), partitionFileWriter); cacheManager.startSegment(subpartitionId, segmentId); cacheManager.appendBuffer(BufferBuilderTestUtils.buildSomeBuffer(), subpartitionId); cacheManager.finishSegment(subpartitionId); assertThat(numReceivedBuffers).hasValue(1); } @Test void testRelease() { TieredStoragePartitionId partitionId = TieredStorageIdMappingUtils.convertId(new ResultPartitionID()); AtomicBoolean isReleased = new AtomicBoolean(false); TestingPartitionFileWriter partitionFileWriter = new TestingPartitionFileWriter.Builder() .setReleaseRunnable(() -> isReleased.set(true)) .build(); RemoteCacheManager cacheManager = new RemoteCacheManager( partitionId, 1, new TestingTieredStorageMemoryManager.Builder().build(), partitionFileWriter); cacheManager.release(); assertThat(isReleased).isTrue(); } }
RemoteCacheManagerTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/ThreadsRejectedExecutionTest.java
{ "start": 1716, "end": 7395 }
class ____ extends ContextTestSupport { @Override public boolean isUseRouteBuilder() { return false; } @Test public void testThreadsRejectedExecution() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { // use a custom pool which rejects any new tasks while currently // in progress // this should force the ThreadsProcessor to run the tasks // itself ExecutorService pool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); from("seda:start").to("log:before") // will use our custom pool .threads().executorService(pool).delay(200).to("log:after").to("mock:result"); } }); context.start(); getMockEndpoint("mock:result").expectedMessageCount(3); template.sendBody("seda:start", "Hello World"); template.sendBody("seda:start", "Hi World"); template.sendBody("seda:start", "Bye World"); assertMockEndpointsSatisfied(); } @Test public void testThreadsRejectedExecutionCallerNotRuns() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { // use a custom pool which rejects any new tasks while currently // in progress // this should force the ThreadsProcessor to run the tasks // itself ExecutorService pool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); from("seda:start").to("log:before") // will use our custom pool .threads().executorService(pool).callerRunsWhenRejected(false).delay(200).syncDelayed().to("log:after") .to("mock:result"); } }); context.start(); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(3); // wait at most 2 seconds mock.setResultWaitTime(2000); template.sendBody("seda:start", "Hello World"); template.sendBody("seda:start", "Hi World"); template.sendBody("seda:start", "Bye World"); // should not be possible to route all 3 mock.assertIsNotSatisfied(); // only 1 should arrive assertEquals(1, mock.getReceivedCounter()); } @Test public void testThreadsRejectedAbort() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("seda:start").to("log:before").threads(1, 1).maxPoolSize(1).maxQueueSize(2) .rejectedPolicy(ThreadPoolRejectedPolicy.Abort).delay(100).to("log:after") .to("mock:result"); } }); context.start(); NotifyBuilder notify = new NotifyBuilder(context).whenDone(10).create(); getMockEndpoint("mock:result").expectedMinimumMessageCount(2); for (int i = 0; i < 10; i++) { template.sendBody("seda:start", "Message " + i); } assertMockEndpointsSatisfied(); assertTrue(notify.matchesWaitTime()); int inflight = context.getInflightRepository().size(); assertEquals(0, inflight); } @Test public void testThreadsRejectedCallerRuns() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("seda:start").to("log:before").threads(1, 1).maxPoolSize(1).maxQueueSize(2) .rejectedPolicy(ThreadPoolRejectedPolicy.CallerRuns).delay(100).to("log:after") .to("mock:result"); } }); context.start(); NotifyBuilder notify = new NotifyBuilder(context).whenDone(10).create(); getMockEndpoint("mock:result").expectedMessageCount(10); for (int i = 0; i < 10; i++) { template.sendBody("seda:start", "Message " + i); } assertMockEndpointsSatisfied(); assertTrue(notify.matchesWaitTime()); int inflight = context.getInflightRepository().size(); assertEquals(0, inflight); } @Test public void testThreadsRejectedAbortNoRedelivery() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { onException(Exception.class).redeliveryDelay(250).maximumRedeliveries(3).handled(true).to("mock:error"); from("seda:start").to("log:before").threads(1, 1).maxPoolSize(1).maxQueueSize(2) .rejectedPolicy(ThreadPoolRejectedPolicy.Abort).delay(250).to("log:after") .to("mock:result"); } }); context.start(); NotifyBuilder notify = new NotifyBuilder(context).whenDone(10).create(); // there should be error handling for aborted tasks (eg no redeliveries // and no error handling) getMockEndpoint("mock:error").expectedMessageCount(0); getMockEndpoint("mock:result").expectedMinimumMessageCount(2); for (int i = 0; i < 10; i++) { template.sendBody("seda:start", "Message " + i); } assertMockEndpointsSatisfied(); assertTrue(notify.matchesWaitTime()); int inflight = context.getInflightRepository().size(); assertEquals(0, inflight); } }
ThreadsRejectedExecutionTest
java
apache__camel
components/camel-spring-parent/camel-spring-ws/src/main/java/org/apache/camel/component/spring/ws/SpringWebserviceComponent.java
{ "start": 2079, "end": 9320 }
class ____ extends DefaultComponent implements SSLContextParametersAware { private static final Logger LOG = LoggerFactory.getLogger(SpringWebserviceComponent.class); @Metadata(label = "security") private boolean useGlobalSslContextParameters; @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { SpringWebserviceConfiguration configuration = new SpringWebserviceConfiguration(); // need to do this first addConsumerConfiguration(remaining, parameters, configuration); SpringWebserviceEndpoint endpoint = new SpringWebserviceEndpoint(this, uri, configuration); setProperties(endpoint, parameters); // configure and setup configuration after it has its properties set via the endpoint configureProducerConfiguration(remaining, configuration); configureMessageFilter(configuration); if (configuration.getSslContextParameters() == null) { configuration.setSslContextParameters(retrieveGlobalSslContextParameters()); } return endpoint; } private void addConsumerConfiguration( String remaining, Map<String, Object> parameters, SpringWebserviceConfiguration configuration) { EndpointMappingType type = EndpointMappingType.getTypeFromUriPrefix(remaining); if (type != null) { LOG.debug("Building Spring Web Services consumer of type {}", type); String lookupKey = getLookupKey(remaining, type); configuration.setEndpointMappingType(type); configuration.setEndpointMappingLookupKey(lookupKey); if (EndpointMappingType.BEANNAME.equals(type)) { addEndpointDispatcherToConfiguration(configuration, lookupKey); } else { addEndpointMappingToConfiguration(parameters, configuration); if (type.equals(EndpointMappingType.XPATHRESULT)) { String expression = getAndRemoveParameter(parameters, "expression", String.class); configuration.setExpression(expression); XPathExpression xPathExpression = createXPathExpression(expression); configuration.setxPathExpression(xPathExpression); } } } } private void configureProducerConfiguration(String remaining, SpringWebserviceConfiguration configuration) throws URISyntaxException { if (configuration.getEndpointMapping() == null && configuration.getEndpointDispatcher() == null) { LOG.debug("Building Spring Web Services producer"); URI webServiceEndpointUri = new URI(UnsafeUriCharactersEncoder.encode(remaining)); // Obtain a WebServiceTemplate from the registry when specified by // an option on the component, else create a new template with // Spring-WS defaults WebServiceTemplate webServiceTemplate = configuration.getWebServiceTemplate(); if (webServiceTemplate == null) { webServiceTemplate = new WebServiceTemplate(); configuration.setWebServiceTemplate(webServiceTemplate); } if (webServiceTemplate.getDefaultUri() == null) { String uri = webServiceEndpointUri.toString(); webServiceTemplate.setDefaultUri(uri); configuration.setWebServiceEndpointUri(uri); } if (configuration.getMessageSender() != null) { webServiceTemplate.setMessageSender(configuration.getMessageSender()); } if (configuration.getMessageFactory() != null) { webServiceTemplate.setMessageFactory(configuration.getMessageFactory()); } } } private String getLookupKey(String remaining, EndpointMappingType type) { String lookupKey = remaining.substring(type.getPrefix().length()); lookupKey = lookupKey.startsWith("//") ? lookupKey.substring(2) : lookupKey; return SpringWebserviceConfiguration.decode(lookupKey); } private XPathExpression createXPathExpression(String xpathExpression) { if (xpathExpression == null) { throw new RuntimeCamelException("Expression parameter is required when using XPath endpoint mapping"); } return XPathExpressionFactory.createXPathExpression(xpathExpression); } private void addEndpointMappingToConfiguration( Map<String, Object> parameters, SpringWebserviceConfiguration configuration) { // Obtain generic CamelSpringWSEndpointMapping from registry CamelSpringWSEndpointMapping endpointMapping = resolveAndRemoveReferenceParameter(parameters, "endpointMapping", CamelSpringWSEndpointMapping.class, null); if (endpointMapping == null && configuration.getEndpointDispatcher() == null) { throw new IllegalArgumentException( "No instance of CamelSpringWSEndpointMapping found in Spring ApplicationContext." + " This bean is required for Spring-WS consumer support (unless the 'spring-ws:beanname:' URI scheme is used)"); } configuration.setEndpointMapping(endpointMapping); } private void addEndpointDispatcherToConfiguration(SpringWebserviceConfiguration configuration, String lookupKey) { // Obtain CamelEndpointDispatcher with the given name from registry CamelEndpointDispatcher endpoint = CamelContextHelper.mandatoryLookup(getCamelContext(), lookupKey, CamelEndpointDispatcher.class); configuration.setEndpointDispatcher(endpoint); } /** * Configures the messageFilter's factory. The factory is looked up in the endpoint's URI and then in the Spring's * context. The bean search mechanism looks for a bean with the name messageFilter. The endpoint's URI search * mechanism looks for the URI's key parameter name messageFilter, for instance, like this: * spring-ws:http://yourdomain.com?messageFilter=<beanName> */ private void configureMessageFilter(SpringWebserviceConfiguration configuration) { if (configuration.getMessageFilter() == null) { // try to lookup a global filter to use final MessageFilter globalMessageFilter = EndpointHelper.resolveReferenceParameter(getCamelContext(), "messageFilter", MessageFilter.class, false); if (globalMessageFilter != null) { configuration.setMessageFilter(globalMessageFilter); } else { // use basic as fallback configuration.setMessageFilter(new BasicMessageFilter()); } } } @Override public boolean isUseGlobalSslContextParameters() { return this.useGlobalSslContextParameters; } /** * Enable usage of global SSL context parameters. */ @Override public void setUseGlobalSslContextParameters(boolean useGlobalSslContextParameters) { this.useGlobalSslContextParameters = useGlobalSslContextParameters; } }
SpringWebserviceComponent
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/DtoProjectionTransformerDelegate.java
{ "start": 3199, "end": 3850 }
class ____ extends QueryRenderer { private final QueryTokenStream delegate; private DetachedStream(QueryTokenStream delegate) { this.delegate = delegate; } @Override public boolean isExpression() { return delegate.isExpression(); } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public Iterator<QueryToken> iterator() { return delegate.iterator(); } @Override public String render() { return delegate instanceof QueryRenderer ? ((QueryRenderer) delegate).render() : delegate.toString(); } } }
DetachedStream
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialDisjointCartesianPointDocValuesAndSourceEvaluator.java
{ "start": 1178, "end": 3948 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(SpatialDisjointCartesianPointDocValuesAndSourceEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator left; private final EvalOperator.ExpressionEvaluator right; private final DriverContext driverContext; private Warnings warnings; public SpatialDisjointCartesianPointDocValuesAndSourceEvaluator(Source source, EvalOperator.ExpressionEvaluator left, EvalOperator.ExpressionEvaluator right, DriverContext driverContext) { this.source = source; this.left = left; this.right = right; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (LongBlock leftBlock = (LongBlock) left.eval(page)) { try (BytesRefBlock rightBlock = (BytesRefBlock) right.eval(page)) { return eval(page.getPositionCount(), leftBlock, rightBlock); } } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += left.baseRamBytesUsed(); baseRamBytesUsed += right.baseRamBytesUsed(); return baseRamBytesUsed; } public BooleanBlock eval(int positionCount, LongBlock leftBlock, BytesRefBlock rightBlock) { try(BooleanBlock.Builder result = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { boolean allBlocksAreNulls = true; if (!leftBlock.isNull(p)) { allBlocksAreNulls = false; } if (!rightBlock.isNull(p)) { allBlocksAreNulls = false; } if (allBlocksAreNulls) { result.appendNull(); continue position; } try { SpatialDisjoint.processCartesianPointDocValuesAndSource(result, p, leftBlock, rightBlock); } catch (IllegalArgumentException | IOException e) { warnings().registerException(e); result.appendNull(); } } return result.build(); } } @Override public String toString() { return "SpatialDisjointCartesianPointDocValuesAndSourceEvaluator[" + "left=" + left + ", right=" + right + "]"; } @Override public void close() { Releasables.closeExpectNoException(left, right); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
SpatialDisjointCartesianPointDocValuesAndSourceEvaluator
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/builditem/CombinedIndexBuildItem.java
{ "start": 1175, "end": 1617 }
class ____ extends SimpleBuildItem { private final IndexView index; private final IndexView computingIndex; public CombinedIndexBuildItem(IndexView index, IndexView computingIndex) { this.index = index; this.computingIndex = computingIndex; } public IndexView getIndex() { return index; } public IndexView getComputingIndex() { return computingIndex; } }
CombinedIndexBuildItem
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java
{ "start": 1219, "end": 3135 }
class ____ implements RequestDispatcher { private final Log logger = LogFactory.getLog(getClass()); private final String resource; /** * Create a new MockRequestDispatcher for the given resource. * @param resource the server resource to dispatch to, located at a * particular path or given by a particular name */ public MockRequestDispatcher(String resource) { Assert.notNull(resource, "Resource must not be null"); this.resource = resource; } @Override public void forward(ServletRequest request, ServletResponse response) { Assert.notNull(request, "Request must not be null"); Assert.notNull(response, "Response must not be null"); Assert.state(!response.isCommitted(), "Cannot perform forward - response is already committed"); getMockHttpServletResponse(response).setForwardedUrl(this.resource); if (logger.isDebugEnabled()) { logger.debug("MockRequestDispatcher: forwarding to [" + this.resource + "]"); } } @Override public void include(ServletRequest request, ServletResponse response) { Assert.notNull(request, "Request must not be null"); Assert.notNull(response, "Response must not be null"); getMockHttpServletResponse(response).addIncludedUrl(this.resource); if (logger.isDebugEnabled()) { logger.debug("MockRequestDispatcher: including [" + this.resource + "]"); } } /** * Obtain the underlying {@link MockHttpServletResponse}, unwrapping * {@link HttpServletResponseWrapper} decorators if necessary. */ protected MockHttpServletResponse getMockHttpServletResponse(ServletResponse response) { if (response instanceof MockHttpServletResponse mockResponse) { return mockResponse; } if (response instanceof HttpServletResponseWrapper wrapper) { return getMockHttpServletResponse(wrapper.getResponse()); } throw new IllegalArgumentException("MockRequestDispatcher requires MockHttpServletResponse"); } }
MockRequestDispatcher
java
elastic__elasticsearch
x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/TypeResolutionTests.java
{ "start": 862, "end": 1723 }
class ____ extends ESTestCase { public void testMulIntervalAndNumber() { Mul m = new Mul(EMPTY, L(1), randomYearInterval()); assertEquals(TypeResolution.TYPE_RESOLVED, m.typeResolved()); } public void testMulNumberAndInterval() { Mul m = new Mul(EMPTY, randomYearInterval(), L(1)); assertEquals(TypeResolution.TYPE_RESOLVED, m.typeResolved()); } public void testMulTypeResolution() throws Exception { Mul mul = new Mul(EMPTY, randomYearInterval(), randomYearInterval()); assertTrue(mul.typeResolved().unresolved()); } private static Literal randomYearInterval() { return L(new IntervalYearMonth(Period.ofMonths(randomInt(123)), INTERVAL_YEAR_TO_MONTH)); } private static Literal L(Object value) { return SqlTestUtils.literal(value); } }
TypeResolutionTests