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
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/graphs/LoadEntityGraphWithCompositeKeyCollectionsTest.java
{ "start": 1742, "end": 5423 }
class ____ { @AfterEach public void tearDown(EntityManagerFactoryScope scope) { scope.getEntityManagerFactory().unwrap( SessionFactory.class ).getSchemaManager().truncateMappedObjects(); scope.releaseEntityManagerFactory(); } @Test void testLoadFromEntityWithAllCollectionsFilled(EntityManagerFactoryScope scope) { Integer exerciseId = scope.fromTransaction( entityManager -> { Activity activityWithAnswersAndDocuments = createActivity(); ActivityAnswer activityAnswer1 = new ActivityAnswer( activityWithAnswersAndDocuments, "question_01", "answer_01" ); ActivityAnswer activityAnswer2 = new ActivityAnswer( activityWithAnswersAndDocuments, "question_02", "answer_02" ); Set<ActivityAnswer> answers = new HashSet<>(); answers.add( activityAnswer1 ); answers.add( activityAnswer2 ); activityWithAnswersAndDocuments.setAnswers( answers ); Set<ActivityDocument> documents = new HashSet<>(); documents.add( new ActivityDocument( activityWithAnswersAndDocuments, "question_01", "document_01" ) ); activityWithAnswersAndDocuments.setDocuments( documents ); entityManager.persist( activityWithAnswersAndDocuments ); return activityWithAnswersAndDocuments.getExercise().getId(); } ); scope.inTransaction( entityManager -> { List<Activity> activities = buildQuery( entityManager, exerciseId ).getResultList(); assertEquals( 1, activities.size() ); assertEquals( 2, activities.get( 0 ).getAnswers().size() ); assertEquals( 1, activities.get( 0 ).getDocuments().size() ); } ); } @Test void testLoadFromEntityWithOneEmptyCollection(EntityManagerFactoryScope scope) { Integer exerciseId = scope.fromTransaction( entityManager -> { Activity activityWithoutDocuments = createActivity(); ActivityAnswer activityAnswer1 = new ActivityAnswer( activityWithoutDocuments, "question_01", "answer_01" ); ActivityAnswer activityAnswer2 = new ActivityAnswer( activityWithoutDocuments, "question_02", "answer_02" ); Set<ActivityAnswer> answers = new HashSet<>(); answers.add( activityAnswer1 ); answers.add( activityAnswer2 ); activityWithoutDocuments.setAnswers( answers ); entityManager.persist( activityWithoutDocuments ); return activityWithoutDocuments.getExercise().getId(); } ); scope.inTransaction( entityManager -> { List<Activity> activities = buildQuery( entityManager, exerciseId ).getResultList(); assertEquals( 1, activities.size() ); assertEquals( 2, activities.get( 0 ).getAnswers().size() ); assertEquals( 0, activities.get( 0 ).getDocuments().size() ); } ); } private TypedQuery<Activity> buildQuery(EntityManager entityManager, Integer exerciseId) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Activity> query = builder.createQuery( Activity.class ); Root<Activity> root = query.from( Activity.class ); query.select( root ).where( builder.equal( root.get( "activityExerciseId" ).get( "exerciseId" ), exerciseId ) ); TypedQuery<Activity> typedQuery = entityManager.createQuery( query ); String graphType = GraphSemantic.LOAD.getJakartaHintName(); String entityGraphName = "with.collections"; typedQuery.setHint( graphType, entityManager.getEntityGraph( entityGraphName ) ); return typedQuery; } private Activity createActivity() { return new Activity( new Exercise( 1, "Pull up" ), "general-ref" ); } @Entity(name = "Activity") @Table(name = "activities") @NamedEntityGraph(name = "with.collections", attributeNodes = {@NamedAttributeNode(value = "answers"), @NamedAttributeNode(value = "documents")}) public static
LoadEntityGraphWithCompositeKeyCollectionsTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1800/Issue1871.java
{ "start": 306, "end": 688 }
class ____ extends TestCase { public void test_for_issue() throws Exception { UnwrapClass m = new UnwrapClass(); m.map = new HashMap(); m.name = "ljw"; m.map.put("a", "1"); m.map.put("b", "2"); String json = JSON.toJSONString(m, SerializerFeature.WriteClassName); System.out.println(json); } public static
Issue1871
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
{ "start": 62571, "end": 69168 }
class ____ create a parameterized type instance for. * @param typeArguments the types used for parameterization. * @return {@link ParameterizedType}. * @throws NullPointerException if {@code rawClass} is {@code null}. * @since 3.2 */ public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class<?> rawClass, final Type... typeArguments) { Objects.requireNonNull(rawClass, "rawClass"); final Type useOwner; if (rawClass.getEnclosingClass() == null) { Validate.isTrue(owner == null, "no owner allowed for top-level %s", rawClass); useOwner = null; } else if (owner == null) { useOwner = rawClass.getEnclosingClass(); } else { Validate.isTrue(isAssignable(owner, rawClass.getEnclosingClass()), "%s is invalid owner type for parameterized %s", owner, rawClass); useOwner = owner; } Validate.noNullElements(typeArguments, "null type argument at index %s"); Validate.isTrue(rawClass.getTypeParameters().length == typeArguments.length, "invalid number of type parameters specified: expected %d, got %d", rawClass.getTypeParameters().length, typeArguments.length); return new ParameterizedTypeImpl(rawClass, useOwner, typeArguments); } /** * Finds the mapping for {@code type} in {@code typeVarAssigns}. * * @param type the type to be replaced. * @param typeVarAssigns the map with type variables. * @return the replaced type. * @throws IllegalArgumentException if the type cannot be substituted. */ private static Type substituteTypeVariables(final Type type, final Map<TypeVariable<?>, Type> typeVarAssigns) { if (type instanceof TypeVariable<?> && typeVarAssigns != null) { final Type replacementType = typeVarAssigns.get(type); if (replacementType == null) { throw new IllegalArgumentException("missing assignment type for type variable " + type); } return replacementType; } return type; } /** * Formats a {@link TypeVariable} including its {@link GenericDeclaration}. * * @param typeVariable the type variable to create a String representation for, not {@code null}. * @return String. * @throws NullPointerException if {@code typeVariable} is {@code null}. * @since 3.2 */ public static String toLongString(final TypeVariable<?> typeVariable) { Objects.requireNonNull(typeVariable, "typeVariable"); final StringBuilder buf = new StringBuilder(); final GenericDeclaration d = typeVariable.getGenericDeclaration(); if (d instanceof Class<?>) { Class<?> c = (Class<?>) d; while (true) { if (c.getEnclosingClass() == null) { buf.insert(0, c.getName()); break; } buf.insert(0, c.getSimpleName()).insert(0, '.'); c = c.getEnclosingClass(); } } else if (d instanceof Type) { // not possible as of now buf.append(toString((Type) d)); } else { buf.append(d); } return buf.append(':').append(typeVariableToString(typeVariable)).toString(); } /** * Formats a given type as a Java-esque String. * * @param type the type to create a String representation for, not {@code null}. * @return String. * @throws NullPointerException if {@code type} is {@code null}. * @since 3.2 */ public static String toString(final Type type) { Objects.requireNonNull(type, "type"); if (type instanceof Class<?>) { return classToString((Class<?>) type); } if (type instanceof ParameterizedType) { return parameterizedTypeToString((ParameterizedType) type); } if (type instanceof WildcardType) { return wildcardTypeToString((WildcardType) type); } if (type instanceof TypeVariable<?>) { return typeVariableToString((TypeVariable<?>) type); } if (type instanceof GenericArrayType) { return genericArrayTypeToString((GenericArrayType) type); } throw new IllegalArgumentException(ObjectUtils.identityToString(type)); } /** * Determines whether or not specified types satisfy the bounds of their mapped type variables. When a type parameter extends another (such as * {@code <T, S extends T>}), uses another as a type parameter (such as {@code <T, S extends Comparable>>}), or otherwise depends on another type variable * to be specified, the dependencies must be included in {@code typeVarAssigns}. * * @param typeVariableMap specifies the potential types to be assigned to the type variables, not {@code null}. * @return whether or not the types can be assigned to their respective type variables. * @throws NullPointerException if {@code typeVariableMap} is {@code null}. */ public static boolean typesSatisfyVariables(final Map<TypeVariable<?>, Type> typeVariableMap) { Objects.requireNonNull(typeVariableMap, "typeVariableMap"); // all types must be assignable to all the bounds of their mapped // type variable. for (final Map.Entry<TypeVariable<?>, Type> entry : typeVariableMap.entrySet()) { final TypeVariable<?> typeVar = entry.getKey(); final Type type = entry.getValue(); for (final Type bound : getImplicitBounds(typeVar)) { if (!isAssignable(type, substituteTypeVariables(bound, typeVariableMap), typeVariableMap)) { return false; } } } return true; } /** * Formats a {@link TypeVariable} as a {@link String}. * * @param typeVariable {@link TypeVariable} to format. * @return String. */ private static String typeVariableToString(final TypeVariable<?> typeVariable) { final StringBuilder builder = new StringBuilder(typeVariable.getName()); final Type[] bounds = typeVariable.getBounds(); if (bounds.length > 0 && !(bounds.length == 1 && Object.class.equals(bounds[0]))) { // https://issues.apache.org/jira/projects/LANG/issues/LANG-1698 // There must be a better way to avoid a stack overflow on Java 17 and up. // Bounds are different in Java 17 and up where instead of Object you can get an
to
java
google__guava
guava/src/com/google/common/util/concurrent/FluentFuture.java
{ "start": 3656, "end": 19405 }
class ____<V extends @Nullable Object> extends FluentFuture<V> implements AbstractFuture.Trusted<V> { @CanIgnoreReturnValue @Override @ParametricNullness public final V get() throws InterruptedException, ExecutionException { return super.get(); } @CanIgnoreReturnValue @Override @ParametricNullness public final V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return super.get(timeout, unit); } @Override public final boolean isDone() { return super.isDone(); } @Override public final boolean isCancelled() { return super.isCancelled(); } @Override public final void addListener(Runnable listener, Executor executor) { super.addListener(listener, executor); } @CanIgnoreReturnValue @Override public final boolean cancel(boolean mayInterruptIfRunning) { return super.cancel(mayInterruptIfRunning); } } FluentFuture() {} /** * Converts the given {@code ListenableFuture} to an equivalent {@code FluentFuture}. * * <p>If the given {@code ListenableFuture} is already a {@code FluentFuture}, it is returned * directly. If not, it is wrapped in a {@code FluentFuture} that delegates all calls to the * original {@code ListenableFuture}. */ public static <V extends @Nullable Object> FluentFuture<V> from(ListenableFuture<V> future) { return future instanceof FluentFuture ? (FluentFuture<V>) future : new ForwardingFluentFuture<V>(future); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 28.0 */ @InlineMe( replacement = "checkNotNull(future)", staticImports = "com.google.common.base.Preconditions.checkNotNull") @Deprecated public static <V extends @Nullable Object> FluentFuture<V> from(FluentFuture<V> future) { return checkNotNull(future); } /** * Returns a {@code Future} whose result is taken from this {@code Future} or, if this {@code * Future} fails with the given {@code exceptionType}, from the result provided by the {@code * fallback}. {@link Function#apply} is not invoked until the primary input has failed, so if the * primary input succeeds, it is never invoked. If, during the invocation of {@code fallback}, an * exception is thrown, this exception is used as the result of the output {@code Future}. * * <p>Usage example: * * {@snippet : * // Falling back to a zero counter in case an exception happens when processing the RPC to fetch * // counters. * ListenableFuture<Integer> faultTolerantFuture = * fetchCounters().catching(FetchException.class, x -> 0, directExecutor()); * } * * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight * listeners are also applicable to heavyweight functions passed to this method. * * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#exceptionally}. It * can also serve some of the use cases of {@link java.util.concurrent.CompletableFuture#handle} * and {@link java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link * #transform}. * * @param exceptionType the exception type that triggers use of {@code fallback}. The exception * type is matched against the input's exception. "The input's exception" means the cause of * the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a * different kind of exception, that exception itself. To avoid hiding bugs and other * unrecoverable errors, callers should prefer more specific types, avoiding {@code * Throwable.class} in particular. * @param fallback the {@link Function} to be called if the input fails with the expected * exception type. The function's argument is the input's exception. "The input's exception" * means the cause of the {@link ExecutionException} thrown by {@code this.get()} or, if * {@code get()} throws a different kind of exception, that exception itself. * @param executor the executor that runs {@code fallback} if the input fails */ @J2ktIncompatible @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") public final <X extends Throwable> FluentFuture<V> catching( Class<X> exceptionType, Function<? super X, ? extends V> fallback, Executor executor) { return (FluentFuture<V>) Futures.catching(this, exceptionType, fallback, executor); } /** * Returns a {@code Future} whose result is taken from this {@code Future} or, if this {@code * Future} fails with the given {@code exceptionType}, from the result provided by the {@code * fallback}. {@link AsyncFunction#apply} is not invoked until the primary input has failed, so if * the primary input succeeds, it is never invoked. If, during the invocation of {@code fallback}, * an exception is thrown, this exception is used as the result of the output {@code Future}. * * <p>Usage examples: * * {@snippet : * // Falling back to a zero counter in case an exception happens when processing the RPC to fetch * // counters. * ListenableFuture<Integer> faultTolerantFuture = * fetchCounters().catchingAsync( * FetchException.class, x -> immediateFuture(0), directExecutor()); * } * * <p>The fallback can also choose to propagate the original exception when desired: * * {@snippet : * // Falling back to a zero counter only in case the exception was a * // TimeoutException. * ListenableFuture<Integer> faultTolerantFuture = * fetchCounters().catchingAsync( * FetchException.class, * e -> { * if (omitDataOnFetchFailure) { * return immediateFuture(0); * } * throw e; * }, * directExecutor()); * } * * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight * listeners are also applicable to heavyweight functions passed to this method. (Specifically, * {@code directExecutor} functions should avoid heavyweight operations inside {@code * AsyncFunction.apply}. Any heavyweight operations should occur in other threads responsible for * completing the returned {@code Future}.) * * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#exceptionally}. It * can also serve some of the use cases of {@link java.util.concurrent.CompletableFuture#handle} * and {@link java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link * #transform}. * * @param exceptionType the exception type that triggers use of {@code fallback}. The exception * type is matched against the input's exception. "The input's exception" means the cause of * the {@link ExecutionException} thrown by {@code this.get()} or, if {@code get()} throws a * different kind of exception, that exception itself. To avoid hiding bugs and other * unrecoverable errors, callers should prefer more specific types, avoiding {@code * Throwable.class} in particular. * @param fallback the {@link AsyncFunction} to be called if the input fails with the expected * exception type. The function's argument is the input's exception. "The input's exception" * means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if * {@code get()} throws a different kind of exception, that exception itself. * @param executor the executor that runs {@code fallback} if the input fails */ @J2ktIncompatible @Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class") public final <X extends Throwable> FluentFuture<V> catchingAsync( Class<X> exceptionType, AsyncFunction<? super X, ? extends V> fallback, Executor executor) { return (FluentFuture<V>) Futures.catchingAsync(this, exceptionType, fallback, executor); } /** * Returns a future that delegates to this future but will finish early (via a {@link * TimeoutException} wrapped in an {@link ExecutionException}) if the specified timeout expires. * If the timeout expires, not only will the output future finish, but also the input future * ({@code this}) will be cancelled and interrupted. * * @param timeout when to time out the future * @param scheduledExecutor The executor service to enforce the timeout. * @since 28.0 (but only since 33.4.0 in the Android flavor) */ @J2ktIncompatible @GwtIncompatible // ScheduledExecutorService public final FluentFuture<V> withTimeout( Duration timeout, ScheduledExecutorService scheduledExecutor) { return withTimeout(toNanosSaturated(timeout), TimeUnit.NANOSECONDS, scheduledExecutor); } /** * Returns a future that delegates to this future but will finish early (via a {@link * TimeoutException} wrapped in an {@link ExecutionException}) if the specified timeout expires. * If the timeout expires, not only will the output future finish, but also the input future * ({@code this}) will be cancelled and interrupted. * * @param timeout when to time out the future * @param unit the time unit of the time parameter * @param scheduledExecutor The executor service to enforce the timeout. */ @J2ktIncompatible @GwtIncompatible // ScheduledExecutorService @SuppressWarnings("GoodTime") // should accept a java.time.Duration public final FluentFuture<V> withTimeout( long timeout, TimeUnit unit, ScheduledExecutorService scheduledExecutor) { return (FluentFuture<V>) Futures.withTimeout(this, timeout, unit, scheduledExecutor); } /** * Returns a new {@code Future} whose result is asynchronously derived from the result of this * {@code Future}. If the input {@code Future} fails, the returned {@code Future} fails with the * same exception (and the function is not invoked). * * <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced * by applying the given {@code AsyncFunction} to the result of the original {@code Future}. * Example usage: * * {@snippet : * FluentFuture<RowKey> rowKeyFuture = FluentFuture.from(indexService.lookUp(query)); * ListenableFuture<QueryResult> queryFuture = * rowKeyFuture.transformAsync(dataService::readFuture, executor); * } * * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight * listeners are also applicable to heavyweight functions passed to this method. (Specifically, * {@code directExecutor} functions should avoid heavyweight operations inside {@code * AsyncFunction.apply}. Any heavyweight operations should occur in other threads responsible for * completing the returned {@code Future}.) * * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the * input future and that of the future returned by the chain function. That is, if the returned * {@code Future} is cancelled, it will attempt to cancel the other two, and if either of the * other two is cancelled, the returned {@code Future} will receive a callback in which it will * attempt to cancel itself. * * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#thenCompose} and * {@link java.util.concurrent.CompletableFuture#thenComposeAsync}. It can also serve some of the * use cases of {@link java.util.concurrent.CompletableFuture#handle} and {@link * java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link #catching}. * * @param function A function to transform the result of this future to the result of the output * future * @param executor Executor to run the function in. * @return A future that holds result of the function (if the input succeeded) or the original * input's failure (if not) */ public final <T extends @Nullable Object> FluentFuture<T> transformAsync( AsyncFunction<? super V, T> function, Executor executor) { return (FluentFuture<T>) Futures.transformAsync(this, function, executor); } /** * Returns a new {@code Future} whose result is derived from the result of this {@code Future}. If * this input {@code Future} fails, the returned {@code Future} fails with the same exception (and * the function is not invoked). Example usage: * * {@snippet : * ListenableFuture<List<Row>> rowsFuture = * queryFuture.transform(QueryResult::getRows, executor); * } * * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight * listeners are also applicable to heavyweight functions passed to this method. * * <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the * input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel * the input, and if the input is cancelled, the returned {@code Future} will receive a callback * in which it will attempt to cancel itself. * * <p>An example use of this method is to convert a serializable object returned from an RPC into * a POJO. * * <p>This method is similar to {@link java.util.concurrent.CompletableFuture#thenApply} and * {@link java.util.concurrent.CompletableFuture#thenApplyAsync}. It can also serve some of the * use cases of {@link java.util.concurrent.CompletableFuture#handle} and {@link * java.util.concurrent.CompletableFuture#handleAsync} when used along with {@link #catching}. * * @param function A Function to transform the results of this future to the results of the * returned future. * @param executor Executor to run the function in. * @return A future that holds result of the transformation. */ public final <T extends @Nullable Object> FluentFuture<T> transform( Function<? super V, T> function, Executor executor) { return (FluentFuture<T>) Futures.transform(this, function, executor); } /** * Registers separate success and failure callbacks to be run when this {@code Future}'s * computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the * computation is already complete, immediately. * * <p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of * callbacks, but any callback added through this method is guaranteed to be called once the * computation is complete. * * <p>Example: * * {@snippet : * future.addCallback( * new FutureCallback<QueryResult>() { * public void onSuccess(QueryResult result) { * storeInCache(result); * } * public void onFailure(Throwable t) { * reportError(t); * } * }, executor); * } * * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See * the discussion in the {@link #addListener} documentation. All its warnings about heavyweight * listeners are also applicable to heavyweight callbacks passed to this method. * * <p>For a more general
TrustedFuture
java
apache__camel
core/camel-management/src/test/java/org/apache/camel/management/ManagedRouteWithOnExceptionTest.java
{ "start": 1151, "end": 3136 }
class ____ extends ManagementTestSupport { @Test public void testShouldBeInstrumentedOk() throws Exception { getMockEndpoint("mock:error").expectedMessageCount(0); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Test public void testShouldBeInstrumentedKaboom() throws Exception { getMockEndpoint("mock:error").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(0); try { template.sendBody("direct:start", "Kaboom"); fail("Should have thrown an exception"); } catch (CamelExecutionException e) { // expected } assertMockEndpointsSatisfied(); } @Test public void testShouldBeInstrumentedOkAndKaboom() throws Exception { getMockEndpoint("mock:error").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); try { template.sendBody("direct:start", "Kaboom"); fail("Should have thrown an exception"); } catch (CamelExecutionException e) { // expected } assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .onException(Exception.class) .to("mock:error") .end() .delay(100) .choice() .when(body().isEqualTo("Kaboom")).throwException(new IllegalArgumentException("Kaboom")) .otherwise().to("mock:result") .end(); } }; } }
ManagedRouteWithOnExceptionTest
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/ClassUtils.java
{ "start": 30298, "end": 30642 }
class ____ or the empty String. * @since 3.7 * @see Class#getSimpleName() */ public static String getName(final Object object) { return getName(object, StringUtils.EMPTY); } /** * Null-safe version of {@code object.getClass().getSimpleName()} * * @param object the object for which to get the
name
java
google__dagger
javatests/dagger/functional/componentdependency/ComponentDependenciesTest.java
{ "start": 1927, "end": 2316 }
interface ____ { Builder dep(MergedOverride dep); TestOverrideComponent build(); } } @Test public void testPolymorphicOverridesStillCompiles() throws Exception { TestOverrideComponent component = DaggerComponentDependenciesTest_TestOverrideComponent.builder().dep(() -> "test").build(); assertThat(component.getString()).isEqualTo("test"); } }
Builder
java
micronaut-projects__micronaut-core
management/src/test/java/io/micronaut/management/health/indicator/diskspace/DiskSpaceIndicatorTest.java
{ "start": 594, "end": 1482 }
class ____ { @Test void diskSpaceHealthIndicatorViaConfiguration() { Consumer<ApplicationContext> healthBeansConsumer = context -> { assertTrue(context.containsBean(HealthEndpoint.class)); assertTrue(context.containsBean(DefaultHealthAggregator.class)); }; Map<String, Object> configuration = Map.of("endpoints.health.disk-space.enabled", StringUtils.FALSE); try (ApplicationContext context = ApplicationContext.run(configuration)) { healthBeansConsumer.accept(context); assertFalse(context.containsBean(DiskSpaceIndicator.class)); } // enabled by default try (ApplicationContext context = ApplicationContext.run()) { healthBeansConsumer.accept(context); assertTrue(context.containsBean(DiskSpaceIndicator.class)); } } }
DiskSpaceIndicatorTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit4/rules/Subclass2AppCtxRuleTests.java
{ "start": 1318, "end": 1392 }
class ____ { @Bean public String baz() { return "baz"; } } }
Config
java
google__guava
guava/src/com/google/common/collect/HashBiMap.java
{ "start": 14976, "end": 16257 }
class ____<T extends @Nullable Object> implements Iterator<T> { @Nullable BiEntry<K, V> next = firstInKeyInsertionOrder; @Nullable BiEntry<K, V> toRemove = null; int expectedModCount = modCount; int remaining = size(); @Override public boolean hasNext() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } return next != null && remaining > 0; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } // requireNonNull is safe because of the hasNext check. BiEntry<K, V> entry = requireNonNull(next); next = entry.nextInKeyInsertionOrder; toRemove = entry; remaining--; return output(entry); } @Override public void remove() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (toRemove == null) { throw new IllegalStateException("no calls to next() since the last call to remove()"); } delete(toRemove); expectedModCount = modCount; toRemove = null; } abstract T output(BiEntry<K, V> entry); } @Override public Set<K> keySet() { return new KeySet(); } private final
Itr
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conversion/numbers/Target.java
{ "start": 206, "end": 2375 }
class ____ { private String i; private String ii; private String d; private String dd; private String f; private String ff; private String l; private String ll; private String b; private String bb; private String complex1; private String complex2; private String bigDecimal1; private String bigInteger1; public String getI() { return i; } public void setI(String i) { this.i = i; } public String getIi() { return ii; } public void setIi(String ii) { this.ii = ii; } public String getD() { return d; } public void setD(String d) { this.d = d; } public String getDd() { return dd; } public void setDd(String dd) { this.dd = dd; } public String getF() { return f; } public void setF(String f) { this.f = f; } public String getFf() { return ff; } public void setFf(String ff) { this.ff = ff; } public String getL() { return l; } public void setL(String l) { this.l = l; } public String getLl() { return ll; } public void setLl(String ll) { this.ll = ll; } public String getB() { return b; } public void setB(String b) { this.b = b; } public String getBb() { return bb; } public void setBb(String bb) { this.bb = bb; } public String getComplex1() { return complex1; } public void setComplex1(String complex1) { this.complex1 = complex1; } public String getComplex2() { return complex2; } public void setComplex2(String complex2) { this.complex2 = complex2; } public String getBigDecimal1() { return bigDecimal1; } public void setBigDecimal1(String bigDecimal1) { this.bigDecimal1 = bigDecimal1; } public String getBigInteger1() { return bigInteger1; } public void setBigInteger1(String bigInteger1) { this.bigInteger1 = bigInteger1; } }
Target
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/builder/BuilderWithCreatorTest.java
{ "start": 2968, "end": 4633 }
class ____ { private final double value; @JsonCreator public DoubleCreatorBuilder(double v) { value = v; } public DoubleCreatorValue build() { return new DoubleCreatorValue(value); } } /* /********************************************************** /* Unit tests /********************************************************** */ private final ObjectMapper MAPPER = new ObjectMapper(); @Test public void testWithPropertiesCreator() throws Exception { final String json = a2q("{'a':1,'c':3,'b':2}"); PropertyCreatorValue value = MAPPER.readValue(json, PropertyCreatorValue.class); assertEquals(1, value.a); assertEquals(2, value.b); assertEquals(3, value.c); } @Test public void testWithDelegatingStringCreator() throws Exception { final int EXP = 139; IntCreatorValue value = MAPPER.readValue(String.valueOf(EXP), IntCreatorValue.class); assertEquals(EXP, value.value); } @Test public void testWithDelegatingIntCreator() throws Exception { final double EXP = -3.75; DoubleCreatorValue value = MAPPER.readValue(String.valueOf(EXP), DoubleCreatorValue.class); assertEquals(EXP, value.value); } @Test public void testWithDelegatingBooleanCreator() throws Exception { final boolean EXP = true; BooleanCreatorValue value = MAPPER.readValue(String.valueOf(EXP), BooleanCreatorValue.class); assertEquals(EXP, value.value); } }
DoubleCreatorBuilder
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/collection_in_constructor/CollectionInConstructorObjectFactory.java
{ "start": 813, "end": 1358 }
class ____ extends DefaultObjectFactory { private static final long serialVersionUID = -5912469844471984785L; @SuppressWarnings("unchecked") @Override public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) { if (type == Store4.class) { return (T) Store4.builder().id((Integer) constructorArgs.get(0)).isles((List<Aisle>) constructorArgs.get(1)) .build(); } return super.create(type, constructorArgTypes, constructorArgs); } }
CollectionInConstructorObjectFactory
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableJust.java
{ "start": 943, "end": 1405 }
class ____<T> extends Observable<T> implements ScalarSupplier<T> { private final T value; public ObservableJust(final T value) { this.value = value; } @Override protected void subscribeActual(Observer<? super T> observer) { ScalarDisposable<T> sd = new ScalarDisposable<>(observer, value); observer.onSubscribe(sd); sd.run(); } @Override public T get() { return value; } }
ObservableJust
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/store/StoreTests.java
{ "start": 6647, "end": 7803 }
class ____ extends FilterIndexInput { private final long corruptionPosition; CorruptibleInput(IndexInput in, long corruptionPosition) { super(in.toString(), in); this.corruptionPosition = corruptionPosition; } private static byte maybeCorruptionMask(boolean doCorrupt) { return (byte) ((doCorrupt ? 1 : 0) << between(0, Byte.SIZE - 1)); } @Override public byte readByte() throws IOException { return (byte) (super.readByte() ^ maybeCorruptionMask(in.getFilePointer() == corruptionPosition)); } @Override public void readBytes(byte[] b, int offset, int len) throws IOException { final var startPointer = in.getFilePointer(); super.readBytes(b, offset, len); if (startPointer <= corruptionPosition && corruptionPosition < in.getFilePointer()) { b[Math.toIntExact(offset + corruptionPosition - startPointer)] ^= maybeCorruptionMask(true); } } }
CorruptibleInput
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INode.java
{ "start": 2571, "end": 2684 }
class ____ common fields for file and * directory inodes. */ @InterfaceAudience.Private public abstract
containing
java
apache__dubbo
dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java
{ "start": 1995, "end": 11207 }
class ____ { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class); @Test @SuppressWarnings("unchecked") public void testClient() throws Throwable { // read server info from property if (PerformanceUtils.getProperty("server", null) == null) { logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911"); return; } final String server = System.getProperty("server", "127.0.0.1:9911"); final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER); final String serialization = PerformanceUtils.getProperty( Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization()); final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT); final int length = PerformanceUtils.getIntProperty("length", 1024); final int connections = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1); final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100); int r = PerformanceUtils.getIntProperty("runs", 10000); final int runs = r > 0 ? r : Integer.MAX_VALUE; final String onerror = PerformanceUtils.getProperty("onerror", "continue"); final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + "&timeout=" + timeout; // Create clients and build connections final ExchangeClient[] exchangeClients = new ExchangeClient[connections]; for (int i = 0; i < connections; i++) { // exchangeClients[i] = Exchangers.connect(url,handler); exchangeClients[i] = Exchangers.connect(url); } List<String> serverEnvironment = (List<String>) exchangeClients[0].request("environment").get(); List<String> serverScene = (List<String>) exchangeClients[0].request("scene").get(); // Create some data for test StringBuilder buf = new StringBuilder(length); for (int i = 0; i < length; i++) { buf.append('A'); } final String data = buf.toString(); // counters final AtomicLong count = new AtomicLong(); final AtomicLong error = new AtomicLong(); final AtomicLong time = new AtomicLong(); final AtomicLong all = new AtomicLong(); // Start multiple threads final CountDownLatch latch = new CountDownLatch(concurrent); for (int i = 0; i < concurrent; i++) { new Thread(new Runnable() { public void run() { try { AtomicInteger index = new AtomicInteger(); long init = System.currentTimeMillis(); for (int i = 0; i < runs; i++) { try { count.incrementAndGet(); ExchangeClient client = exchangeClients[index.getAndIncrement() % connections]; long start = System.currentTimeMillis(); String result = (String) client.request(data).get(); long end = System.currentTimeMillis(); if (!data.equals(result)) { throw new IllegalStateException("Invalid result " + result); } time.addAndGet(end - start); } catch (Exception e) { error.incrementAndGet(); e.printStackTrace(); if ("exit".equals(onerror)) { System.exit(-1); } else if ("break".equals(onerror)) { break; } else if ("sleep".equals(onerror)) { try { Thread.sleep(30000); } catch (InterruptedException e1) { } } } } all.addAndGet(System.currentTimeMillis() - init); } finally { latch.countDown(); } } }) .start(); } // Output, tps is not for accuracy, but it reflects the situation to a certain extent. new Thread(new Runnable() { public void run() { try { SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); long lastCount = count.get(); long sleepTime = 2000; long elapsd = sleepTime / 1000; boolean bfirst = true; while (latch.getCount() > 0) { long c = count.get() - lastCount; if (!bfirst) // The first time is inaccurate. logger.info("[" + dateFormat.format(new Date()) + "] count: " + count.get() + ", error: " + error.get() + ",tps:" + (c / elapsd)); bfirst = false; lastCount = count.get(); Thread.sleep(sleepTime); } } catch (Exception e) { e.printStackTrace(); } } }) .start(); latch.await(); for (ExchangeClient client : exchangeClients) { if (client.isConnected()) { client.close(); } } long total = count.get(); long failed = error.get(); long succeeded = total - failed; long elapsed = time.get(); long allElapsed = all.get(); long clientElapsed = allElapsed - elapsed; long art = 0; long qps = 0; long throughput = 0; if (elapsed > 0) { art = elapsed / succeeded; qps = concurrent * succeeded * 1000 / elapsed; throughput = concurrent * succeeded * length * 2 * 1000 / elapsed; } PerformanceUtils.printBorder(); PerformanceUtils.printHeader("Dubbo Remoting Performance Test Report"); PerformanceUtils.printBorder(); PerformanceUtils.printHeader("Test Environment"); PerformanceUtils.printSeparator(); for (String item : serverEnvironment) { PerformanceUtils.printBody("Server " + item); } PerformanceUtils.printSeparator(); List<String> clientEnvironment = PerformanceUtils.getEnvironment(); for (String item : clientEnvironment) { PerformanceUtils.printBody("Client " + item); } PerformanceUtils.printSeparator(); PerformanceUtils.printHeader("Test Scene"); PerformanceUtils.printSeparator(); for (String item : serverScene) { PerformanceUtils.printBody("Server " + item); } PerformanceUtils.printBody("Client Transporter: " + transporter); PerformanceUtils.printBody("Serialization: " + serialization); PerformanceUtils.printBody("Response Timeout: " + timeout + " ms"); PerformanceUtils.printBody("Data Length: " + length + " bytes"); PerformanceUtils.printBody("Client Shared Connections: " + connections); PerformanceUtils.printBody("Client Concurrent Threads: " + concurrent); PerformanceUtils.printBody("Run Times Per Thread: " + runs); PerformanceUtils.printSeparator(); PerformanceUtils.printHeader("Test Result"); PerformanceUtils.printSeparator(); PerformanceUtils.printBody( "Succeeded Requests: " + DecimalFormat.getIntegerInstance().format(succeeded)); PerformanceUtils.printBody("Failed Requests: " + failed); PerformanceUtils.printBody("Client Elapsed Time: " + clientElapsed + " ms"); PerformanceUtils.printBody("Average Response Time: " + art + " ms"); PerformanceUtils.printBody("Requests Per Second: " + qps + "/s"); PerformanceUtils.printBody( "Throughput Per Second: " + DecimalFormat.getIntegerInstance().format(throughput) + " bytes/s"); PerformanceUtils.printBorder(); } static
PerformanceClientTest
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableSequenceEqual.java
{ "start": 1984, "end": 2106 }
interface ____ { void drain(); void innerError(Throwable ex); } static final
EqualCoordinatorHelper
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/EqualsIncompatibleTypeTest.java
{ "start": 16901, "end": 17346 }
class ____ { boolean t(Stream<Integer> xs, String x) { // BUG: Diagnostic contains: return xs.anyMatch(x::equals); } } """) .doTest(); } @Test public void methodReference_comparableTypes_noFinding() { compilationHelper .addSourceLines( "Test.java", """ import java.util.stream.Stream;
Test
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReferenceValidation.java
{ "start": 6856, "end": 7578 }
class ____<REF extends INodeReference> implements Callable<Integer> { static final int BATCH_SIZE = 100_000; private final List<REF> references = new LinkedList<>(); private final AtomicInteger errorCount; Task(Iterator<REF> i, AtomicInteger errorCount) { for(int n = 0; i.hasNext() && n < BATCH_SIZE; n++) { references.add(i.next()); i.remove(); } this.errorCount = errorCount; } @Override public Integer call() throws Exception { for (final REF ref : references) { try { ref.assertReferences(); } catch (Throwable t) { printError(errorCount, "%s", t); } } return references.size(); } } }
Task
java
apache__flink
flink-connectors/flink-hadoop-compatibility/src/test/java/org/apache/flink/test/hadoopcompatibility/mapred/HadoopReduceFunctionITCase.java
{ "start": 2338, "end": 6042 }
class ____ extends MultipleProgramsTestBase { @TestTemplate void testStandardGrouping(@TempDir Path tempFolder) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setRuntimeMode(RuntimeExecutionMode.BATCH); DataStream<Tuple2<IntWritable, Text>> ds = HadoopTestData.getKVPairDataStream(env).map(new Mapper1()); DataStream<Tuple2<IntWritable, IntWritable>> commentCnts = ds.keyBy(x -> x.f0) .window(GlobalWindows.createWithEndOfStreamTrigger()) .apply(new HadoopReducerWrappedFunction<>(new CommentCntReducer())); String resultPath = tempFolder.toUri().toString(); commentCnts.sinkTo( FileSink.forRowFormat( new org.apache.flink.core.fs.Path(resultPath), new SimpleStringEncoder<Tuple2<IntWritable, IntWritable>>()) .build()); env.execute(); String expected = "(0,0)\n" + "(1,3)\n" + "(2,5)\n" + "(3,5)\n" + "(4,2)\n"; compareResultsByLinesInMemory(expected, resultPath); } @TestTemplate void testUngroupedHadoopReducer(@TempDir Path tempFolder) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setRuntimeMode(RuntimeExecutionMode.BATCH); DataStream<Tuple2<IntWritable, Text>> ds = HadoopTestData.getKVPairDataStream(env); SingleOutputStreamOperator<Tuple2<IntWritable, IntWritable>> commentCnts = ds.windowAll(GlobalWindows.createWithEndOfStreamTrigger()) .apply(new HadoopReducerWrappedFunction<>(new AllCommentCntReducer())); String resultPath = tempFolder.toUri().toString(); commentCnts.sinkTo( FileSink.forRowFormat( new org.apache.flink.core.fs.Path(resultPath), new SimpleStringEncoder<Tuple2<IntWritable, IntWritable>>()) .build()); env.execute(); String expected = "(42,15)\n"; compareResultsByLinesInMemory(expected, resultPath); } @TestTemplate void testConfigurationViaJobConf(@TempDir Path tempFolder) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setRuntimeMode(RuntimeExecutionMode.BATCH); JobConf conf = new JobConf(); conf.set("my.cntPrefix", "Hello"); DataStream<Tuple2<IntWritable, Text>> ds = HadoopTestData.getKVPairDataStream(env).map(new Mapper2()); DataStream<Tuple2<IntWritable, IntWritable>> helloCnts = ds.keyBy(x -> x.f0) .window(GlobalWindows.createWithEndOfStreamTrigger()) .apply( new HadoopReducerWrappedFunction<>( new ConfigurableCntReducer(), conf)); String resultPath = tempFolder.toUri().toString(); helloCnts.sinkTo( FileSink.forRowFormat( new org.apache.flink.core.fs.Path(resultPath), new SimpleStringEncoder<Tuple2<IntWritable, IntWritable>>()) .build()); env.execute(); String expected = "(0,0)\n" + "(1,0)\n" + "(2,1)\n" + "(3,1)\n" + "(4,1)\n"; compareResultsByLinesInMemory(expected, resultPath); } /** A {@link Reducer} to sum counts. */ public static
HadoopReduceFunctionITCase
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/ClassNameScopeOverrideTest.java
{ "start": 562, "end": 1415 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(EchoResource.class, HelloClientWithBaseUri.class)) .withConfigurationResource("classname-scope-test-application.properties"); @RestClient HelloClientWithBaseUri client; @Test void shouldHaveDependentScope() { BeanManager beanManager = Arc.container().beanManager(); Set<Bean<?>> beans = beanManager.getBeans(HelloClientWithBaseUri.class, RestClient.LITERAL); Bean<?> resolvedBean = beanManager.resolve(beans); assertThat(resolvedBean.getScope()).isEqualTo(Dependent.class); } @Test void shouldConnect() { assertThat(client.echo("Bob")).isEqualTo("hello, Bob!!!"); } }
ClassNameScopeOverrideTest
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/ServiceRegistry.java
{ "start": 1800, "end": 2014 }
interface ____ { Class<? extends org.hibernate.service.Service> role(); Class<? extends org.hibernate.service.Service> impl(); } /** * A Java service loadable via {@link java.util.ServiceLoader} */ @
Service
java
quarkusio__quarkus
devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusBuildTask.java
{ "start": 1937, "end": 12610 }
class ____ extends QuarkusTaskWithExtensionView { private static final String QUARKUS_BUILD_DIR = "quarkus-build"; private static final String QUARKUS_BUILD_GEN_DIR = QUARKUS_BUILD_DIR + "/gen"; private static final String QUARKUS_BUILD_APP_DIR = QUARKUS_BUILD_DIR + "/app"; private static final String QUARKUS_BUILD_DEP_DIR = QUARKUS_BUILD_DIR + "/dep"; static final String QUARKUS_ARTIFACT_PROPERTIES = "quarkus-artifact.properties"; static final String NATIVE_SOURCES = "native-sources"; @Internal public abstract Property<ForcedPropertieBuildService> getAdditionalForcedProperties(); private final Provider<Boolean> preservesJarTimestamps; QuarkusBuildTask(String description, boolean compatible) { super(description, compatible); this.preservesJarTimestamps = getProject().getTasks() .named(JavaPlugin.JAR_TASK_NAME, Jar.class) .map(Jar::isPreserveFileTimestamps) .orElse(getProject().getProviders().provider(() -> false)); } @Inject protected abstract FileSystemOperations getFileSystemOperations(); @Classpath public FileCollection getClasspath() { return classpath; } private FileCollection classpath = getProject().getObjects().fileCollection(); public void setCompileClasspath(FileCollection compileClasspath) { this.classpath = compileClasspath; } @Input public abstract MapProperty<String, String> getCachingRelevantInput(); @Input public abstract Property<Boolean> getJarEnabled(); @Input public abstract Property<Boolean> getNativeEnabled(); @Input public abstract Property<Boolean> getNativeSourcesOnly(); @Internal public abstract Property<String> getRunnerSuffix(); @Internal public abstract Property<String> getRunnerName(); @Internal public abstract Property<Path> getOutputDirectory(); @Input public abstract Property<PackageConfig.JarConfig.JarType> getJarType(); PackageConfig.JarConfig.JarType jarType() { return getJarType().get(); } boolean jarEnabled() { return getJarEnabled().get(); } boolean nativeEnabled() { return getNativeEnabled().get(); } boolean nativeSourcesOnly() { return getNativeSourcesOnly().get(); } Path gradleBuildDir() { return buildDir.toPath(); } Path genBuildDir() { return gradleBuildDir().resolve(QUARKUS_BUILD_GEN_DIR); } Path appBuildDir() { return gradleBuildDir().resolve(QUARKUS_BUILD_APP_DIR); } Path depBuildDir() { return gradleBuildDir().resolve(QUARKUS_BUILD_DEP_DIR); } File artifactProperties() { return new File(buildDir, QUARKUS_ARTIFACT_PROPERTIES); } File nativeSources() { return new File(buildDir, NATIVE_SOURCES); } /** * "final" location of the "fast-jar". */ File fastJar() { return new File(buildDir, outputDirectory()); } /** * "final" location of the "uber-jar". */ File runnerJar() { return new File(buildDir, runnerJarFileName()); } /** * "final" location of the "native" runner. */ File nativeRunner() { return new File(buildDir, nativeRunnerFileName()); } String runnerJarFileName() { return runnerName() + ".jar"; } String nativeRunnerFileName() { return runnerName(); } String runnerName() { return runnerBaseName() + runnerSuffix(); } String nativeImageSourceJarDirName() { return runnerBaseName() + "-native-image-source-jar"; } String runnerBaseName() { return getRunnerName().get(); } String outputDirectory() { return getOutputDirectory().get().toString(); } private String runnerSuffix() { return getRunnerSuffix().get(); } @InputFile @PathSensitive(PathSensitivity.RELATIVE) public abstract RegularFileProperty getApplicationModel(); ApplicationModel resolveAppModelForBuild() { try { return ToolingUtils.deserializeAppModel(getApplicationModel().get().getAsFile().toPath()); } catch (IOException e) { throw new RuntimeException(e); } } /** * Runs the Quarkus-build in the "well known" location, Gradle's {@code build/} directory. * * <p> * It would be easier to run the Quarkus-build directly in {@code build/quarkus-build/gen} to have a "clean * target directory", but that breaks already existing Gradle builds for users, which have for example * {@code Dockerfile}s that rely on the fact that build artifacts are present in {@code build/}. * * <p> * This requires this method to * <ol> * <li>"properly" clean the directories that are going to be populated by the Quarkus build, then * <li>run the Quarkus build with the target directory {@code build/} and then * <li>populate the * </ol> */ @SuppressWarnings("deprecation") // legacy JAR void generateBuild() { Path buildDir = gradleBuildDir(); Path genDir = genBuildDir(); if (nativeEnabled()) { if (nativeSourcesOnly()) { getLogger().info("Building Quarkus app for native (sources only) packaging in {}", genDir); } else { getLogger().info("Building Quarkus app for native packaging in {}", genDir); } } else { getLogger().info("Building Quarkus app for JAR type {} in {}", jarType(), genDir); } // Need to delete app-cds.jsa specially, because it's usually read-only and Gradle's delete file-system // operation doesn't delete "read only" files :( deleteFileIfExists(genDir.resolve(outputDirectory()).resolve("app-cds.jsa")); getFileSystemOperations().delete(delete -> { // Caching and "up-to-date" checks depend on the inputs, this 'delete()' should ensure that the up-to-date // checks work against "clean" outputs, considering that the outputs depend on the package-type. delete.delete(genDir); // Delete directories inside Gradle's build/ dir that are going to be populated by the Quarkus build. if (nativeEnabled()) { if (jarEnabled()) { throw QuarkusBuild.nativeAndJar(); } delete.delete(fastJar()); } else if (jarEnabled()) { switch (jarType()) { case FAST_JAR -> { delete.delete(buildDir.resolve(nativeImageSourceJarDirName())); delete.delete(fastJar()); } case LEGACY_JAR -> delete.delete(buildDir.resolve("lib")); case MUTABLE_JAR, UBER_JAR -> { } } } }); ApplicationModel appModel = resolveAppModelForBuild(); Map<String, String> quarkusProperties = effectiveProvider() .buildEffectiveConfiguration(appModel, getAdditionalForcedProperties().get().getProperties()) .getQuarkusValues(); if (nativeEnabled()) { if (nativeSourcesOnly()) { getLogger().info("Starting Quarkus application build for native (sources only) packaging"); } else { getLogger().info("Starting Quarkus application build for native packaging"); } } else { getLogger().info("Starting Quarkus application build for JAR type {}", jarType()); } if (getLogger().isEnabled(LogLevel.INFO)) { getLogger().info("Effective properties: {}", quarkusProperties.entrySet().stream() .map(Object::toString) .sorted() .collect(Collectors.joining("\n ", "\n ", ""))); } WorkQueue workQueue = workQueue(quarkusProperties, getExtensionView().getBuildForkOptions().get()); workQueue.submit(BuildWorker.class, params -> { params.getBuildSystemProperties().putAll(buildSystemProperties(appModel.getAppArtifact(), quarkusProperties)); params.getBaseName().set(getExtensionView().getFinalName()); params.getTargetDirectory().set(buildDir.toFile()); params.getAppModel().set(appModel); params.getGradleVersion().set(GradleVersion.current().getVersion()); }); workQueue.await(); // Copy built artifacts from `build/` into `build/quarkus-build/gen/` getFileSystemOperations().copy(copy -> { copy.from(buildDir); copy.into(genDir); copy.eachFile(new CopyActionDeleteNonWriteableTarget(genDir)); if (nativeEnabled()) { if (jarEnabled()) { throw QuarkusBuild.nativeAndJar(); } if (nativeSourcesOnly()) { copy.include(QUARKUS_ARTIFACT_PROPERTIES); copy.include(nativeImageSourceJarDirName() + "/**"); } else { copy.include(nativeRunnerFileName()); copy.include(nativeImageSourceJarDirName() + "/**"); copy.include(outputDirectory() + "/**"); copy.include(QUARKUS_ARTIFACT_PROPERTIES); } } else if (jarEnabled()) { switch (jarType()) { case FAST_JAR -> { copy.include(outputDirectory() + "/**"); copy.include(QUARKUS_ARTIFACT_PROPERTIES); } case LEGACY_JAR -> { copy.include("lib/**"); copy.include(QUARKUS_ARTIFACT_PROPERTIES); copy.include(runnerJarFileName()); } case MUTABLE_JAR, UBER_JAR -> { copy.include(QUARKUS_ARTIFACT_PROPERTIES); copy.include(runnerJarFileName()); } } } }); } void abort(String message, Object... args) { getLogger().warn(message, args); getProject().getTasks().stream() .filter(t -> t != this) .filter(t -> !t.getState().getExecuted()).forEach(t -> { t.setEnabled(false); }); throw new StopExecutionException(); } public static final
QuarkusBuildTask
java
apache__camel
components/camel-crypto-pgp/src/main/java/org/apache/camel/converter/crypto/PGPSecretKeyAndPrivateKeyAndUserId.java
{ "start": 1021, "end": 1626 }
class ____ { private final PGPSecretKey secretKey; private final PGPPrivateKey privateKey; private final String userId; public PGPSecretKeyAndPrivateKeyAndUserId(PGPSecretKey secretKey, PGPPrivateKey privateKey, String userId) { this.secretKey = secretKey; this.privateKey = privateKey; this.userId = userId; } public PGPSecretKey getSecretKey() { return secretKey; } public PGPPrivateKey getPrivateKey() { return privateKey; } public String getUserId() { return userId; } }
PGPSecretKeyAndPrivateKeyAndUserId
java
quarkusio__quarkus
extensions/hibernate-search-orm-elasticsearch/deployment/src/main/java/io/quarkus/hibernate/search/orm/elasticsearch/deployment/HibernateSearchManagementEnabled.java
{ "start": 310, "end": 633 }
class ____ extends HibernateSearchEnabled { HibernateSearchManagementEnabled(HibernateSearchElasticsearchBuildTimeConfig config) { super(config); } @Override public boolean getAsBoolean() { return super.getAsBoolean() && config.management().enabled(); } }
HibernateSearchManagementEnabled
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/expression/Attribute.java
{ "start": 1960, "end": 9900 }
class ____ equality of the contained attribute ignores the {@link Attribute#id()}. Useful when we want to create new * attributes and want to avoid duplicates. Because we assign unique ids on creation, a normal equality check would always fail when * we create the "same" attribute again. * <p> * C.f. {@link AttributeMap} (and its contained wrapper class) which does the exact opposite: ignores everything but the id by * using {@link Attribute#semanticEquals(Expression)}. */ public record IdIgnoringWrapper(Attribute inner) { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Attribute otherAttribute = ((IdIgnoringWrapper) o).inner(); return inner().equals(otherAttribute, true); } @Override public int hashCode() { return inner().hashCode(true); } } public IdIgnoringWrapper ignoreId() { return new IdIgnoringWrapper(this); } /** * Changing this will break bwc with 8.15, see {@link FieldAttribute#fieldName()}. */ public static final String SYNTHETIC_ATTRIBUTE_NAME_PREFIX = "$$"; public static final String SYNTHETIC_ATTRIBUTE_NAME_SEPARATOR = "$"; private static final TransportVersion ESQL_QUALIFIERS_IN_ATTRIBUTES = TransportVersion.fromName("esql_qualifiers_in_attributes"); // can the attr be null private final Nullability nullability; private final String qualifier; public Attribute(Source source, String name, @Nullable NameId id) { this(source, name, Nullability.TRUE, id); } public Attribute(Source source, @Nullable String qualifier, String name, @Nullable NameId id) { this(source, qualifier, name, Nullability.TRUE, id); } public Attribute(Source source, String name, Nullability nullability, @Nullable NameId id) { this(source, null, name, nullability, id); } public Attribute(Source source, @Nullable String qualifier, String name, Nullability nullability, @Nullable NameId id) { this(source, qualifier, name, nullability, id, false); } public Attribute(Source source, String name, Nullability nullability, @Nullable NameId id, boolean synthetic) { this(source, null, name, nullability, id, synthetic); } public Attribute( Source source, @Nullable String qualifier, String name, Nullability nullability, @Nullable NameId id, boolean synthetic ) { super(source, name, emptyList(), id, synthetic); this.qualifier = qualifier; this.nullability = nullability; } public static String rawTemporaryName(String... parts) { var name = String.join(SYNTHETIC_ATTRIBUTE_NAME_SEPARATOR, parts); return name.isEmpty() || name.startsWith(SYNTHETIC_ATTRIBUTE_NAME_PREFIX) ? name : SYNTHETIC_ATTRIBUTE_NAME_PREFIX + name; } @Override public final Expression replaceChildren(List<Expression> newChildren) { throw new UnsupportedOperationException("this type of node doesn't have any children to replace"); } public String qualifier() { return qualifier; } public String qualifiedName() { return qualifier != null ? "[" + qualifier + "].[" + name() + "]" : name(); } @Override public Nullability nullable() { return nullability; } @Override public AttributeSet references() { return AttributeSet.of(this); } public Attribute withLocation(Source source) { return Objects.equals(source(), source) ? this : clone(source, qualifier(), name(), dataType(), nullable(), id(), synthetic()); } public Attribute withQualifier(String qualifier) { return Objects.equals(qualifier, qualifier) ? this : clone(source(), qualifier, name(), dataType(), nullable(), id(), synthetic()); } public Attribute withName(String name) { return Objects.equals(name(), name) ? this : clone(source(), qualifier(), name, dataType(), nullable(), id(), synthetic()); } public Attribute withNullability(Nullability nullability) { return Objects.equals(nullable(), nullability) ? this : clone(source(), qualifier(), name(), dataType(), nullability, id(), synthetic()); } public Attribute withId(NameId id) { return clone(source(), qualifier(), name(), dataType(), nullable(), id, synthetic()); } public Attribute withDataType(DataType type) { return Objects.equals(dataType(), type) ? this : clone(source(), qualifier(), name(), type, nullable(), id(), synthetic()); } protected abstract Attribute clone( Source source, String qualifier, String name, DataType type, Nullability nullability, NameId id, boolean synthetic ); @Override public Attribute toAttribute() { return this; } @Override public int semanticHash() { return id().hashCode(); } @Override public boolean semanticEquals(Expression other) { return other instanceof Attribute otherAttr && id().equals(otherAttr.id()); } @Override protected Expression canonicalize() { return clone(Source.EMPTY, qualifier(), name(), dataType(), nullability, id(), synthetic()); } @Override protected int innerHashCode(boolean ignoreIds) { return Objects.hash(super.innerHashCode(ignoreIds), qualifier, nullability); } @Override protected boolean innerEquals(Object o, boolean ignoreIds) { var other = (Attribute) o; return super.innerEquals(other, ignoreIds) && Objects.equals(qualifier, other.qualifier) && Objects.equals(nullability, other.nullability); } @Override public String toString() { return qualifiedName() + "{" + label() + (synthetic() ? "$" : "") + "}" + "#" + id(); } @Override public String nodeString() { return toString(); } protected abstract String label(); /** * Compares the size and datatypes of two lists of attributes for equality. */ public static boolean dataTypeEquals(List<Attribute> left, List<Attribute> right) { if (left.size() != right.size()) { return false; } for (int i = 0; i < left.size(); i++) { if (left.get(i).dataType() != right.get(i).dataType()) { return false; } } return true; } /** * @return true if the attribute represents a TSDB dimension type */ public abstract boolean isDimension(); /** * @return true if the attribute represents a TSDB metric type */ public abstract boolean isMetric(); protected void checkAndSerializeQualifier(PlanStreamOutput out, TransportVersion version) throws IOException { if (version.supports(ESQL_QUALIFIERS_IN_ATTRIBUTES)) { out.writeOptionalCachedString(qualifier()); } else if (qualifier() != null) { // Non-null qualifier means the query specifically defined one. Old nodes don't know what to do with it and just writing // null would lose information and lead to undefined, likely invalid queries. // IllegalArgumentException returns a 400 to the user, which is what we want here. throw new IllegalArgumentException("Trying to serialize an Attribute with a qualifier to an old node"); } } protected static String readQualifier(PlanStreamInput in, TransportVersion version) throws IOException { if (version.supports(ESQL_QUALIFIERS_IN_ATTRIBUTES)) { return in.readOptionalCachedString(); } return null; } }
where
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FileToFtpsWithFtpClientConfigRefIT.java
{ "start": 1373, "end": 2569 }
class ____ extends FtpsServerExplicitSSLWithoutClientAuthTestSupport { @BindToRegistry("ftpsClient") private final FTPSClient client = new FTPSClient("SSLv3"); @BindToRegistry("ftpsClientIn") private final FTPSClient client1 = new FTPSClient("SSLv3"); private String getFtpUrl(boolean in) { return "ftps://admin@localhost:{{ftp.server.port}}/tmp2/camel?password=admin&initialDelay=2000&ftpClient=#ftpsClient" + (in ? "In" : "") + "&disableSecureDataChannelDefaults=true&delete=true"; } @Disabled("CAMEL-16784:Disable testFromFileToFtp tests") @Test public void testFromFileToFtp() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(2); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("file:src/test/data?noop=true").log("Putting ${file:name}").to(getFtpUrl(false)); from(getFtpUrl(true)).to("mock:result"); } }; } }
FileToFtpsWithFtpClientConfigRefIT
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/observers/SerializedObserver.java
{ "start": 1506, "end": 6143 }
class ____<T> implements Observer<T>, Disposable { final Observer<? super T> downstream; final boolean delayError; static final int QUEUE_LINK_SIZE = 4; Disposable upstream; boolean emitting; AppendOnlyLinkedArrayList<Object> queue; volatile boolean done; /** * Construct a {@code SerializedObserver} by wrapping the given actual {@link Observer}. * @param downstream the actual {@code Observer}, not {@code null} (not verified) */ public SerializedObserver(@NonNull Observer<? super T> downstream) { this(downstream, false); } /** * Construct a SerializedObserver by wrapping the given actual {@link Observer} and * optionally delaying the errors till all regular values have been emitted * from the internal buffer. * @param actual the actual {@code Observer}, not {@code null} (not verified) * @param delayError if {@code true}, errors are emitted after regular values have been emitted */ public SerializedObserver(@NonNull Observer<? super T> actual, boolean delayError) { this.downstream = actual; this.delayError = delayError; } @Override public void onSubscribe(@NonNull Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { this.upstream = d; downstream.onSubscribe(this); } } @Override public void dispose() { done = true; upstream.dispose(); } @Override public boolean isDisposed() { return upstream.isDisposed(); } @Override public void onNext(@NonNull T t) { if (done) { return; } if (t == null) { upstream.dispose(); onError(ExceptionHelper.createNullPointerException("onNext called with a null value.")); return; } synchronized (this) { if (done) { return; } if (emitting) { AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(QUEUE_LINK_SIZE); queue = q; } q.add(NotificationLite.next(t)); return; } emitting = true; } downstream.onNext(t); emitLoop(); } @Override public void onError(@NonNull Throwable t) { if (done) { RxJavaPlugins.onError(t); return; } boolean reportError; synchronized (this) { if (done) { reportError = true; } else if (emitting) { done = true; AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(QUEUE_LINK_SIZE); queue = q; } Object err = NotificationLite.error(t); if (delayError) { q.add(err); } else { q.setFirst(err); } return; } else { done = true; emitting = true; reportError = false; } } if (reportError) { RxJavaPlugins.onError(t); return; } downstream.onError(t); // no need to loop because this onError is the last event } @Override public void onComplete() { if (done) { return; } synchronized (this) { if (done) { return; } if (emitting) { AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(QUEUE_LINK_SIZE); queue = q; } q.add(NotificationLite.complete()); return; } done = true; emitting = true; } downstream.onComplete(); // no need to loop because this onComplete is the last event } void emitLoop() { for (;;) { AppendOnlyLinkedArrayList<Object> q; synchronized (this) { q = queue; if (q == null) { emitting = false; return; } queue = null; } if (q.accept(downstream)) { return; } } } }
SerializedObserver
java
apache__camel
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/annotation/InheritanceTest.java
{ "start": 1077, "end": 1422 }
class ____ extends AdviceRouteTest { @Test void shouldInheritTheAnnotation() throws Exception { mock.expectedBodiesReceived("Hello Will!"); String result = template.requestBody((Object) null, String.class); mock.assertIsSatisfied(); assertEquals("Hello Will!", result); } @Nested
InheritanceTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/collection/EmbeddableWithManyToMany_HHH_11302_Test.java
{ "start": 1023, "end": 1333 }
class ____ extends AbstractEmbeddableWithManyToManyTest { @Override protected void addAnnotatedClasses(MetadataSources metadataSources) { metadataSources.addAnnotatedClasses( ContactType.class, Person.class ); } @Entity @Table(name = "CONTACTTYPE") public static
EmbeddableWithManyToMany_HHH_11302_Test
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/ParallelCollect.java
{ "start": 2896, "end": 4856 }
class ____<T, C> extends Operators.BaseFluxToMonoOperator<T, C> { final BiConsumer<? super C, ? super T> collector; @Nullable C collection; boolean done; ParallelCollectSubscriber(CoreSubscriber<? super C> subscriber, C initialValue, BiConsumer<? super C, ? super T> collector) { super(subscriber); this.collection = initialValue; this.collector = collector; } @Override public void onNext(T t) { if (done) { Operators.onNextDropped(t, actual.currentContext()); return; } try { synchronized (this) { final C collection = this.collection; if (collection != null) { collector.accept(collection, t); } } } catch (Throwable ex) { onError(Operators.onOperatorError(this.s, ex, t, actual.currentContext())); } } @Override public void onError(Throwable t) { if (done) { Operators.onErrorDropped(t, actual.currentContext()); return; } done = true; final C c; synchronized (this) { c = collection; collection = null; } if (c == null) { return; } Operators.onDiscard(c, actual.currentContext()); actual.onError(t); } @Override public void onComplete() { if (done) { return; } done = true; completePossiblyEmpty(); } @Override public void cancel() { s.cancel(); final C c; synchronized (this) { c = collection; collection = null; } if (c != null) { Operators.onDiscard(c, actual.currentContext()); } } @Override @Nullable C accumulatedValue() { final C c; synchronized (this) { c = collection; collection = null; } return c; } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; if (key == Attr.TERMINATED) return done; if (key == Attr.CANCELLED) return collection == null && !done; return super.scanUnsafe(key); } } }
ParallelCollectSubscriber
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/intg/AdditionalMappingContributorTests.java
{ "start": 7786, "end": 8154 }
class ____ implements AdditionalMappingContributor { @Override public void contribute( AdditionalMappingContributions contributions, InFlightMetadataCollector metadata, ResourceStreamLocator resourceStreamLocator, MetadataBuildingContext buildingContext) { contributions.contributeEntity( Entity2.class ); } } public static
ClassContributorImpl
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/authorization/method/AuthorizationMethodPointcutsTests.java
{ "start": 4333, "end": 4455 }
interface ____ { @MyAnnotation String methodOne(String paramOne); } public static
MethodAnnotationControllerInterface
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/ListShareGroupOffsetsResult.java
{ "start": 1242, "end": 3301 }
class ____ { private final Map<String, KafkaFuture<Map<TopicPartition, SharePartitionOffsetInfo>>> futures; ListShareGroupOffsetsResult(final Map<CoordinatorKey, KafkaFuture<Map<TopicPartition, SharePartitionOffsetInfo>>> futures) { this.futures = futures.entrySet().stream() .collect(Collectors.toMap(e -> e.getKey().idValue, Map.Entry::getValue)); } /** * Return the future when the requests for all groups succeed. * * @return Future which yields all {@code Map<String, Map<TopicPartition, SharePartitionOffsetInfo>>} objects, if requests for all the groups succeed. */ public KafkaFuture<Map<String, Map<TopicPartition, SharePartitionOffsetInfo>>> all() { return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture<?>[0])).thenApply( nil -> { Map<String, Map<TopicPartition, SharePartitionOffsetInfo>> offsets = new HashMap<>(futures.size()); futures.forEach((groupId, future) -> { try { offsets.put(groupId, future.get()); } catch (InterruptedException | ExecutionException e) { // This should be unreachable, since the KafkaFuture#allOf already ensured // that all the futures completed successfully. throw new RuntimeException(e); } }); return offsets; }); } /** * Return a future which yields a map of topic partitions to offsets for the specified group. If the group doesn't * have offset information for a specific partition, the corresponding value in the returned map will be null. */ public KafkaFuture<Map<TopicPartition, SharePartitionOffsetInfo>> partitionsToOffsetInfo(String groupId) { if (!futures.containsKey(groupId)) { throw new IllegalArgumentException("Group ID not found: " + groupId); } return futures.get(groupId); } }
ListShareGroupOffsetsResult
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/annotation/AnnotationBeanWiringInfoResolverTests.java
{ "start": 2210, "end": 2754 }
class ____ even when autowiring is NO").isNotNull(); assertThat(info.indicatesAutowiring()).isFalse(); assertThat(info.getBeanName()).isEqualTo(WirelessSoap.class.getName()); } @Test void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitlyAndCustomBeanName() { AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver(); BeanWiringInfo info = resolver.resolveWiringInfo(new NamedWirelessSoap()); assertThat(info).as("Must *not* be returning null for an @Configurable
instance
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_array_string.java
{ "start": 305, "end": 1105 }
class ____ extends TestCase { public void test_scanInt() throws Exception { StringBuffer buf = new StringBuffer(); buf.append('['); for (int i = 0; i < 10; ++i) { if (i != 0) { buf.append(','); } // 1000000000000 // buf.append("\"" + i + "\""); } buf.append(']'); Reader reader = new StringReader(buf.toString()); JSONReaderScanner scanner = new JSONReaderScanner(reader); DefaultJSONParser parser = new DefaultJSONParser(scanner); JSONArray array = (JSONArray) parser.parse(); for (int i = 0; i < array.size(); ++i) { Assert.assertEquals(Integer.toString(i), array.get(i)); } } }
JSONReaderScannerTest_array_string
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/search/ShardSearchFailureTests.java
{ "start": 1409, "end": 8137 }
class ____ extends ESTestCase { private static SearchShardTarget randomShardTarget(String indexUuid) { String nodeId = randomAlphaOfLengthBetween(5, 10); String indexName = randomAlphaOfLengthBetween(5, 10); String clusterAlias = randomBoolean() ? randomAlphaOfLengthBetween(5, 10) : null; return new SearchShardTarget(nodeId, new ShardId(new Index(indexName, indexUuid), randomInt()), clusterAlias); } public static ShardSearchFailure createTestItem(String indexUuid) { String randomMessage = randomAlphaOfLengthBetween(3, 20); Exception ex = new ParsingException(0, 0, randomMessage, new IllegalArgumentException("some bad argument")); return new ShardSearchFailure(ex, randomBoolean() ? randomShardTarget(indexUuid) : null); } public void testFromXContent() throws IOException { doFromXContentTestWithRandomFields(false); } /** * This test adds random fields and objects to the xContent rendered out to * ensure we can parse it back to be forward compatible with additions to * the xContent */ public void testFromXContentWithRandomFields() throws IOException { doFromXContentTestWithRandomFields(true); } private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws IOException { ShardSearchFailure response = createTestItem(IndexMetadata.INDEX_UUID_NA_VALUE); XContentType xContentType = randomFrom(XContentType.values()); boolean humanReadable = randomBoolean(); BytesReference originalBytes = toShuffledXContent(response, xContentType, ToXContent.EMPTY_PARAMS, humanReadable); BytesReference mutated; if (addRandomFields) { mutated = insertRandomFields(xContentType, originalBytes, null, random()); } else { mutated = originalBytes; } ShardSearchFailure parsed; try (XContentParser parser = createParser(xContentType.xContent(), mutated)) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); parsed = SearchResponseUtils.parseShardSearchFailure(parser); assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken()); assertNull(parser.nextToken()); } assertEquals(response.index(), parsed.index()); assertEquals(response.shard(), parsed.shard()); assertEquals(response.shardId(), parsed.shardId()); /* * we cannot compare the cause, because it will be wrapped in an outer * ElasticSearchException best effort: try to check that the original * message appears somewhere in the rendered xContent */ String originalMsg = response.getCause().getMessage(); assertEquals(parsed.getCause().getMessage(), "Elasticsearch exception [type=parsing_exception, reason=" + originalMsg + "]"); String nestedMsg = response.getCause().getCause().getMessage(); assertEquals( parsed.getCause().getCause().getMessage(), "Elasticsearch exception [type=illegal_argument_exception, reason=" + nestedMsg + "]" ); } public void testToXContent() throws IOException { ShardSearchFailure failure = new ShardSearchFailure( new ParsingException(0, 0, "some message", null), new SearchShardTarget("nodeId", new ShardId(new Index("indexName", "indexUuid"), 123), null) ); BytesReference xContent = toXContent(failure, XContentType.JSON, randomBoolean()); assertEquals(XContentHelper.stripWhitespace(""" { "shard": 123, "index": "indexName", "node": "nodeId", "reason": { "type": "parsing_exception", "reason": "some message", "line": 0, "col": 0 } }"""), xContent.utf8ToString()); } public void testToXContentForNoShardAvailable() throws IOException { ShardId shardId = new ShardId(new Index("indexName", "indexUuid"), 123); ShardSearchFailure failure = new ShardSearchFailure( NoShardAvailableActionException.forOnShardFailureWrapper("shard unassigned"), new SearchShardTarget("nodeId", shardId, null) ); BytesReference xContent = toXContent(failure, XContentType.JSON, randomBoolean()); assertEquals(XContentHelper.stripWhitespace(""" { "shard": 123, "index": "indexName", "node": "nodeId", "reason":{"type":"no_shard_available_action_exception","reason":"shard unassigned"} }"""), xContent.utf8ToString()); } public void testToXContentWithClusterAlias() throws IOException { ShardSearchFailure failure = new ShardSearchFailure( new ParsingException(0, 0, "some message", null), new SearchShardTarget("nodeId", new ShardId(new Index("indexName", "indexUuid"), 123), "cluster1") ); BytesReference xContent = toXContent(failure, XContentType.JSON, randomBoolean()); assertEquals(XContentHelper.stripWhitespace(""" { "shard": 123, "index": "cluster1:indexName", "node": "nodeId", "reason": { "type": "parsing_exception", "reason": "some message", "line": 0, "col": 0 } }"""), xContent.utf8ToString()); } public void testSerialization() throws IOException { for (int runs = 0; runs < 25; runs++) { final ShardSearchFailure testItem; if (randomBoolean()) { testItem = createTestItem(randomAlphaOfLength(12)); } else { SearchShardTarget target = randomShardTarget(randomAlphaOfLength(12)); testItem = new ShardSearchFailure(NoShardAvailableActionException.forOnShardFailureWrapper("unavailable"), target); } ShardSearchFailure deserializedInstance = copyWriteable( testItem, writableRegistry(), ShardSearchFailure::new, TransportVersionUtils.randomVersion(random()) ); assertEquals(testItem.index(), deserializedInstance.index()); assertEquals(testItem.shard(), deserializedInstance.shard()); assertEquals(testItem.shardId(), deserializedInstance.shardId()); assertEquals(testItem.reason(), deserializedInstance.reason()); assertEquals(testItem.status(), deserializedInstance.status()); } } }
ShardSearchFailureTests
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryClientService.java
{ "start": 9890, "end": 20079 }
class ____ implements HSClientProtocol { private RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); public InetSocketAddress getConnectAddress() { return getBindAddress(); } private Job verifyAndGetJob(final JobId jobID, boolean exceptionThrow) throws IOException { UserGroupInformation loginUgi = null; Job job = null; try { loginUgi = UserGroupInformation.getLoginUser(); job = loginUgi.doAs(new PrivilegedExceptionAction<Job>() { @Override public Job run() throws Exception { Job job = history.getJob(jobID); return job; } }); } catch (InterruptedException e) { throw new IOException(e); } if (job == null && exceptionThrow) { throw new IOException("Unknown Job " + jobID); } if (job != null) { JobACL operation = JobACL.VIEW_JOB; checkAccess(job, operation); } return job; } @Override public GetCountersResponse getCounters(GetCountersRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId, true); GetCountersResponse response = recordFactory.newRecordInstance(GetCountersResponse.class); response.setCounters(TypeConverter.toYarn(job.getAllCounters())); return response; } @Override public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException { JobId jobId = request.getJobId(); Job job = verifyAndGetJob(jobId, false); GetJobReportResponse response = recordFactory.newRecordInstance(GetJobReportResponse.class); if (job != null) { response.setJobReport(job.getReport()); } else { response.setJobReport(null); } return response; } @Override public GetTaskAttemptReportResponse getTaskAttemptReport( GetTaskAttemptReportRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId(), true); GetTaskAttemptReportResponse response = recordFactory.newRecordInstance(GetTaskAttemptReportResponse.class); response.setTaskAttemptReport(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getReport()); return response; } @Override public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException { TaskId taskId = request.getTaskId(); Job job = verifyAndGetJob(taskId.getJobId(), true); GetTaskReportResponse response = recordFactory.newRecordInstance(GetTaskReportResponse.class); response.setTaskReport(job.getTask(taskId).getReport()); return response; } @Override public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents( GetTaskAttemptCompletionEventsRequest request) throws IOException { JobId jobId = request.getJobId(); int fromEventId = request.getFromEventId(); int maxEvents = request.getMaxEvents(); Job job = verifyAndGetJob(jobId, true); GetTaskAttemptCompletionEventsResponse response = recordFactory.newRecordInstance(GetTaskAttemptCompletionEventsResponse.class); response.addAllCompletionEvents(Arrays.asList(job.getTaskAttemptCompletionEvents(fromEventId, maxEvents))); return response; } @Override public KillJobResponse killJob(KillJobRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskResponse killTask(KillTaskRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public KillTaskAttemptResponse killTaskAttempt( KillTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException { TaskAttemptId taskAttemptId = request.getTaskAttemptId(); Job job = verifyAndGetJob(taskAttemptId.getTaskId().getJobId(), true); GetDiagnosticsResponse response = recordFactory.newRecordInstance(GetDiagnosticsResponse.class); response.addAllDiagnostics(job.getTask(taskAttemptId.getTaskId()).getAttempt(taskAttemptId).getDiagnostics()); return response; } @Override public FailTaskAttemptResponse failTaskAttempt( FailTaskAttemptRequest request) throws IOException { throw new IOException("Invalid operation on completed job"); } @Override public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException { JobId jobId = request.getJobId(); TaskType taskType = request.getTaskType(); GetTaskReportsResponse response = recordFactory.newRecordInstance(GetTaskReportsResponse.class); Job job = verifyAndGetJob(jobId, true); Collection<Task> tasks = job.getTasks(taskType).values(); for (Task task : tasks) { response.addTaskReport(task.getReport()); } return response; } @Override public GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request) throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); // Verify that the connection is kerberos authenticated if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos authentication"); } GetDelegationTokenResponse response = recordFactory.newRecordInstance( GetDelegationTokenResponse.class); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } MRDelegationTokenIdentifier tokenIdentifier = new MRDelegationTokenIdentifier(owner, new Text( request.getRenewer()), realUser); Token<MRDelegationTokenIdentifier> realJHSToken = new Token<MRDelegationTokenIdentifier>(tokenIdentifier, jhsDTSecretManager); org.apache.hadoop.yarn.api.records.Token mrDToken = org.apache.hadoop.yarn.api.records.Token.newInstance( realJHSToken.getIdentifier(), realJHSToken.getKind().toString(), realJHSToken.getPassword(), realJHSToken.getService().toString()); response.setDelegationToken(mrDToken); return response; } @Override public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token<MRDelegationTokenIdentifier> token = new Token<MRDelegationTokenIdentifier>( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getShortUserName(); long nextExpTime = jhsDTSecretManager.renewToken(token, user); RenewDelegationTokenResponse renewResponse = Records .newRecord(RenewDelegationTokenResponse.class); renewResponse.setNextExpirationTime(nextExpTime); return renewResponse; } @Override public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException { if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be cancelled only with kerberos authentication"); } org.apache.hadoop.yarn.api.records.Token protoToken = request.getDelegationToken(); Token<MRDelegationTokenIdentifier> token = new Token<MRDelegationTokenIdentifier>( protoToken.getIdentifier().array(), protoToken.getPassword() .array(), new Text(protoToken.getKind()), new Text( protoToken.getService())); String user = UserGroupInformation.getCurrentUser().getUserName(); jhsDTSecretManager.cancelToken(token, user); return Records.newRecord(CancelDelegationTokenResponse.class); } private void checkAccess(Job job, JobACL jobOperation) throws IOException { UserGroupInformation callerUGI; callerUGI = UserGroupInformation.getCurrentUser(); if (!job.checkAccess(callerUGI, jobOperation)) { throw new IOException(new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation " + jobOperation.name() + " on " + job.getID())); } } private boolean isAllowedDelegationTokenOp() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { return EnumSet.of(AuthenticationMethod.KERBEROS, AuthenticationMethod.KERBEROS_SSL, AuthenticationMethod.CERTIFICATE) .contains(UserGroupInformation.getCurrentUser() .getRealAuthenticationMethod()); } else { return true; } } } protected ResourceConfig configure(Configuration configuration, ApplicationClientProtocol protocol) { ResourceConfig config = new ResourceConfig(); config.packages("org.apache.hadoop.mapreduce.v2.hs.webapp"); config.register(new HSJerseyBinder(configuration, protocol)); config.register(HsWebServices.class); config.register(GenericExceptionHandler.class); config.register(new JettisonFeature()).register(JAXBContextResolver.class); return config; } private
HSClientProtocolHandler
java
google__guava
android/guava/src/com/google/common/collect/Cut.java
{ "start": 4166, "end": 6681 }
class ____ both methods that * use the `endpoint` field, compareTo() and endpoint(). Additionally, the main implementation * of Cut.compareTo checks for belowAll before reading accessing `endpoint` on another Cut * instance. */ super(""); } @Override Comparable<?> endpoint() { throw new IllegalStateException("range unbounded on this side"); } @Override boolean isLessThan(Comparable<?> value) { return true; } @Override BoundType typeAsLowerBound() { throw new IllegalStateException(); } @Override BoundType typeAsUpperBound() { throw new AssertionError("this statement should be unreachable"); } @Override Cut<Comparable<?>> withLowerBoundType( BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new IllegalStateException(); } @Override Cut<Comparable<?>> withUpperBoundType( BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new AssertionError("this statement should be unreachable"); } @Override void describeAsLowerBound(StringBuilder sb) { sb.append("(-\u221e"); } @Override void describeAsUpperBound(StringBuilder sb) { throw new AssertionError(); } @Override Comparable<?> leastValueAbove(DiscreteDomain<Comparable<?>> domain) { return domain.minValue(); } @Override Comparable<?> greatestValueBelow(DiscreteDomain<Comparable<?>> domain) { throw new AssertionError(); } @Override Cut<Comparable<?>> canonical(DiscreteDomain<Comparable<?>> domain) { try { return Cut.belowValue(domain.minValue()); } catch (NoSuchElementException e) { return this; } } @Override public int compareTo(Cut<Comparable<?>> o) { return (o == this) ? 0 : -1; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public String toString() { return "-\u221e"; } private Object readResolve() { return INSTANCE; } @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; } /* * The implementation neither produces nor consumes any non-null instance of * type C, so casting the type parameter is safe. */ @SuppressWarnings("unchecked") static <C extends Comparable> Cut<C> aboveAll() { return (Cut<C>) AboveAll.INSTANCE; } private static final
overrides
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/authorization/ReactiveAuthorizationAdvisorProxyFactoryTests.java
{ "start": 6535, "end": 7176 }
class ____ implements Identifiable, Comparable<User> { private final String id; private final String firstName; private final String lastName; User(String id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } public String getId() { return this.id; } @Override public Mono<String> getFirstName() { return Mono.just(this.firstName); } @Override public Mono<String> getLastName() { return Mono.just(this.lastName); } @Override public int compareTo(@NonNull User that) { return this.id.compareTo(that.getId()); } } static
User
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/binding/DelegateDeclaration.java
{ "start": 1624, "end": 2080 }
class ____ extends Declaration implements HasContributionType { abstract DependencyRequest delegateRequest(); // Note: We're using DaggerAnnotation instead of XAnnotation for its equals/hashcode abstract Optional<DaggerAnnotation> mapKey(); @Memoized @Override public abstract int hashCode(); @Override public abstract boolean equals(Object obj); /** A {@link DelegateDeclaration} factory. */ public static final
DelegateDeclaration
java
grpc__grpc-java
okhttp/third_party/okhttp/main/java/io/grpc/okhttp/internal/OptionalMethod.java
{ "start": 1178, "end": 1213 }
interface ____ base class */ public
or
java
quarkusio__quarkus
integration-tests/test-extension/extension-that-defines-junit-test-extensions/runtime/src/main/java/org/acme/CallbackInvokingInterceptor.java
{ "start": 1444, "end": 1579 }
class ____ the hierarchy in search for more methods clazz = clazz.getSuperclass(); } return methods; } }
in
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/ClassVisitor.java
{ "start": 3786, "end": 4006 }
class ____ to which this visitor must delegate method calls, or {@literal null}. */ public ClassVisitor getDelegate() { return cv; } /** * Visits the header of the class. * * @param version the
visitor
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/FileExclusiveReadNoneStrategyTest.java
{ "start": 2574, "end": 3269 }
class ____ implements Processor { @Override public void process(Exchange exchange) throws Exception { LOG.info("Creating a slow file with no locks..."); try (OutputStream fos = Files.newOutputStream(testFile("slowfile/hello.txt"))) { fos.write("Hello World".getBytes()); for (int i = 0; i < 3; i++) { Thread.sleep(100); fos.write(("Line #" + i).getBytes()); LOG.info("Appending to slowfile"); } fos.write("Bye World".getBytes()); } LOG.info("... done creating slowfile"); } } }
MySlowFileProcessor
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java
{ "start": 18549, "end": 18854 }
class ____ { /** Comment for a field */ @SuppressWarnings("test") private Object field; } """) .addOutputLines( "UnusedWithComment.java", """ package unusedvars; public
UnusedWithComment
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoBuilderTest.java
{ "start": 15536, "end": 16233 }
interface ____<T> { ImmutableList.Builder<T> listBuilder(); String call(); } @Test public void propertyBuilderWithoutSetter() { ConcatListCaller<Integer> caller = new AutoBuilder_AutoBuilderTest_ConcatListCaller<>(); caller.listBuilder().add(1, 1, 2, 3, 5, 8); String s = caller.call(); assertThat(s).isEqualTo("112358"); } static <K, V extends Number> Map<K, V> singletonMap(K key, V value) { return Collections.singletonMap(key, value); } static <K, V extends Number> SingletonMapBuilder<K, V> singletonMapBuilder() { return new AutoBuilder_AutoBuilderTest_SingletonMapBuilder<>(); } @AutoBuilder(callMethod = "singletonMap")
ConcatListCaller
java
elastic__elasticsearch
qa/vector/src/main/java/org/elasticsearch/test/knn/KnnIndexTester.java
{ "start": 3863, "end": 15374 }
enum ____ { TIERED, LOG_BYTE, NO, LOG_DOC } private static String formatIndexPath(CmdLineArgs args) { List<String> suffix = new ArrayList<>(); if (args.indexType() == IndexType.FLAT) { suffix.add("flat"); } else if (args.indexType() == IndexType.GPU_HNSW) { suffix.add("gpu_hnsw"); } else if (args.indexType() == IndexType.IVF) { suffix.add("ivf"); suffix.add(Integer.toString(args.ivfClusterSize())); } else { suffix.add(Integer.toString(args.hnswM())); suffix.add(Integer.toString(args.hnswEfConstruction())); if (args.quantizeBits() < 32) { suffix.add(Integer.toString(args.quantizeBits())); } } return INDEX_DIR + "/" + args.docVectors().get(0).getFileName() + "-" + String.join("-", suffix) + ".index"; } static Codec createCodec(CmdLineArgs args) { final KnnVectorsFormat format; int quantizeBits = args.quantizeBits(); if (args.indexType() == IndexType.IVF) { ESNextDiskBBQVectorsFormat.QuantEncoding encoding = switch (quantizeBits) { case (1) -> ESNextDiskBBQVectorsFormat.QuantEncoding.ONE_BIT_4BIT_QUERY; case (2) -> ESNextDiskBBQVectorsFormat.QuantEncoding.TWO_BIT_4BIT_QUERY; case (4) -> ESNextDiskBBQVectorsFormat.QuantEncoding.FOUR_BIT_SYMMETRIC; default -> throw new IllegalArgumentException( "IVF index type only supports 1, 2 or 4 bits quantization, but got: " + quantizeBits ); }; format = new ESNextDiskBBQVectorsFormat( encoding, args.ivfClusterSize(), ES920DiskBBQVectorsFormat.DEFAULT_CENTROIDS_PER_PARENT_CLUSTER, DenseVectorFieldMapper.ElementType.FLOAT, args.onDiskRescore() ); } else if (args.indexType() == IndexType.GPU_HNSW) { if (quantizeBits == 32) { format = new ES92GpuHnswVectorsFormat(); } else if (quantizeBits == 7) { format = new ES92GpuHnswSQVectorsFormat(); } else { throw new IllegalArgumentException("GPU HNSW index type only supports 7 or 32 bits quantization, but got: " + quantizeBits); } } else { if (quantizeBits == 1) { if (args.indexType() == IndexType.FLAT) { format = new ES818BinaryQuantizedVectorsFormat(); } else { format = new ES818HnswBinaryQuantizedVectorsFormat(args.hnswM(), args.hnswEfConstruction(), 1, null); } } else if (quantizeBits < 32) { if (args.indexType() == IndexType.FLAT) { format = new ES813Int8FlatVectorFormat(null, quantizeBits, true); } else { format = new ES814HnswScalarQuantizedVectorsFormat(args.hnswM(), args.hnswEfConstruction(), null, quantizeBits, true); } } else { format = new Lucene99HnswVectorsFormat(args.hnswM(), args.hnswEfConstruction(), 1, null); } } return new Lucene103Codec() { @Override public KnnVectorsFormat getKnnVectorsFormatForField(String field) { return new KnnVectorsFormat(format.getName()) { @Override public KnnVectorsWriter fieldsWriter(SegmentWriteState state) throws IOException { return format.fieldsWriter(state); } @Override public KnnVectorsReader fieldsReader(SegmentReadState state) throws IOException { return format.fieldsReader(state); } @Override public int getMaxDimensions(String fieldName) { return MAX_DIMS_COUNT; } @Override public String toString() { return format.toString(); } }; } }; } /** * Main method to run the KNN index tester. * It parses command line arguments, creates the index, and runs searches if specified. * * @param args Command line arguments * @throws Exception If an error occurs during index creation or search */ public static void main(String[] args) throws Exception { if (args.length != 1 || args[0].equals("--help") || args[0].equals("-h")) { // printout an example configuration formatted file and indicate that it is required System.out.println("Usage: java -cp <your-classpath> org.elasticsearch.test.knn.KnnIndexTester <config-file>"); System.out.println("Where <config-file> is a JSON file containing one or more configurations for the KNN index tester."); System.out.println("An example configuration object: "); System.out.println( Strings.toString( new CmdLineArgs.Builder().setDimensions(64) .setDocVectors(List.of("/doc/vectors/path")) .setQueryVectors("/query/vectors/path") .build(), true, true ) ); return; } String jsonConfig = args[0]; // Parse command line arguments Path jsonConfigPath = PathUtils.get(jsonConfig); if (Files.exists(jsonConfigPath) == false) { throw new IllegalArgumentException("JSON config file does not exist: " + jsonConfigPath); } // Parse the JSON config file to get command line arguments // This assumes that CmdLineArgs.fromXContent is implemented to parse the JSON file List<CmdLineArgs> cmdLineArgsList = new ArrayList<>(); try ( InputStream jsonStream = Files.newInputStream(jsonConfigPath); XContentParser parser = XContentType.JSON.xContent().createParser(XContentParserConfiguration.EMPTY, jsonStream) ) { // check if the parser is at the start of an object if so, we only have one set of arguments if (parser.currentToken() == null && parser.nextToken() == XContentParser.Token.START_OBJECT) { cmdLineArgsList.add(CmdLineArgs.fromXContent(parser)); } else if (parser.currentToken() == XContentParser.Token.START_ARRAY) { // if the parser is at the start of an array, we have multiple sets of arguments while (parser.nextToken() != XContentParser.Token.END_ARRAY) { cmdLineArgsList.add(CmdLineArgs.fromXContent(parser)); } } else { throw new IllegalArgumentException("Invalid JSON format in config file: " + jsonConfigPath); } } FormattedResults formattedResults = new FormattedResults(); for (CmdLineArgs cmdLineArgs : cmdLineArgsList) { double[] visitPercentages = cmdLineArgs.indexType().equals(IndexType.IVF) && cmdLineArgs.numQueries() > 0 ? cmdLineArgs.visitPercentages() : new double[] { 0 }; String indexType = cmdLineArgs.indexType().name().toLowerCase(Locale.ROOT); Results indexResults = new Results( cmdLineArgs.docVectors().get(0).getFileName().toString(), indexType, cmdLineArgs.numDocs(), cmdLineArgs.filterSelectivity() ); Results[] results = new Results[visitPercentages.length]; for (int i = 0; i < visitPercentages.length; i++) { results[i] = new Results( cmdLineArgs.docVectors().get(0).getFileName().toString(), indexType, cmdLineArgs.numDocs(), cmdLineArgs.filterSelectivity() ); } logger.info("Running with Java: " + Runtime.version()); logger.info("Running KNN index tester with arguments: " + cmdLineArgs); Codec codec = createCodec(cmdLineArgs); Path indexPath = PathUtils.get(formatIndexPath(cmdLineArgs)); MergePolicy mergePolicy = getMergePolicy(cmdLineArgs); if (cmdLineArgs.reindex() || cmdLineArgs.forceMerge()) { KnnIndexer knnIndexer = new KnnIndexer( cmdLineArgs.docVectors(), indexPath, codec, cmdLineArgs.indexThreads(), cmdLineArgs.vectorEncoding(), cmdLineArgs.dimensions(), cmdLineArgs.vectorSpace(), cmdLineArgs.numDocs(), mergePolicy, cmdLineArgs.writerBufferSizeInMb(), cmdLineArgs.writerMaxBufferedDocs() ); if (cmdLineArgs.reindex() == false && Files.exists(indexPath) == false) { throw new IllegalArgumentException("Index path does not exist: " + indexPath); } if (cmdLineArgs.reindex()) { knnIndexer.createIndex(indexResults); } if (cmdLineArgs.forceMerge()) { knnIndexer.forceMerge(indexResults, cmdLineArgs.forceMergeMaxNumSegments()); } } numSegments(indexPath, indexResults); if (cmdLineArgs.queryVectors() != null && cmdLineArgs.numQueries() > 0) { for (int i = 0; i < results.length; i++) { KnnSearcher knnSearcher = new KnnSearcher(indexPath, cmdLineArgs, visitPercentages[i]); knnSearcher.runSearch(results[i], cmdLineArgs.earlyTermination()); } } formattedResults.queryResults.addAll(List.of(results)); formattedResults.indexResults.add(indexResults); } logger.info("Results: \n" + formattedResults); } private static MergePolicy getMergePolicy(CmdLineArgs args) { MergePolicy mergePolicy = null; if (args.mergePolicy() != null) { if (args.mergePolicy() == MergePolicyType.TIERED) { mergePolicy = new TieredMergePolicy(); } else if (args.mergePolicy() == MergePolicyType.LOG_BYTE) { mergePolicy = new LogByteSizeMergePolicy(); } else if (args.mergePolicy() == MergePolicyType.NO) { mergePolicy = NoMergePolicy.INSTANCE; } else if (args.mergePolicy() == MergePolicyType.LOG_DOC) { mergePolicy = new LogDocMergePolicy(); } else { throw new IllegalArgumentException("Invalid merge policy: " + args.mergePolicy()); } } return mergePolicy; } static void numSegments(Path indexPath, KnnIndexTester.Results result) { try (FSDirectory dir = FSDirectory.open(indexPath); IndexReader reader = DirectoryReader.open(dir)) { result.numSegments = reader.leaves().size(); } catch (IOException e) { throw new UncheckedIOException("Failed to get segment count for index at " + indexPath, e); } } static
MergePolicyType
java
elastic__elasticsearch
qa/packaging/src/test/java/org/elasticsearch/packaging/test/PackagingTestCase.java
{ "start": 4541, "end": 4826 }
class ____ extends Assert { /** * Annotation for tests which exhibit a known issue and are temporarily disabled. */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @TestGroup(enabled = false, sysProperty = "tests.awaitsfix") @
PackagingTestCase
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/expression/predicate/regex/RegexOperation.java
{ "start": 365, "end": 1238 }
class ____ { public static Boolean match(Object value, Pattern pattern) { if (pattern == null) { return Boolean.TRUE; } if (value == null) { return null; } return pattern.matcher(value.toString()).matches(); } public static Boolean match(Object value, String pattern) { return match(value, pattern, Boolean.FALSE); } public static Boolean match(Object value, String pattern, Boolean caseInsensitive) { if (pattern == null) { return Boolean.TRUE; } if (value == null) { return null; } int flags = 0; if (Boolean.TRUE.equals(caseInsensitive)) { flags |= Pattern.CASE_INSENSITIVE; } return Pattern.compile(pattern, flags).matcher(value.toString()).matches(); } }
RegexOperation
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/metadata/RequestMatcherMetadataResponseResolver.java
{ "start": 2247, "end": 8310 }
class ____ implements Saml2MetadataResponseResolver { private static final String DEFAULT_METADATA_FILENAME = "saml-{registrationId}-metadata.xml"; private RequestMatcher matcher = new OrRequestMatcher( pathPattern("/saml2/service-provider-metadata/{registrationId}"), pathPattern("/saml2/metadata/{registrationId}"), pathPattern("/saml2/metadata")); private String filename = DEFAULT_METADATA_FILENAME; private final RelyingPartyRegistrationRepository registrations; private final Saml2MetadataResolver metadata; /** * Construct a {@link RequestMatcherMetadataResponseResolver} * @param registrations the source for relying party metadata * @param metadata the strategy for converting {@link RelyingPartyRegistration}s into * metadata */ public RequestMatcherMetadataResponseResolver(RelyingPartyRegistrationRepository registrations, Saml2MetadataResolver metadata) { Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null"); Assert.notNull(metadata, "saml2MetadataResolver cannot be null"); this.registrations = registrations; this.metadata = metadata; } /** * Construct and serialize a relying party's SAML 2.0 metadata based on the given * {@link HttpServletRequest}. Uses the configured {@link RequestMatcher} to identify * the metadata request, including looking for any indicated {@code registrationId}. * * <p> * If a {@code registrationId} is found in the request, it will attempt to use that, * erroring if no {@link RelyingPartyRegistration} is found. * * <p> * If no {@code registrationId} is found in the request, it will attempt to show all * {@link RelyingPartyRegistration}s in an {@code <md:EntitiesDescriptor>}. To * exercise this functionality, the provided * {@link RelyingPartyRegistrationRepository} needs to implement {@link Iterable}. * @param request the HTTP request * @return a {@link Saml2MetadataResponse} instance * @throws Saml2Exception if the {@link RequestMatcher} specifies a non-existent * {@code registrationId} */ @Override public Saml2MetadataResponse resolve(HttpServletRequest request) { RequestMatcher.MatchResult result = this.matcher.matcher(request); if (!result.isMatch()) { return null; } String registrationId = result.getVariables().get("registrationId"); Saml2MetadataResponse response = responseByRegistrationId(request, registrationId); if (response != null) { return response; } if (this.registrations instanceof IterableRelyingPartyRegistrationRepository iterable) { return responseByIterable(request, iterable); } if (this.registrations instanceof Iterable<?>) { Iterable<RelyingPartyRegistration> registrations = (Iterable<RelyingPartyRegistration>) this.registrations; return responseByIterable(request, registrations); } return null; } private Saml2MetadataResponse responseByRegistrationId(HttpServletRequest request, String registrationId) { if (registrationId == null) { return null; } RelyingPartyRegistration registration = this.registrations.findByRegistrationId(registrationId); if (registration == null) { throw new Saml2Exception("registration not found"); } return responseByIterable(request, Collections.singleton(registration)); } private Saml2MetadataResponse responseByIterable(HttpServletRequest request, Iterable<RelyingPartyRegistration> registrations) { Map<String, RelyingPartyRegistration> results = new LinkedHashMap<>(); for (RelyingPartyRegistration registration : registrations) { RelyingPartyRegistrationPlaceholderResolvers.UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers .uriResolver(request, registration); String entityId = uriResolver.resolve(registration.getEntityId()); results.computeIfAbsent(entityId, (e) -> { String ssoLocation = uriResolver.resolve(registration.getAssertionConsumerServiceLocation()); String sloLocation = uriResolver.resolve(registration.getSingleLogoutServiceLocation()); String sloResponseLocation = uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation()); return registration.mutate() .entityId(entityId) .assertionConsumerServiceLocation(ssoLocation) .singleLogoutServiceLocation(sloLocation) .singleLogoutServiceResponseLocation(sloResponseLocation) .build(); }); } String metadata = this.metadata.resolve(results.values()); String value = (results.size() == 1) ? results.values().iterator().next().getRegistrationId() : UUID.randomUUID().toString(); String fileName = this.filename.replace("{registrationId}", value); try { String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()); return new Saml2MetadataResponse(metadata, encodedFileName); } catch (UnsupportedEncodingException ex) { throw new Saml2Exception(ex); } } /** * Use this {@link RequestMatcher} to identity which requests to generate metadata * for. By default, matches {@code /saml2/metadata}, * {@code /saml2/metadata/{registrationId}}, {@code /saml2/service-provider-metadata}, * and {@code /saml2/service-provider-metadata/{registrationId}} * @param requestMatcher the {@link RequestMatcher} to use */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be empty"); this.matcher = requestMatcher; } /** * Sets the metadata filename template. If it contains the {@code {registrationId}} * placeholder, it will be resolved as a random UUID if there are multiple * {@link RelyingPartyRegistration}s. Otherwise, it will be replaced by the * {@link RelyingPartyRegistration}'s id. * * <p> * The default value is {@code saml-{registrationId}-metadata.xml} * @param metadataFilename metadata filename, must contain a {registrationId} */ public void setMetadataFilename(String metadataFilename) { Assert.hasText(metadataFilename, "metadataFilename cannot be empty"); this.filename = metadataFilename; } }
RequestMatcherMetadataResponseResolver
java
quarkusio__quarkus
test-framework/kubernetes-client/src/main/java/io/quarkus/test/kubernetes/client/WithKubernetesTestServer.java
{ "start": 1159, "end": 1299 }
class ____ implements Consumer<KubernetesServer> { @Override public void accept(KubernetesServer t) { } } }
NO_SETUP
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/EqualsIncompatibleTypeTest.java
{ "start": 14195, "end": 14257 }
interface ____ extends Comparable<Comparable<RecOne>> {}
RecOne
java
apache__camel
components/camel-aws/camel-aws-xray/src/main/java/org/apache/camel/component/aws/xray/decorators/http/NettyHttpSegmentDecorator.java
{ "start": 872, "end": 1030 }
class ____ extends AbstractHttpSegmentDecorator { @Override public String getComponent() { return "netty-http"; } }
NettyHttpSegmentDecorator
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/extensions/NamespaceTemplateExtensionValidationFailureTest.java
{ "start": 500, "end": 1755 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addAsResource(new StringAsset( "{bro:surname}\n" + "{bro:name.bubu}"), "templates/foo.html") .addClasses(SomeExtensions.class)) .assertException(t -> { Throwable e = t; TemplateException te = null; while (e != null) { if (e instanceof TemplateException) { te = (TemplateException) e; break; } e = e.getCause(); } assertNotNull(te); assertTrue(te.getMessage().contains("Found incorrect expressions (1)"), te.getMessage()); assertTrue(te.getMessage().contains("Property/method [bubu] not found on class [java.lang.String]"), te.getMessage()); }); @Test public void test() { fail(); } @TemplateExtension(namespace = "bro") public static
NamespaceTemplateExtensionValidationFailureTest
java
apache__camel
components/camel-fop/src/test/java/org/apache/camel/component/fop/FopEndpointTest.java
{ "start": 1438, "end": 5896 }
class ____ extends CamelTestSupport { private boolean canTest() { try { context().getEndpoint("fop:pdf"); } catch (Exception e) { return false; } return true; } @Test public void generatePdfFromXslfoWithSpecificText() throws Exception { if (!canTest()) { // cannot run on CI return; } Endpoint endpoint = context().getEndpoint("fop:pdf"); Producer producer = endpoint.createProducer(); Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(FopHelper.decorateTextWithXSLFO("Test Content")); producer.process(exchange); PDDocument document = getDocumentFrom(exchange); String content = FopHelper.extractTextFrom(document); assertEquals("Test Content", content); } @Test public void specifyCustomUserConfigurationFile() { if (!canTest()) { // cannot run on CI return; } FopEndpoint customConfiguredEndpoint = context() .getEndpoint("fop:pdf?userConfigURL=file:src/test/data/conf/testcfg.xml", FopEndpoint.class); float customSourceResolution = customConfiguredEndpoint.getFopFactory().getSourceResolution(); assertEquals(96.0, customSourceResolution, 0.1); } @Test public void specifyCustomUserConfigurationFileClasspath() { if (!canTest()) { // cannot run on CI return; } FopEndpoint customConfiguredEndpoint = context() .getEndpoint("fop:pdf?userConfigURL=myconf/testcfg.xml", FopEndpoint.class); float customSourceResolution = customConfiguredEndpoint.getFopFactory().getSourceResolution(); assertEquals(96.0, customSourceResolution, 0.1); } @Test public void setPDFRenderingMetadataPerDocument() throws Exception { if (!canTest()) { // cannot run on CI return; } Endpoint endpoint = context().getEndpoint("fop:pdf"); Producer producer = endpoint.createProducer(); Exchange exchange = new DefaultExchange(context); exchange.getIn().setHeader("CamelFop.Render.Creator", "Test User"); exchange.getIn().setBody(FopHelper.decorateTextWithXSLFO("Test Content")); producer.process(exchange); PDDocument document = getDocumentFrom(exchange); String creator = FopHelper.getDocumentMetadataValue(document, COSName.CREATOR); assertEquals("Test User", creator); } @Test public void encryptPdfWithUserPassword() throws Exception { if (!canTest()) { // cannot run on CI return; } Endpoint endpoint = context().getEndpoint("fop:pdf"); Producer producer = endpoint.createProducer(); Exchange exchange = new DefaultExchange(context); final String password = "secret"; exchange.getIn().setHeader("CamelFop.Encrypt.userPassword", password); exchange.getIn().setBody(FopHelper.decorateTextWithXSLFO("Test Content")); producer.process(exchange); try (InputStream inputStream = exchange.getMessage().getBody(InputStream.class)) { PDDocument document = Loader.loadPDF(new RandomAccessReadBuffer(inputStream), password); assertTrue(document.isEncrypted()); } } @Test public void overridePdfOutputFormatToPlainText() throws Exception { if (!canTest()) { // cannot run on CI return; } String defaultOutputFormat = "pdf"; Endpoint endpoint = context().getEndpoint("fop:" + defaultOutputFormat); Producer producer = endpoint.createProducer(); Exchange exchange = new DefaultExchange(context); exchange.getIn().setHeader(FopConstants.CAMEL_FOP_OUTPUT_FORMAT, "txt"); exchange.getIn().setBody(FopHelper.decorateTextWithXSLFO("Test Content")); producer.process(exchange); String plainText = exchange.getMessage().getBody(String.class).trim(); assertEquals("Test Content", plainText); } private PDDocument getDocumentFrom(Exchange exchange) throws IOException { InputStream inputStream = exchange.getMessage().getBody(InputStream.class); return Loader.loadPDF(new RandomAccessReadBuffer(inputStream)); } }
FopEndpointTest
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/support/hierarchical/ParallelExecutionConfiguration.java
{ "start": 665, "end": 833 }
class ____ intended to be used to configure * implementations of {@link HierarchicalTestExecutorService}. Such * implementations may use all of the properties in this
are
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestGetDesiredBalanceAction.java
{ "start": 1160, "end": 2010 }
class ____ extends BaseRestHandler { @Override public String getName() { return "get_desired_balance"; } @Override public List<Route> routes() { return List.of(new Route(RestRequest.Method.GET, "_internal/desired_balance")); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { final var req = new DesiredBalanceRequest(RestUtils.getMasterNodeTimeout(request)); return restChannel -> client.execute( TransportGetDesiredBalanceAction.TYPE, req, new RestRefCountedChunkedToXContentListener<>(restChannel) ); } @Override public Set<String> supportedCapabilities() { return Set.of("desired_balance_node_weights_in_response"); } }
RestGetDesiredBalanceAction
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/EtagSource.java
{ "start": 1202, "end": 1396 }
interface ____ { /** * Return an etag of this file status. * A return value of null or "" means "no etag" * @return a possibly null or empty etag. */ String getEtag(); }
EtagSource
java
google__guava
android/guava/src/com/google/common/collect/ImmutableRangeSet.java
{ "start": 27396, "end": 28173 }
class ____<C extends Comparable> implements Serializable { private final ImmutableList<Range<C>> ranges; SerializedForm(ImmutableList<Range<C>> ranges) { this.ranges = ranges; } Object readResolve() { if (ranges.isEmpty()) { return of(); } else if (ranges.equals(ImmutableList.of(Range.all()))) { return all(); } else { return new ImmutableRangeSet<C>(ranges); } } } @J2ktIncompatible // java.io.ObjectInputStream Object writeReplace() { return new SerializedForm<C>(ranges); } @J2ktIncompatible // java.io.ObjectInputStream private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } }
SerializedForm
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/SyntheticCreationalContext.java
{ "start": 271, "end": 1633 }
interface ____<T> extends CreationalContext<T> { /** * * @return the build-time parameters */ Map<String, Object> getParams(); /** * Obtains a contextual reference for a synthetic injection point. * * @param <R> * @param requiredType * @param qualifiers * @return a contextual reference for the given required type and qualifiers * @throws IllegalArgumentException If a corresponding synthetic injection point was not defined */ <R> R getInjectedReference(Class<R> requiredType, Annotation... qualifiers); /** * Obtains a contextual reference for a synthetic injection point. * * @param <R> * @param requiredType * @param qualifiers * @return a contextual reference for the given required type and qualifiers * @throws IllegalArgumentException If a corresponding synthetic injection point was not defined */ <R> R getInjectedReference(TypeLiteral<R> requiredType, Annotation... qualifiers); /** * Returns an {@link InterceptionProxy} for this synthetic bean. * * @return an {@link InterceptionProxy} for this synthetic bean * @throws IllegalArgumentException if no {@link InterceptionProxy} was registered for this synthetic bean */ <R> InterceptionProxy<R> getInterceptionProxy(); }
SyntheticCreationalContext
java
apache__flink
flink-connectors/flink-hadoop-compatibility/src/main/java/org/apache/flink/api/java/hadoop/mapreduce/utils/HadoopUtils.java
{ "start": 1149, "end": 2157 }
class ____ { /** * Merge HadoopConfiguration into Configuration. This is necessary for the HDFS configuration. */ public static void mergeHadoopConf(Configuration hadoopConfig) { // we have to load the global configuration here, because the HadoopInputFormatBase does not // have access to a Flink configuration object org.apache.flink.configuration.Configuration flinkConfiguration = GlobalConfiguration.loadConfiguration(); Configuration hadoopConf = org.apache.flink.api.java.hadoop.mapred.utils.HadoopUtils.getHadoopConfiguration( flinkConfiguration); for (Map.Entry<String, String> e : hadoopConf) { if (hadoopConfig.get(e.getKey()) == null) { hadoopConfig.set(e.getKey(), e.getValue()); } } } /** Private constructor to prevent instantiation. */ private HadoopUtils() { throw new RuntimeException(); } }
HadoopUtils
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/generated/RecordComparator.java
{ "start": 1233, "end": 1362 }
interface ____ extends Comparator<RowData>, Serializable { @Override int compare(RowData o1, RowData o2); }
RecordComparator
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/processor/MethodRetrievalProcessor.java
{ "start": 33711, "end": 34829 }
class ____ extends RepeatableAnnotations<ValueMappingGem, ValueMappingsGem, ValueMappingOptions> { protected RepeatValueMappings() { super( elementUtils, VALUE_MAPPING_FQN, VALUE_MAPPINGS_FQN ); } @Override protected ValueMappingGem singularInstanceOn(Element element) { return ValueMappingGem.instanceOn( element ); } @Override protected ValueMappingsGem multipleInstanceOn(Element element) { return ValueMappingsGem.instanceOn( element ); } @Override protected void addInstance(ValueMappingGem gem, Element source, Set<ValueMappingOptions> mappings) { ValueMappingOptions valueMappingOptions = ValueMappingOptions.fromMappingGem( gem ); mappings.add( valueMappingOptions ); } @Override protected void addInstances(ValueMappingsGem gems, Element source, Set<ValueMappingOptions> mappings) { ValueMappingOptions.fromMappingsGem( gems, (ExecutableElement) source, messager, mappings ); } } private
RepeatValueMappings
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/core/AuthenticatedPrincipal.java
{ "start": 1219, "end": 1512 }
interface ____ implementors to expose specific attributes of their custom * representation of <code>Principal</code> in a generic way. * * @author Joe Grandja * @since 5.0 * @see Authentication#getPrincipal() * @see org.springframework.security.core.userdetails.UserDetails */ public
allows
java
apache__rocketmq
client/src/test/java/org/apache/rocketmq/client/impl/MQAdminImplTest.java
{ "start": 2710, "end": 11202 }
class ____ { @Mock private MQClientInstance mQClientFactory; @Mock private MQClientAPIImpl mQClientAPIImpl; private MQAdminImpl mqAdminImpl; private final String defaultTopic = "defaultTopic"; private final String defaultBroker = "defaultBroker"; private final String defaultCluster = "defaultCluster"; private final String defaultBrokerAddr = "127.0.0.1:10911"; private final long defaultTimeout = 3000L; @Before public void init() throws RemotingException, InterruptedException, MQClientException { when(mQClientFactory.getMQClientAPIImpl()).thenReturn(mQClientAPIImpl); when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createRouteData()); ClientConfig clientConfig = mock(ClientConfig.class); when(clientConfig.getNamespace()).thenReturn("namespace"); when(mQClientFactory.getClientConfig()).thenReturn(clientConfig); when(mQClientFactory.findBrokerAddressInPublish(any())).thenReturn(defaultBrokerAddr); when(mQClientFactory.getAnExistTopicRouteData(any())).thenReturn(createRouteData()); mqAdminImpl = new MQAdminImpl(mQClientFactory); } @Test public void assertTimeoutMillis() { assertEquals(6000L, mqAdminImpl.getTimeoutMillis()); mqAdminImpl.setTimeoutMillis(defaultTimeout); assertEquals(defaultTimeout, mqAdminImpl.getTimeoutMillis()); } @Test public void testCreateTopic() throws MQClientException { mqAdminImpl.createTopic("", defaultTopic, 6); } @Test public void assertFetchPublishMessageQueues() throws MQClientException { List<MessageQueue> queueList = mqAdminImpl.fetchPublishMessageQueues(defaultTopic); assertNotNull(queueList); assertEquals(6, queueList.size()); for (MessageQueue each : queueList) { assertEquals(defaultTopic, each.getTopic()); assertEquals(defaultBroker, each.getBrokerName()); } } @Test public void assertFetchSubscribeMessageQueues() throws MQClientException { Set<MessageQueue> queueList = mqAdminImpl.fetchSubscribeMessageQueues(defaultTopic); assertNotNull(queueList); assertEquals(6, queueList.size()); for (MessageQueue each : queueList) { assertEquals(defaultTopic, each.getTopic()); assertEquals(defaultBroker, each.getBrokerName()); } } @Test public void assertSearchOffset() throws MQClientException { assertEquals(0, mqAdminImpl.searchOffset(new MessageQueue(), defaultTimeout)); } @Test public void assertMaxOffset() throws MQClientException { assertEquals(0, mqAdminImpl.maxOffset(new MessageQueue())); } @Test public void assertMinOffset() throws MQClientException { assertEquals(0, mqAdminImpl.minOffset(new MessageQueue())); } @Test public void assertEarliestMsgStoreTime() throws MQClientException { assertEquals(0, mqAdminImpl.earliestMsgStoreTime(new MessageQueue())); } @Test(expected = MQClientException.class) public void assertViewMessage() throws MQBrokerException, RemotingException, InterruptedException, MQClientException { MessageExt actual = mqAdminImpl.viewMessage(defaultTopic, "1"); assertNotNull(actual); } @Test public void assertQueryMessage() throws InterruptedException, MQClientException, MQBrokerException, RemotingException { doAnswer(invocation -> { InvokeCallback callback = invocation.getArgument(3); QueryMessageResponseHeader responseHeader = new QueryMessageResponseHeader(); responseHeader.setIndexLastUpdatePhyoffset(1L); responseHeader.setIndexLastUpdateTimestamp(System.currentTimeMillis()); RemotingCommand response = mock(RemotingCommand.class); when(response.decodeCommandCustomHeader(QueryMessageResponseHeader.class)).thenReturn(responseHeader); when(response.getBody()).thenReturn(getMessageResult()); when(response.getCode()).thenReturn(ResponseCode.SUCCESS); callback.operationSucceed(response); return null; }).when(mQClientAPIImpl).queryMessage(anyString(), any(), anyLong(), any(InvokeCallback.class), any()); QueryResult actual = mqAdminImpl.queryMessage(defaultTopic, "keys", 100, 1L, 50L); assertNotNull(actual); assertEquals(1, actual.getMessageList().size()); assertEquals(defaultTopic, actual.getMessageList().get(0).getTopic()); } @Test public void assertQueryMessageByUniqKey() throws InterruptedException, MQClientException, MQBrokerException, RemotingException { doAnswer(invocation -> { InvokeCallback callback = invocation.getArgument(3); QueryMessageResponseHeader responseHeader = new QueryMessageResponseHeader(); responseHeader.setIndexLastUpdatePhyoffset(1L); responseHeader.setIndexLastUpdateTimestamp(System.currentTimeMillis()); RemotingCommand response = mock(RemotingCommand.class); when(response.decodeCommandCustomHeader(QueryMessageResponseHeader.class)).thenReturn(responseHeader); when(response.getBody()).thenReturn(getMessageResult()); when(response.getCode()).thenReturn(ResponseCode.SUCCESS); callback.operationSucceed(response); return null; }).when(mQClientAPIImpl).queryMessage(anyString(), any(), anyLong(), any(InvokeCallback.class), any()); String msgId = buildMsgId(); MessageExt actual = mqAdminImpl.queryMessageByUniqKey(defaultTopic, msgId); assertNotNull(actual); assertEquals(msgId, actual.getMsgId()); assertEquals(defaultTopic, actual.getTopic()); actual = mqAdminImpl.queryMessageByUniqKey(defaultCluster, defaultTopic, msgId); assertNotNull(actual); assertEquals(msgId, actual.getMsgId()); assertEquals(defaultTopic, actual.getTopic()); QueryResult queryResult = mqAdminImpl.queryMessageByUniqKey(defaultTopic, msgId, 1, 0L, 1L); assertNotNull(queryResult); assertEquals(1, queryResult.getMessageList().size()); assertEquals(defaultTopic, queryResult.getMessageList().get(0).getTopic()); } private String buildMsgId() { MessageExt msgExt = createMessageExt(); int storeHostIPLength = (msgExt.getFlag() & MessageSysFlag.STOREHOSTADDRESS_V6_FLAG) == 0 ? 4 : 16; int msgIDLength = storeHostIPLength + 4 + 8; ByteBuffer byteBufferMsgId = ByteBuffer.allocate(msgIDLength); return MessageDecoder.createMessageId(byteBufferMsgId, msgExt.getStoreHostBytes(), msgExt.getCommitLogOffset()); } private TopicRouteData createRouteData() { TopicRouteData result = new TopicRouteData(); result.setBrokerDatas(createBrokerData()); result.setQueueDatas(createQueueData()); return result; } private List<BrokerData> createBrokerData() { HashMap<Long, String> brokerAddrs = new HashMap<>(); brokerAddrs.put(MixAll.MASTER_ID, defaultBrokerAddr); return Collections.singletonList(new BrokerData(defaultCluster, defaultBroker, brokerAddrs)); } private List<QueueData> createQueueData() { QueueData queueData = new QueueData(); queueData.setPerm(6); queueData.setBrokerName(defaultBroker); queueData.setReadQueueNums(6); queueData.setWriteQueueNums(6); return Collections.singletonList(queueData); } private byte[] getMessageResult() throws Exception { byte[] bytes = MessageDecoder.encode(createMessageExt(), false); ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length); byteBuffer.put(bytes); return byteBuffer.array(); } private MessageExt createMessageExt() { MessageExt result = new MessageExt(); result.setBody("body".getBytes(StandardCharsets.UTF_8)); result.setTopic(defaultTopic); result.setBrokerName(defaultBroker); result.putUserProperty("key", "value"); result.setKeys("keys"); SocketAddress bornHost = new InetSocketAddress("127.0.0.1", 12911); SocketAddress storeHost = new InetSocketAddress("127.0.0.1", 10911); result.setBornHost(bornHost); result.setStoreHost(storeHost); return result; } }
MQAdminImplTest
java
micronaut-projects__micronaut-core
http-client-jdk/src/main/java/io/micronaut/http/client/jdk/HttpHeadersAdapter.java
{ "start": 1147, "end": 2296 }
class ____ implements HttpHeaders { private final java.net.http.HttpHeaders httpHeaders; private final ConversionService conversionService; /** * * @param httpHeaders HTTP Headers. * @param conversionService Conversion Service. */ public HttpHeadersAdapter(java.net.http.HttpHeaders httpHeaders, ConversionService conversionService) { this.httpHeaders = httpHeaders; this.conversionService = conversionService; } @Override public List<String> getAll(CharSequence name) { return httpHeaders.allValues(name.toString()); } @Override public String get(CharSequence name) { return httpHeaders.firstValue(name.toString()).orElse(null); } @Override public Set<String> names() { return httpHeaders.map().keySet(); } @Override public Collection<List<String>> values() { return httpHeaders.map().values(); } @Override public <T> Optional<T> get(CharSequence name, ArgumentConversionContext<T> conversionContext) { return conversionService.convert(get(name), conversionContext); } }
HttpHeadersAdapter
java
netty__netty
handler/src/main/java/io/netty/handler/pcap/UDPPacket.java
{ "start": 705, "end": 1499 }
class ____ { private static final short UDP_HEADER_SIZE = 8; private UDPPacket() { // Prevent outside initialization } /** * Write UDP Packet * * @param byteBuf ByteBuf where Packet data will be set * @param payload Payload of this Packet * @param srcPort Source Port * @param dstPort Destination Port */ static void writePacket(ByteBuf byteBuf, ByteBuf payload, int srcPort, int dstPort) { byteBuf.writeShort(srcPort); // Source Port byteBuf.writeShort(dstPort); // Destination Port byteBuf.writeShort(UDP_HEADER_SIZE + payload.readableBytes()); // UDP Header Length + Payload Length byteBuf.writeShort(0x0001); // Checksum byteBuf.writeBytes(payload); // Payload of Data } }
UDPPacket
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/DummyHAService.java
{ "start": 9487, "end": 10094 }
class ____ implements FenceMethod { @Override public void checkArgs(String args) throws BadFencingConfigurationException { } @Override public boolean tryFence(HAServiceTarget target, String args) throws BadFencingConfigurationException { LOG.info("tryFence(" + target + ")"); DummyHAService svc = (DummyHAService)target; synchronized (svc) { svc.fenceCount++; } if (svc.failToFence) { LOG.info("Injected failure to fence"); return false; } svc.sharedResource.release(svc); return true; } } }
DummyFencer
java
apache__camel
components/camel-bean/src/main/java/org/apache/camel/component/bean/MethodsFilter.java
{ "start": 1051, "end": 1144 }
class ____ at retaining the right methods while parsing a given {@link java.lang.Class}. */
aims
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/EsqlBaseParser.java
{ "start": 265162, "end": 266141 }
class ____ extends ConstantContext { public ParameterContext parameter() { return getRuleContext(ParameterContext.class,0); } @SuppressWarnings("this-escape") public InputParameterContext(ConstantContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).enterInputParameter(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).exitInputParameter(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof EsqlBaseParserVisitor ) return ((EsqlBaseParserVisitor<? extends T>)visitor).visitInputParameter(this); else return visitor.visitChildren(this); } } @SuppressWarnings("CheckReturnValue") public static
InputParameterContext
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/subscribers/DefaultSubscriber.java
{ "start": 3336, "end": 4438 }
class ____<T> implements FlowableSubscriber<T> { Subscription upstream; @Override public final void onSubscribe(Subscription s) { if (EndConsumerHelper.validate(this.upstream, s, getClass())) { this.upstream = s; onStart(); } } /** * Requests from the upstream {@link Subscription}. * @param n the request amount, positive */ protected final void request(long n) { Subscription s = this.upstream; if (s != null) { s.request(n); } } /** * Cancels the upstream's {@link Subscription}. */ protected final void cancel() { Subscription s = this.upstream; this.upstream = SubscriptionHelper.CANCELLED; s.cancel(); } /** * Called once the subscription has been set on this observer; override this * to perform initialization or issue an initial request. * <p> * The default implementation requests {@link Long#MAX_VALUE}. */ protected void onStart() { request(Long.MAX_VALUE); } }
DefaultSubscriber
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/jsontype/PolymorphicTypeValidator.java
{ "start": 2738, "end": 2969 }
class ____ implements java.io.Serializable { private static final long serialVersionUID = 3L; /** * Definition of return values to indicate determination regarding validity. */ public
PolymorphicTypeValidator
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/formatter/TextFormatTests.java
{ "start": 1827, "end": 14265 }
class ____ extends ESTestCase { static final BlockFactory blockFactory = TestBlockFactory.getNonBreakingInstance(); public void testCsvContentType() { assertEquals("text/csv; charset=utf-8; header=present", CSV.contentType(req())); } public void testCsvContentTypeWithoutHeader() { assertEquals("text/csv; charset=utf-8; header=absent", CSV.contentType(reqWithParam("header", "absent"))); } public void testTsvContentType() { assertEquals("text/tab-separated-values; charset=utf-8", TSV.contentType(req())); } public void testCsvEscaping() { assertEscapedCorrectly("string", CSV, CSV.delimiter(), "string"); assertEscapedCorrectly("", CSV, CSV.delimiter(), ""); assertEscapedCorrectly("\"", CSV, CSV.delimiter(), "\"\"\"\""); assertEscapedCorrectly("\",\"", CSV, CSV.delimiter(), "\"\"\",\"\"\""); assertEscapedCorrectly("\"quo\"ted\"", CSV, CSV.delimiter(), "\"\"\"quo\"\"ted\"\"\""); assertEscapedCorrectly("one;two", CSV, ';', "\"one;two\""); assertEscapedCorrectly("one\ntwo", CSV, CSV.delimiter(), "\"one\ntwo\""); assertEscapedCorrectly("one\rtwo", CSV, CSV.delimiter(), "\"one\rtwo\""); final String inputString = randomStringForEscaping(); final String expectedResult; if (inputString.contains(",") || inputString.contains("\n") || inputString.contains("\r") || inputString.contains("\"")) { expectedResult = "\"" + inputString.replaceAll("\"", "\"\"") + "\""; } else { expectedResult = inputString; } assertEscapedCorrectly(inputString, CSV, ',', expectedResult); } public void testTsvEscaping() { assertEscapedCorrectly("string", TSV, null, "string"); assertEscapedCorrectly("", TSV, null, ""); assertEscapedCorrectly("\"", TSV, null, "\""); assertEscapedCorrectly("\t", TSV, null, "\\t"); assertEscapedCorrectly("\n\"\t", TSV, null, "\\n\"\\t"); final var inputString = randomStringForEscaping(); final var expectedResult = new StringBuilder(); for (int i = 0; i < inputString.length(); i++) { final var c = inputString.charAt(i); switch (c) { case '\n' -> expectedResult.append("\\n"); case '\t' -> expectedResult.append("\\t"); default -> expectedResult.append(c); } } assertEscapedCorrectly(inputString, TSV, null, expectedResult.toString()); } private static String randomStringForEscaping() { return String.join("", randomList(20, () -> randomFrom("a", "b", ",", ";", "\n", "\r", "\t", "\""))); } private static void assertEscapedCorrectly(String inputString, TextFormat format, Character delimiter, String expectedString) { try (var writer = new StringWriter()) { format.writeEscaped(inputString, delimiter, writer); writer.flush(); assertEquals(expectedString, writer.toString()); } catch (IOException e) { throw new AssertionError("impossible", e); } } public void testCsvFormatWithEmptyData() { String text = format(CSV, req(), emptyData()); assertEquals("name\r\n", text); } public void testTsvFormatWithEmptyData() { String text = format(TSV, req(), emptyData()); assertEquals("name\n", text); } public void testCsvFormatWithRegularData() { String text = format(CSV, req(), regularData()); assertEquals(""" string,number,location,location2,null_field\r Along The River Bank,708,POINT (12.0 56.0),POINT (1234.0 5678.0),\r Mind Train,280,POINT (-97.0 26.0),POINT (-9753.0 2611.0),\r """, text); } public void testCsvFormatNoHeaderWithRegularData() { String text = format(CSV, reqWithParam("header", "absent"), regularData()); assertEquals(""" Along The River Bank,708,POINT (12.0 56.0),POINT (1234.0 5678.0),\r Mind Train,280,POINT (-97.0 26.0),POINT (-9753.0 2611.0),\r """, text); } public void testCsvFormatWithCustomDelimiterRegularData() { Set<Character> forbidden = Set.of('"', '\r', '\n', '\t'); Character delim = randomValueOtherThanMany(forbidden::contains, () -> randomAlphaOfLength(1).charAt(0)); String text = format(CSV, reqWithParam("delimiter", String.valueOf(delim)), regularData()); List<String> terms = Arrays.asList( "string", "number", "location", "location2", "null_field", "Along The River Bank", "708", "POINT (12.0 56.0)", "POINT (1234.0 5678.0)", "", "Mind Train", "280", "POINT (-97.0 26.0)", "POINT (-9753.0 2611.0)", "" ); List<String> expectedTerms = terms.stream() .map(x -> x.contains(String.valueOf(delim)) ? '"' + x + '"' : x) .collect(Collectors.toList()); StringBuilder sb = new StringBuilder(); do { sb.append(expectedTerms.remove(0)); sb.append(delim); sb.append(expectedTerms.remove(0)); sb.append(delim); sb.append(expectedTerms.remove(0)); sb.append(delim); sb.append(expectedTerms.remove(0)); sb.append(delim); sb.append(expectedTerms.remove(0)); sb.append("\r\n"); } while (expectedTerms.size() > 0); assertEquals(sb.toString(), text); } public void testTsvFormatWithRegularData() { String text = format(TSV, req(), regularData()); assertEquals(""" string\tnumber\tlocation\tlocation2\tnull_field Along The River Bank\t708\tPOINT (12.0 56.0)\tPOINT (1234.0 5678.0)\t Mind Train\t280\tPOINT (-97.0 26.0)\tPOINT (-9753.0 2611.0)\t """, text); } public void testCsvFormatWithEscapedData() { String text = format(CSV, req(), escapedData()); assertEquals(""" first,""\"special""\"\r normal,""\"quo""ted"", "\r commas,"a,b,c, ,d,e,\t "\r """, text); } public void testCsvFormatWithCustomDelimiterEscapedData() { String text = format(CSV, reqWithParam("delimiter", "\\"), escapedData()); assertEquals(""" first\\""\"special""\"\r normal\\""\"quo""ted"", "\r commas\\"a,b,c, ,d,e,\t "\r """, text); } public void testTsvFormatWithEscapedData() { String text = format(TSV, req(), escapedData()); assertEquals(""" first\t"special" normal\t"quo"ted",\\n commas\ta,b,c,\\n,d,e,\\t\\n """, text); } public void testInvalidCsvDelims() { List<String> invalid = Arrays.asList("\"", "\r", "\n", "\t", "", "ab"); for (String c : invalid) { Exception e = expectThrows(IllegalArgumentException.class, () -> format(CSV, reqWithParam("delimiter", c), emptyData())); String msg; if (c.length() == 1) { msg = c.equals("\t") ? "illegal delimiter [TAB] specified as delimiter for the [csv] format; choose the [tsv] format instead" : "illegal reserved character specified as delimiter [" + c + "]"; } else { msg = "invalid " + (c.length() > 0 ? "multi-character" : "empty") + " delimiter [" + c + "]"; } assertEquals(msg, e.getMessage()); } } public void testPlainTextEmptyCursorWithColumns() { assertEquals(""" name \s --------------- """, format(PLAIN_TEXT, req(), emptyData())); } public void testPlainTextEmptyCursorWithoutColumns() { assertEquals( StringUtils.EMPTY, getTextBodyContent( PLAIN_TEXT.format(req(), new EsqlQueryResponse(emptyList(), emptyList(), 0, 0, null, false, false, 0L, 0L, null)) ) ); } public void testCsvFormatWithDropNullColumns() { String text = format(CSV, reqWithParam("drop_null_columns", "true"), regularData()); assertEquals(""" string,number,location,location2\r Along The River Bank,708,POINT (12.0 56.0),POINT (1234.0 5678.0)\r Mind Train,280,POINT (-97.0 26.0),POINT (-9753.0 2611.0)\r """, text); } public void testTsvFormatWithDropNullColumns() { String text = format(TSV, reqWithParam("drop_null_columns", "true"), regularData()); assertEquals(""" string\tnumber\tlocation\tlocation2 Along The River Bank\t708\tPOINT (12.0 56.0)\tPOINT (1234.0 5678.0) Mind Train\t280\tPOINT (-97.0 26.0)\tPOINT (-9753.0 2611.0) """, text); } private static EsqlQueryResponse emptyData() { return new EsqlQueryResponse( singletonList(new ColumnInfoImpl("name", "keyword", null)), emptyList(), 0, 0, null, false, false, 0L, 0L, null ); } private static EsqlQueryResponse regularData() { BlockFactory blockFactory = TestBlockFactory.getNonBreakingInstance(); // headers List<ColumnInfoImpl> headers = asList( new ColumnInfoImpl("string", "keyword", null), new ColumnInfoImpl("number", "integer", null), new ColumnInfoImpl("location", "geo_point", null), new ColumnInfoImpl("location2", "cartesian_point", null), new ColumnInfoImpl("null_field", "keyword", null) ); BytesRefArray geoPoints = new BytesRefArray(2, BigArrays.NON_RECYCLING_INSTANCE); geoPoints.append(GEO.asWkb(new Point(12, 56))); geoPoints.append(GEO.asWkb(new Point(-97, 26))); // values List<Page> values = List.of( new Page( blockFactory.newBytesRefBlockBuilder(2) .appendBytesRef(new BytesRef("Along The River Bank")) .appendBytesRef(new BytesRef("Mind Train")) .build(), blockFactory.newIntArrayVector(new int[] { 11 * 60 + 48, 4 * 60 + 40 }, 2).asBlock(), blockFactory.newBytesRefArrayVector(geoPoints, 2).asBlock(), blockFactory.newBytesRefBlockBuilder(2) .appendBytesRef(CARTESIAN.asWkb(new Point(1234, 5678))) .appendBytesRef(CARTESIAN.asWkb(new Point(-9753, 2611))) .build(), blockFactory.newConstantNullBlock(2) ) ); return new EsqlQueryResponse(headers, values, 0, 0, null, false, false, 0L, 0L, null); } private static EsqlQueryResponse escapedData() { // headers List<ColumnInfoImpl> headers = asList( new ColumnInfoImpl("first", "keyword", null), new ColumnInfoImpl("\"special\"", "keyword", null) ); // values List<Page> values = List.of( new Page( blockFactory.newBytesRefBlockBuilder(2) .appendBytesRef(new BytesRef("normal")) .appendBytesRef(new BytesRef("commas")) .build(), blockFactory.newBytesRefBlockBuilder(2) .appendBytesRef(new BytesRef("\"quo\"ted\",\n")) .appendBytesRef(new BytesRef("a,b,c,\n,d,e,\t\n")) .build() ) ); return new EsqlQueryResponse(headers, values, 0, 0, null, false, false, 0L, 0L, null); } private static RestRequest req() { return new FakeRestRequest(); } private static RestRequest reqWithParam(String paramName, String paramVal) { return new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withParams(singletonMap(paramName, paramVal)).build(); } private String format(TextFormat format, RestRequest request, EsqlQueryResponse response) { return getTextBodyContent(format.format(request, response)); } }
TextFormatTests
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/oncrpc/RegistrationClient.java
{ "start": 1145, "end": 1462 }
class ____ extends SimpleTcpClient { public static final Logger LOG = LoggerFactory.getLogger(RegistrationClient.class); public RegistrationClient(String host, int port, XDR request) { super(host, port, request); } /** * Handler to handle response from the server. */ static
RegistrationClient
java
apache__spark
common/unsafe/src/main/java/org/apache/spark/sql/catalyst/util/CollationFactory.java
{ "start": 11676, "end": 11893 }
enum ____ { PREDEFINED, USER_DEFINED } /** * Bit 29 in collation ID having value 0 for UTF8_BINARY family and 1 for ICU family of * collations. */ protected
DefinitionOrigin
java
apache__camel
components/camel-aws/camel-aws2-sns/src/main/java/org/apache/camel/component/aws2/sns/MessageDeduplicationIdStrategy.java
{ "start": 891, "end": 995 }
interface ____ { String getMessageDeduplicationId(Exchange exchange); }
MessageDeduplicationIdStrategy
java
bumptech__glide
library/test/src/test/java/com/bumptech/glide/load/data/mediastore/MediaStoreUtilTest.java
{ "start": 459, "end": 1038 }
class ____ { @Test public void isAndroidPickerUri_notAndroidPickerUri_returnsFalse() { Uri mediaStoreUri = Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "123"); assertThat(MediaStoreUtil.isAndroidPickerUri(mediaStoreUri)).isFalse(); } @Test public void isAndroidPickerUri_identifiesAndroidPickerUri_returnsTrue() { Uri androidPickerUri = Uri.parse("content://media/picker/0/com.android.providers.media.photopicker/media/123"); assertThat(MediaStoreUtil.isAndroidPickerUri(androidPickerUri)).isTrue(); } }
MediaStoreUtilTest
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java
{ "start": 26891, "end": 26972 }
class ____ { } @RestControllerAdvice("com.example") static
ControllerAdviceClass
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/builder/NoClassNameToStringStyleTest.java
{ "start": 1258, "end": 7413 }
class ____ extends AbstractLangTest { private final Integer base = Integer.valueOf(5); @BeforeEach public void setUp() { ToStringBuilder.setDefaultStyle(ToStringStyle.NO_CLASS_NAME_STYLE); } @AfterEach public void tearDown() { ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE); } @Test void testAppendSuper() { assertEquals("[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals("[<null>]", new ToStringBuilder(base).appendSuper("Integer@8888[<null>]").toString()); assertEquals("[a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals("[<null>,a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[<null>]").append("a", "hello").toString()); assertEquals("[a=hello]", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString()); } @Test void testArray() { final Integer i3 = Integer.valueOf(3); final Integer i4 = Integer.valueOf(4); assertEquals("[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString()); assertEquals("[a={}]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString()); assertEquals("[a=<size=1>]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString()); assertEquals("[a={3}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString()); assertEquals("[a=<size=2>]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString()); assertEquals("[a={3,4}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString()); } @Test void testBlank() { assertEquals("[]", new ToStringBuilder(base).toString()); } @Test void testCollection() { final Integer i3 = Integer.valueOf(3); final Integer i4 = Integer.valueOf(4); assertEquals("[a=<size=0>]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString()); assertEquals("[a=[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString()); assertEquals("[a=<size=1>]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString()); assertEquals("[a=[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString()); assertEquals("[a=<size=2>]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString()); assertEquals("[a=[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString()); } @Test void testLong() { assertEquals("[3]", new ToStringBuilder(base).append(3L).toString()); assertEquals("[a=3]", new ToStringBuilder(base).append("a", 3L).toString()); assertEquals("[a=3,b=4]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString()); } @Test void testLongArray() { long[] array = {1, 2, -3, 4}; assertEquals("[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals("[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals("[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals("[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test void testLongArrayArray() { long[][] array = {{1, 2}, null, {5}}; assertEquals("[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals("[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals("[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals("[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test void testMap() { assertEquals("[a=<size=0>]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString()); assertEquals("[a={}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString()); assertEquals("[a=<size=1>]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString()); assertEquals("[a={k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString()); } @Test void testObject() { final Integer i3 = Integer.valueOf(3); final Integer i4 = Integer.valueOf(4); assertEquals("[<null>]", new ToStringBuilder(base).append((Object) null).toString()); assertEquals("[3]", new ToStringBuilder(base).append(i3).toString()); assertEquals("[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).toString()); assertEquals("[a=3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals("[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals("[a=<Integer>]", new ToStringBuilder(base).append("a", i3, false).toString()); } @Test void testObjectArray() { Object[] array = {null, base, new int[] {3, 6}}; assertEquals("[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString()); assertEquals("[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals("[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals("[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test void testPerson() { final Person p = new Person(); p.name = "John Q. Public"; p.age = 45; p.smoker = true; assertEquals("[name=John Q. Public,age=45,smoker=true]", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).toString()); } }
NoClassNameToStringStyleTest
java
elastic__elasticsearch
x-pack/plugin/old-lucene-versions/src/test/java/org/elasticsearch/xpack/lucene/bwc/codecs/lucene50/Lucene50PostingsWriter.java
{ "start": 3048, "end": 3297 }
class ____ writes docId(maybe frq,pos,offset,payloads) list * with postings format. * * Postings list for each term will be stored separately. * * @see Lucene50SkipWriter for details about skipping setting and postings layout. */ public final
that
java
FasterXML__jackson-core
src/main/java/tools/jackson/core/base/GeneratorBase.java
{ "start": 418, "end": 633 }
class ____ part of API that a JSON generator exposes * to applications, adds shared internal methods that sub-classes * can use and adds some abstract methods sub-classes must implement. */ public abstract
implements
java
apache__hadoop
hadoop-common-project/hadoop-annotations/src/main/java/org/apache/hadoop/classification/InterfaceStability.java
{ "start": 2082, "end": 2251 }
interface ____ {}; /** * Evolving, but can break compatibility at minor release (i.e. m.x) */ @Documented @Retention(RetentionPolicy.RUNTIME) public @
Stable
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/operators/windowing/functions/InternalIterableProcessAllWindowFunction.java
{ "start": 1505, "end": 3348 }
class ____<IN, OUT, W extends Window> extends WrappingFunction<ProcessAllWindowFunction<IN, OUT, W>> implements InternalWindowFunction<Iterable<IN>, OUT, Byte, W> { private static final long serialVersionUID = 1L; private transient InternalProcessAllWindowContext<IN, OUT, W> ctx; public InternalIterableProcessAllWindowFunction( ProcessAllWindowFunction<IN, OUT, W> wrappedFunction) { super(wrappedFunction); } @Override public void open(OpenContext openContext) throws Exception { super.open(openContext); ProcessAllWindowFunction<IN, OUT, W> wrappedFunction = this.wrappedFunction; this.ctx = new InternalProcessAllWindowContext<>(wrappedFunction); } @Override public void process( Byte key, final W window, final InternalWindowContext context, Iterable<IN> input, Collector<OUT> out) throws Exception { this.ctx.window = window; this.ctx.internalContext = context; ProcessAllWindowFunction<IN, OUT, W> wrappedFunction = this.wrappedFunction; wrappedFunction.process(ctx, input, out); } @Override public void clear(final W window, final InternalWindowContext context) throws Exception { this.ctx.window = window; this.ctx.internalContext = context; ProcessAllWindowFunction<IN, OUT, W> wrappedFunction = this.wrappedFunction; wrappedFunction.clear(ctx); } @Override public RuntimeContext getRuntimeContext() { throw new RuntimeException("This should never be called."); } @Override public IterationRuntimeContext getIterationRuntimeContext() { throw new RuntimeException("This should never be called."); } }
InternalIterableProcessAllWindowFunction
java
alibaba__nacos
client/src/main/java/com/alibaba/nacos/client/naming/core/Balancer.java
{ "start": 1142, "end": 3009 }
class ____ { /** * Select all instance. * * @param serviceInfo service information * @return all instance of services */ public static List<Instance> selectAll(ServiceInfo serviceInfo) { List<Instance> hosts = serviceInfo.getHosts(); if (CollectionUtils.isEmpty(hosts)) { throw new IllegalStateException("no host to srv for serviceInfo: " + serviceInfo.getName()); } return hosts; } /** * Random select one instance from service. * * @param dom service * @return random instance */ public static Instance selectHost(ServiceInfo dom) { return getHostByRandomWeight(selectAll(dom)); } } /** * Return one host from the host list by random-weight. * * @param hosts The list of the host. * @return The random-weight result of the host */ protected static Instance getHostByRandomWeight(List<Instance> hosts) { NAMING_LOGGER.debug("entry randomWithWeight"); if (hosts == null || hosts.size() == 0) { NAMING_LOGGER.debug("hosts == null || hosts.size() == 0"); return null; } NAMING_LOGGER.debug("new Chooser"); List<Pair<Instance>> hostsWithWeight = new ArrayList<>(); for (Instance host : hosts) { if (host.isHealthy()) { hostsWithWeight.add(new Pair<Instance>(host, host.getWeight())); } } NAMING_LOGGER.debug("for (Host host : hosts)"); Chooser<String, Instance> vipChooser = new Chooser<>("www.taobao.com"); vipChooser.refresh(hostsWithWeight); NAMING_LOGGER.debug("vipChooser.refresh"); return vipChooser.randomWithWeight(); } }
RandomByWeight
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/configproperties/ValidatedGetterConfig.java
{ "start": 1001, "end": 1355 }
class ____ { private URL url; private String name; @NotNull public URL getUrl() { return url; } public void setUrl(URL url) { this.url = url; } @NotBlank public String getName() { return name; } public void setName(String name) { this.name = name; } }
ValidatedGetterConfig
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java
{ "start": 11856, "end": 12510 }
class ____ { public void badApis(Date date) { // BUG: Diagnostic contains: DoNotCall date.setHours(1); // BUG: Diagnostic contains: DoNotCall date.setMinutes(1); // BUG: Diagnostic contains: DoNotCall date.setSeconds(1); } } """) .doTest(); } @Test public void javaSqlDate_staticallyTypedAsJavaUtilDate() { testHelper .addSourceLines( "TestClass.java", """ import java.time.Instant; import java.util.Date; public
TestClass
java
spring-projects__spring-boot
module/spring-boot-reactor/src/main/java/org/springframework/boot/reactor/autoconfigure/ReactorProperties.java
{ "start": 902, "end": 1320 }
class ____ { /** * Context Propagation support mode for Reactor operators. */ private ContextPropagationMode contextPropagation = ContextPropagationMode.LIMITED; public ContextPropagationMode getContextPropagation() { return this.contextPropagation; } public void setContextPropagation(ContextPropagationMode contextPropagation) { this.contextPropagation = contextPropagation; } public
ReactorProperties
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/PreviewDatafeedAction.java
{ "start": 12383, "end": 13604 }
class ____ extends ActionResponse implements ToXContentObject { private final BytesReference preview; public Response(BytesReference preview) { this.preview = preview; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeBytesReference(preview); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { try (InputStream stream = preview.streamInput()) { builder.rawValue(stream, XContentType.JSON); } return builder; } @Override public int hashCode() { return Objects.hash(preview); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Response other = (Response) obj; return Objects.equals(preview, other.preview); } @Override public final String toString() { return Strings.toString(this); } } }
Response
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/observers/async/AsyncObserverExceptionTest.java
{ "start": 5091, "end": 5285 }
class ____ { @Inject Event<String> event; CompletionStage<String> produceAsync(String value) { return event.fireAsync(value); } } }
StringProducer
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Issue900.java
{ "start": 199, "end": 447 }
class ____ extends TestCase { public void test_for_issue() throws Exception { Model model = JSON.parseObject("{\"id\":123}", Model.class, Feature.SupportNonPublicField); assertEquals(123, model.id); } public static
Issue900
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/metrics/MpJvmMetricsTest.java
{ "start": 690, "end": 4670 }
class ____ extends BaseJvmMetricsTest { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addClasses(InMemoryMetricExporter.class, InMemoryMetricExporterProvider.class) .addAsResource(new StringAsset(InMemoryMetricExporterProvider.class.getCanonicalName()), "META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider") .add(new StringAsset( "quarkus.otel.metrics.enabled=true\n" + "quarkus.otel.traces.exporter=none\n" + "quarkus.otel.logs.exporter=none\n" + "quarkus.otel.metrics.exporter=in-memory\n" + "quarkus.otel.metric.export.interval=300ms\n"), "application.properties")); // No need to reset between tests. Data is test independent. Will also run faster. @Test void testClassLoadedMetrics() throws IOException { assertMetric("jvm.class.loaded", "Number of classes loaded since JVM start.", "{class}", MetricDataType.LONG_SUM); } @Test void testClassUnloadedMetrics() throws IOException { assertMetric("jvm.class.unloaded", "Number of classes unloaded since JVM start.", "{class}", MetricDataType.LONG_SUM); } @Test void testClassCountMetrics() { assertMetric("jvm.class.count", "Number of classes currently loaded.", "{class}", MetricDataType.LONG_SUM); } @Test void testCpuTimeMetric() throws IOException { assertMetric("jvm.cpu.time", "CPU time used by the process as reported by the JVM.", "s", MetricDataType.DOUBLE_SUM); } @Test void testCpuCountMetric() throws IOException { assertMetric("jvm.cpu.count", "Number of processors available to the Java virtual machine.", "{cpu}", MetricDataType.LONG_SUM); } @Test void testCpuRecentUtilizationMetric() throws IOException { assertMetric("jvm.cpu.recent_utilization", "Recent CPU utilization for the process as reported by the JVM.", "1", MetricDataType.DOUBLE_GAUGE); } @Test void testGarbageCollectionCountMetric() { System.gc(); assertMetric("jvm.gc.duration", "Duration of JVM garbage collection actions.", "s", MetricDataType.HISTOGRAM); } @Test void testJvmMemoryUsedMetric() throws IOException { assertMetric("jvm.memory.used", "Measure of memory used.", "By", MetricDataType.LONG_SUM); } @Test void testJvmMemoryCommittedMetric() throws IOException { assertMetric("jvm.memory.committed", "Measure of memory committed.", "By", MetricDataType.LONG_SUM); } @Test void testMemoryLimitMetric() throws IOException { assertMetric("jvm.memory.limit", "Measure of max obtainable memory.", "By", MetricDataType.LONG_SUM); } @Test void testMemoryUsedAfterLastGcMetric() throws IOException { assertMetric("jvm.memory.used_after_last_gc", "Measure of memory used, as measured after the most recent garbage collection event on this pool.", "By", MetricDataType.LONG_SUM); } @Disabled("Because of this challenge: https://github.com/eclipse/microprofile-telemetry/issues/241") @Test void testThreadCountMetric() throws IOException { assertMetric("jvm.thread.count", "Number of executing platform threads.", "{thread}", MetricDataType.LONG_SUM); } }
MpJvmMetricsTest
java
alibaba__nacos
api/src/test/java/com/alibaba/nacos/api/remote/DefaultRequestFutureTest.java
{ "start": 1600, "end": 14509 }
class ____ { private static final String CONNECTION_ID = "1233_1.1.1.1_3306"; private static final String REQUEST_ID = "10000"; @Mock private Response response; @Mock private ExecutorService executor; private long timestamp; @BeforeEach void setUp() throws Exception { timestamp = System.currentTimeMillis(); } @AfterEach void tearDown() throws Exception { } @Test void testSyncGetResponseSuccessWithoutTimeout() throws InterruptedException { DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(100); requestFuture.setResponse(response); } catch (Exception ignored) { } }).start(); Response actual = requestFuture.get(); assertEquals(response, actual); assertEquals(CONNECTION_ID, requestFuture.getConnectionId()); assertEquals(REQUEST_ID, requestFuture.getRequestId()); assertTrue(requestFuture.isDone()); assertTrue(requestFuture.getTimeStamp() >= timestamp); } @Test void testSyncGetResponseFailureWithoutTimeout() throws InterruptedException { DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(100); requestFuture.setFailResult(new RuntimeException("test")); } catch (Exception ignored) { } }).start(); Response actual = requestFuture.get(); assertNull(actual); assertEquals(CONNECTION_ID, requestFuture.getConnectionId()); assertEquals(REQUEST_ID, requestFuture.getRequestId()); assertTrue(requestFuture.isDone()); assertTrue(requestFuture.getTimeStamp() >= timestamp); } @Test void testSyncGetResponseSuccessWithTimeout() throws InterruptedException, TimeoutException { DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(100); requestFuture.setResponse(response); } catch (Exception ignored) { } }).start(); Response actual = requestFuture.get(1000L); assertEquals(response, actual); assertEquals(CONNECTION_ID, requestFuture.getConnectionId()); assertEquals(REQUEST_ID, requestFuture.getRequestId()); assertTrue(requestFuture.isDone()); assertTrue(requestFuture.getTimeStamp() >= timestamp); } @Test void testSyncGetResponseSuccessWithInvalidTimeout() throws InterruptedException, TimeoutException { DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(100); requestFuture.setResponse(response); } catch (Exception ignored) { } }).start(); Response actual = requestFuture.get(-1L); assertEquals(response, actual); assertEquals(CONNECTION_ID, requestFuture.getConnectionId()); assertEquals(REQUEST_ID, requestFuture.getRequestId()); assertTrue(requestFuture.isDone()); assertTrue(requestFuture.getTimeStamp() >= timestamp); } @Test void testSyncGetResponseFailureWithTimeout() throws InterruptedException, TimeoutException { assertThrows(TimeoutException.class, () -> { DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID); requestFuture.get(100L); }); } @Test void testSyncGetResponseSuccessByTriggerWithoutTimeout() throws InterruptedException { MockFutureTrigger trigger = new MockFutureTrigger(); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(100); requestFuture.setResponse(response); } catch (Exception ignored) { } }).start(); Response actual = requestFuture.get(); assertEquals(response, actual); assertEquals(CONNECTION_ID, requestFuture.getConnectionId()); assertEquals(REQUEST_ID, requestFuture.getRequestId()); assertTrue(requestFuture.isDone()); assertTrue(requestFuture.getTimeStamp() >= timestamp); assertFalse(trigger.isTimeout); } @Test void testSyncGetResponseFailureByTriggerWithoutTimeout() throws InterruptedException { MockFutureTrigger trigger = new MockFutureTrigger(); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(100); requestFuture.setFailResult(new RuntimeException("test")); } catch (Exception ignored) { } }).start(); Response actual = requestFuture.get(); assertNull(actual); assertEquals(CONNECTION_ID, requestFuture.getConnectionId()); assertEquals(REQUEST_ID, requestFuture.getRequestId()); assertTrue(requestFuture.isDone()); assertTrue(requestFuture.getTimeStamp() >= timestamp); assertFalse(trigger.isTimeout); } @Test void testSyncGetResponseSuccessByTriggerWithTimeout() throws InterruptedException, TimeoutException { MockFutureTrigger trigger = new MockFutureTrigger(); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(100); requestFuture.setResponse(response); } catch (Exception ignored) { } }).start(); Response actual = requestFuture.get(1000L); assertEquals(response, actual); assertEquals(CONNECTION_ID, requestFuture.getConnectionId()); assertEquals(REQUEST_ID, requestFuture.getRequestId()); assertTrue(requestFuture.isDone()); assertTrue(requestFuture.getTimeStamp() >= timestamp); assertFalse(trigger.isTimeout); assertFalse(trigger.isCancel); } @Test void testSyncGetResponseFailureByTriggerWithTimeout() throws InterruptedException, TimeoutException { assertThrows(TimeoutException.class, () -> { MockFutureTrigger trigger = new MockFutureTrigger(); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); try { requestFuture.get(100L); } finally { assertTrue(trigger.isTimeout); } }); } @Test void testASyncGetResponseSuccessWithoutTimeout() throws InterruptedException { MockFutureTrigger trigger = new MockFutureTrigger(); MockRequestCallback callback = new MockRequestCallback(200L); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, trigger); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(100); requestFuture.setResponse(response); } catch (Exception ignored) { } }).start(); TimeUnit.MILLISECONDS.sleep(250); assertEquals(response, callback.response); assertNull(callback.exception); assertFalse(trigger.isTimeout); assertFalse(trigger.isTimeout); assertEquals(callback, requestFuture.getRequestCallBack()); } @Test void testASyncGetResponseSuccessWithoutTimeoutByExecutor() throws InterruptedException { MockFutureTrigger trigger = new MockFutureTrigger(); MockRequestCallback callback = new MockRequestCallback(executor, 200L); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, trigger); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(100); requestFuture.setResponse(response); } catch (Exception ignored) { } }).start(); TimeUnit.MILLISECONDS.sleep(250); assertEquals(callback, requestFuture.getRequestCallBack()); verify(executor).execute(any(DefaultRequestFuture.CallBackHandler.class)); } @Test void testASyncGetResponseFailureWithoutTimeout() throws InterruptedException { MockFutureTrigger trigger = new MockFutureTrigger(); MockRequestCallback callback = new MockRequestCallback(1000L); DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, trigger); new Thread(() -> { try { TimeUnit.MILLISECONDS.sleep(100); requestFuture.setFailResult(new RuntimeException("test")); } catch (Exception ignored) { } }).start(); TimeUnit.MILLISECONDS.sleep(250); assertNull(callback.response); assertTrue(callback.exception instanceof RuntimeException); assertFalse(trigger.isTimeout); assertEquals(callback, requestFuture.getRequestCallBack()); } @Test void testASyncGetResponseFailureWithTimeout() throws InterruptedException { MockFutureTrigger trigger = new MockFutureTrigger(); MockRequestCallback callback = new MockRequestCallback(100L); final DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, trigger); TimeUnit.MILLISECONDS.sleep(500); assertNull(callback.response); assertTrue(callback.exception instanceof TimeoutException); assertTrue(trigger.isTimeout); assertEquals(callback, requestFuture.getRequestCallBack()); } @Test void testSyncRequestFutureCancelFailedWithTimeout() throws InterruptedException { MockFutureTrigger trigger = new MockFutureTrigger(); final DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); assertThrows(TimeoutException.class, () -> requestFuture.get(100L)); requestFuture.cancel(true); assertTrue(trigger.isTimeout); assertFalse(trigger.isCancel); } @Test void testSyncRequestFutureCancelFailed() throws InterruptedException { MockFutureTrigger trigger = new MockFutureTrigger(); final DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, null, trigger); requestFuture.cancel(true); assertFalse(trigger.isTimeout); assertFalse(trigger.isCancel); } @Test void testASyncRequestFutureCancelFailedWithTrigger() throws InterruptedException { MockFutureTrigger trigger = new MockFutureTrigger(); MockRequestCallback callback = new MockRequestCallback(100L); final DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, trigger); TimeUnit.MILLISECONDS.sleep(500L); requestFuture.cancel(true); assertNull(callback.response); assertTrue(callback.exception instanceof TimeoutException); assertTrue(trigger.isTimeout); assertFalse(trigger.isCancel); assertEquals(callback, requestFuture.getRequestCallBack()); } @Test void testASyncRequestFutureCancelSuccessWithTrigger() throws InterruptedException { MockFutureTrigger trigger = new MockFutureTrigger(); MockRequestCallback callback = new MockRequestCallback(500L); final DefaultRequestFuture requestFuture = new DefaultRequestFuture(CONNECTION_ID, REQUEST_ID, callback, trigger); TimeUnit.MILLISECONDS.sleep(100L); requestFuture.cancel(true); assertNull(callback.response); assertNull(callback.exception); assertFalse(trigger.isTimeout); assertTrue(trigger.isCancel); assertEquals(callback, requestFuture.getRequestCallBack()); } @Test void testFutureTriggerDefaultMethod() { final AtomicInteger callCount = new AtomicInteger(0); DefaultRequestFuture.FutureTrigger mockTrigger = callCount::incrementAndGet; assertEquals(0, callCount.get()); mockTrigger.triggerOnTimeout(); assertEquals(1, callCount.get()); mockTrigger.triggerOnCancel(); assertEquals(2, callCount.get()); } private
DefaultRequestFutureTest
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/event/DefaultEventBus.java
{ "start": 434, "end": 1291 }
class ____ implements EventBus { private final Sinks.Many<Event> bus; private final Scheduler scheduler; private final EventRecorder recorder = EventRecorder.getInstance(); public DefaultEventBus(Scheduler scheduler) { this.bus = Sinks.many().multicast().directBestEffort(); this.scheduler = scheduler; } @Override public Flux<Event> get() { return bus.asFlux().onBackpressureDrop().publishOn(scheduler); } @Override public void publish(Event event) { recorder.record(event); Sinks.EmitResult emitResult; while ((emitResult = bus.tryEmitNext(event)) == Sinks.EmitResult.FAIL_NON_SERIALIZED) { // busy-loop } if (emitResult != Sinks.EmitResult.FAIL_ZERO_SUBSCRIBER) { emitResult.orThrow(); } } }
DefaultEventBus
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/support/ClassFilters.java
{ "start": 3708, "end": 4610 }
class ____ implements ClassFilter, Serializable { private final ClassFilter[] filters; UnionClassFilter(ClassFilter[] filters) { this.filters = filters; } @Override public boolean matches(Class<?> clazz) { for (ClassFilter filter : this.filters) { if (filter.matches(clazz)) { return true; } } return false; } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof UnionClassFilter that && ObjectUtils.nullSafeEquals(this.filters, that.filters))); } @Override public int hashCode() { return Arrays.hashCode(this.filters); } @Override public String toString() { return getClass().getName() + ": " + Arrays.toString(this.filters); } } /** * ClassFilter implementation for an intersection of the given ClassFilters. */ @SuppressWarnings("serial") private static
UnionClassFilter
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_failureWithActualExpected_Test.java
{ "start": 1147, "end": 3147 }
class ____ { private ConcreteAssert assertion; private Object actual = "Actual"; private Object expected = "Expected"; @BeforeEach void setup() { assertion = new ConcreteAssert("foo"); } @Test void should_create_failure_with_simple_message() { // WHEN AssertionFailedError afe = assertion.failureWithActualExpected(actual, expected, "fail"); // THEN then(afe).hasMessage("fail"); then(afe.getActual().getEphemeralValue()).isSameAs(actual); then(afe.getExpected().getEphemeralValue()).isSameAs(expected); } @Test void should_create_failure_with_message_having_args() { // WHEN AssertionFailedError afe = assertion.failureWithActualExpected(actual, expected, "fail %d %s %%s", 5, "times"); // THEN then(afe).hasMessage("fail 5 times %s"); then(afe.getActual().getEphemeralValue()).isSameAs(actual); then(afe.getExpected().getEphemeralValue()).isSameAs(expected); } @Test void should_keep_description_set_by_user() { // WHEN AssertionFailedError afe = assertion.as("user description") .failureWithActualExpected(actual, expected, "fail %d %s", 5, "times"); // THEN then(afe).hasMessage("[user description] fail 5 times"); then(afe.getActual().getEphemeralValue()).isSameAs(actual); then(afe.getExpected().getEphemeralValue()).isSameAs(expected); } @Test void should_keep_specific_error_message_and_description_set_by_user() { // WHEN AssertionFailedError afe = assertion.as("test context") .overridingErrorMessage("my %d errors %s", 5, "!") .failureWithActualExpected(actual, expected, "%d %s", 5, "time"); // THEN then(afe).hasMessage("[test context] my 5 errors !"); then(afe.getActual().getEphemeralValue()).isSameAs(actual); then(afe.getExpected().getEphemeralValue()).isSameAs(expected); } }
AbstractAssert_failureWithActualExpected_Test
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDelayTest.java
{ "start": 1120, "end": 3847 }
class ____ extends RxJavaTest { @Test public void success() { Maybe.just(1).delay(100, TimeUnit.MILLISECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(1); } @Test public void error() { Maybe.error(new TestException()).delay(100, TimeUnit.MILLISECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test public void complete() { Maybe.empty().delay(100, TimeUnit.MILLISECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(); } @Test public void disposeDuringDelay() { TestScheduler scheduler = new TestScheduler(); TestObserver<Integer> to = Maybe.just(1).delay(100, TimeUnit.MILLISECONDS, scheduler) .test(); to.dispose(); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); to.assertEmpty(); } @Test public void dispose() { PublishProcessor<Integer> pp = PublishProcessor.create(); TestObserver<Integer> to = pp.singleElement().delay(100, TimeUnit.MILLISECONDS).test(); assertTrue(pp.hasSubscribers()); to.dispose(); assertFalse(pp.hasSubscribers()); } @Test public void isDisposed() { PublishProcessor<Integer> pp = PublishProcessor.create(); TestHelper.checkDisposed(pp.singleElement().delay(100, TimeUnit.MILLISECONDS)); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeMaybe(new Function<Maybe<Object>, Maybe<Object>>() { @Override public Maybe<Object> apply(Maybe<Object> f) throws Exception { return f.delay(100, TimeUnit.MILLISECONDS); } }); } @Test public void delayedErrorOnSuccess() { final TestScheduler scheduler = new TestScheduler(); final TestObserver<Integer> observer = Maybe.just(1) .delay(5, TimeUnit.SECONDS, scheduler, true) .test(); scheduler.advanceTimeTo(2, TimeUnit.SECONDS); observer.assertNoValues(); scheduler.advanceTimeTo(5, TimeUnit.SECONDS); observer.assertValue(1); } @Test public void delayedErrorOnError() { final TestScheduler scheduler = new TestScheduler(); final TestObserver<?> observer = Maybe.error(new TestException()) .delay(5, TimeUnit.SECONDS, scheduler, true) .test(); scheduler.advanceTimeTo(2, TimeUnit.SECONDS); observer.assertNoErrors(); scheduler.advanceTimeTo(5, TimeUnit.SECONDS); observer.assertError(TestException.class); } }
MaybeDelayTest
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java
{ "start": 11237, "end": 12922 }
interface ____ remote service */ public String getServiceInterface() { return interfaceName; } /** * The group of the service */ public String getGroup() { // Compatible with seata-1.4.0: io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc() return referenceConfig.getGroup(); } /** * The version of the service */ public String getVersion() { // Compatible with seata-1.4.0: io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc() return referenceConfig.getVersion(); } public String getKey() { return key; } public Map<String, Object> getReferenceProps() { return referenceProps; } public MutablePropertyValues getPropertyValues() { return propertyValues; } public ReferenceConfig getReferenceConfig() { return referenceConfig; } public void setKeyAndReferenceConfig(String key, ReferenceConfig referenceConfig) { this.key = key; this.referenceConfig = referenceConfig; } /** * Create lazy proxy for reference. */ private void createLazyProxy() { // set proxy interfaces // see also: org.apache.dubbo.rpc.proxy.AbstractProxyFactory.getProxy(org.apache.dubbo.rpc.Invoker<T>, boolean) List<Class<?>> interfaces = new ArrayList<>(); interfaces.add(interfaceClass); Class<?>[] internalInterfaces = AbstractProxyFactory.getInternalInterfaces(); Collections.addAll(interfaces, internalInterfaces); if (!StringUtils.isEquals(interfaceClass.getName(), interfaceName)) { // add service
of
java
mockito__mockito
mockito-core/src/main/java/org/mockito/ArgumentCaptor.java
{ "start": 8003, "end": 8055 }
class ____ captured. * * @return the raw
being