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 | quarkusio__quarkus | integration-tests/narayana-lra/src/test/java/io/quarkus/it/lra/LRAITTestClassOrderer.java | {
"start": 270,
"end": 592
} | class ____ to ensure that tests with the "ProfileTest" suffix are run last.
* This is necessary because other tests require the LRA Dev Service coordinator to be started first,
* and we also want to test that the Dev Service coordinator is not started when the particular
* config properties are defined.
*/
public | orderer |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/object/GenericStoredProcedure.java | {
"start": 1196,
"end": 1254
} | class ____ extends StoredProcedure {
}
| GenericStoredProcedure |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AbfsTailLatencyTracker.java | {
"start": 1457,
"end": 7206
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(
AbfsTailLatencyTracker.class);
private static AbfsTailLatencyTracker singletonLatencyTracker;
private static final ReentrantLock LOCK = new ReentrantLock();
private static final int HISTOGRAM_MAX_VALUE = 60_000;
private static final int HISTOGRAM_SIGNIFICANT_FIGURES = 3;
private final Map<AbfsRestOperationType, SlidingWindowHdrHistogram>
operationLatencyMap = new HashMap<>();
private final int talLatencyAnalysisWindowInMillis;
private final int tailLatencyAnalysisWindowGranularity;
private final int tailLatencyPercentile;
private final int tailLatencyMinSampleSize;
private final int tailLatencyMinDeviation;
private final int tailLatencyComputationIntervalInMillis;
/**
* Constructor to initialize the latency tracker with configuration.
* @param abfsConfiguration Configuration settings for latency tracking.
*/
public AbfsTailLatencyTracker(final AbfsConfiguration abfsConfiguration) {
this.talLatencyAnalysisWindowInMillis = abfsConfiguration.getTailLatencyAnalysisWindowInMillis();
this.tailLatencyAnalysisWindowGranularity = abfsConfiguration.getTailLatencyAnalysisWindowGranularity();
this.tailLatencyPercentile = abfsConfiguration.getTailLatencyPercentile();
this.tailLatencyMinSampleSize = abfsConfiguration.getTailLatencyMinSampleSize();
this.tailLatencyMinDeviation = abfsConfiguration.getTailLatencyMinDeviation();
this.tailLatencyComputationIntervalInMillis = abfsConfiguration.getTailLatencyComputationIntervalInMillis();
ScheduledExecutorService histogramRotatorThread = Executors.newSingleThreadScheduledExecutor(
r -> {
Thread t = new Thread(r, "Histogram-Rotator-Thread");
t.setDaemon(true);
return t;
});
long rotationInterval = talLatencyAnalysisWindowInMillis/tailLatencyAnalysisWindowGranularity;
histogramRotatorThread.scheduleAtFixedRate(this::rotateHistograms,
rotationInterval, rotationInterval, TimeUnit.MILLISECONDS);
ScheduledExecutorService tailLatencyComputationThread = Executors.newSingleThreadScheduledExecutor(
r -> {
Thread t = new Thread(r, "Tail-Latency-Computation-Thread");
t.setDaemon(true);
return t;
});
tailLatencyComputationThread.scheduleAtFixedRate(this::computePercentiles,
tailLatencyComputationIntervalInMillis, tailLatencyComputationIntervalInMillis, TimeUnit.MILLISECONDS);
}
/**
* Rotates all histograms to ensure they reflect the most recent latency data.
* This method is called periodically based on the configured rotation interval.
*/
private void rotateHistograms() {
for (SlidingWindowHdrHistogram histogram : operationLatencyMap.values()) {
histogram.rotateIfNeeded();
}
}
/**
* Computes the tail latency percentiles for all operation types.
* This method is called periodically based on the configured computation interval.
*/
private void computePercentiles() {
for (SlidingWindowHdrHistogram histogram : operationLatencyMap.values()) {
histogram.computeLatency();
}
}
/**
* Creates a singleton object of the {@link SlidingWindowHdrHistogram}.
* which is shared across all filesystem instances.
* @param abfsConfiguration configuration set.
* @return singleton object of intercept.
*/
static AbfsTailLatencyTracker initializeSingleton(AbfsConfiguration abfsConfiguration) {
if (singletonLatencyTracker == null) {
LOCK.lock();
try {
if (singletonLatencyTracker == null) {
singletonLatencyTracker = new AbfsTailLatencyTracker(abfsConfiguration);
}
} finally {
LOCK.unlock();
}
}
return singletonLatencyTracker;
}
/**
* Updates the latency for a specific operation type.
* @param latency Latency value to be recorded.
* @param operationType Only applicable for read and write operations.
*/
public void updateLatency(final AbfsRestOperationType operationType,
final long latency) {
SlidingWindowHdrHistogram histogram = operationLatencyMap.get(operationType);
if (histogram == null) {
LOCK.lock();
try {
if (operationLatencyMap.get(operationType) == null) {
LOG.debug("Creating new histogram for operation: {}", operationType);
histogram = new SlidingWindowHdrHistogram(
talLatencyAnalysisWindowInMillis,
tailLatencyAnalysisWindowGranularity,
tailLatencyMinSampleSize,
tailLatencyPercentile,
tailLatencyMinDeviation,
HISTOGRAM_MAX_VALUE, HISTOGRAM_SIGNIFICANT_FIGURES,
operationType);
operationLatencyMap.put(operationType, histogram);
}
} finally {
LOCK.unlock();
}
} else {
LOG.debug("Using existing histogram for operation: {}", operationType);
}
if (histogram == null) {
LOG.error("Unable to find/create histogram for: {}", operationType);
return;
}
histogram.recordValue(latency);
LOG.debug("Updated latency for operation: {} with latency: {}",
operationType, latency);
}
/**
* Gets the tail latency for a specific operation type.
* @param operationType for which tail latency is required.
* @return Tail latency value.
*/
public double getTailLatency(final AbfsRestOperationType operationType) {
SlidingWindowHdrHistogram histogram = operationLatencyMap.get(operationType);
if (histogram != null) {
return histogram.getTailLatency();
}
LOG.debug("No histogram yet created for operation: {}", operationType);
return 0;
}
}
| AbfsTailLatencyTracker |
java | junit-team__junit5 | junit-platform-suite-api/src/main/java/org/junit/platform/suite/api/ExcludeClassNamePatterns.java | {
"start": 1018,
"end": 1318
} | class ____ be
* excluded from the test plan.
*
* @since 1.0
* @see Suite
* @see org.junit.platform.engine.discovery.ClassNameFilter#excludeClassNamePatterns
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Documented
@API(status = MAINTAINED, since = "1.0")
public @ | will |
java | spring-projects__spring-boot | module/spring-boot-liquibase/src/test/java/org/springframework/boot/liquibase/autoconfigure/endpoint/LiquibaseEndpointAutoConfigurationTests.java | {
"start": 3538,
"end": 4156
} | class ____ {
@Bean
SpringLiquibase liquibase() {
return new DataSourceClosingSpringLiquibase() {
private boolean propertiesSet;
@Override
public void setCloseDataSourceOnceMigrated(boolean closeDataSourceOnceMigrated) {
if (this.propertiesSet) {
throw new IllegalStateException(
"setCloseDataSourceOnceMigrated invoked after afterPropertiesSet");
}
super.setCloseDataSourceOnceMigrated(closeDataSourceOnceMigrated);
}
@Override
public void afterPropertiesSet() {
this.propertiesSet = true;
}
};
}
}
}
| DataSourceClosingLiquibaseConfiguration |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/erroneous/misbalancedbraces/Source.java | {
"start": 215,
"end": 274
} | class ____ {
//CHECKSTYLE:OFF
public int foo;
}
| Source |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/main/java/org/hibernate/processor/util/NullnessUtil.java | {
"start": 1092,
"end": 13517
} | class ____ {
private NullnessUtil() {
throw new AssertionError( "shouldn't be instantiated" );
}
/**
* A method that suppresses warnings from the Nullness Checker.
*
* <p>The method takes a possibly-null reference, unsafely casts it to have the @NonNull type
* qualifier, and returns it. The Nullness Checker considers both the return value, and also the
* argument, to be non-null after the method call. Therefore, the {@code castNonNull} method can
* be used either as a cast expression or as a statement. The Nullness Checker issues no warnings
* in any of the following code:
*
* <pre><code>
* // one way to use as a cast:
* {@literal @}NonNull String s = castNonNull(possiblyNull1);
*
* // another way to use as a cast:
* castNonNull(possiblyNull2).toString();
*
* // one way to use as a statement:
* castNonNull(possiblyNull3);
* possiblyNull3.toString();`
* </code></pre>
* <p>
* The {@code castNonNull} method is intended to be used in situations where the programmer
* definitively knows that a given reference is not null, but the type system is unable to make
* this deduction. It is not intended for defensive programming, in which a programmer cannot
* prove that the value is not null but wishes to have an earlier indication if it is. See the
* Checker Framework Manual for further discussion.
*
* <p>The method throws {@link AssertionError} if Java assertions are enabled and the argument is
* {@code null}. If the exception is ever thrown, then that indicates that the programmer misused
* the method by using it in a circumstance where its argument can be null.
*
* @param <T> the type of the reference
* @param ref a reference of @Nullable type, that is non-null at run time
*
* @return the argument, cast to have the type qualifier @NonNull
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T castNonNull(@Nullable T ref) {
assert ref != null : "Misuse of castNonNull: called with a null argument";
return ref;
}
/**
* Suppress warnings from the Nullness Checker, with a custom error message. See {@link
* #castNonNull(Object)} for documentation.
*
* @param <T> the type of the reference
* @param ref a reference of @Nullable type, that is non-null at run time
* @param message text to include if this method is misused
*
* @return the argument, cast to have the type qualifier @NonNull
*
* @see #castNonNull(Object)
*/
public static @EnsuresNonNull("#1") <T extends @Nullable Object> @NonNull T castNonNull(
@Nullable T ref, String message) {
assert ref != null : "Misuse of castNonNull: called with a null argument: " + message;
return ref;
}
/**
* Like castNonNull, but whereas that method only checks and casts the reference itself, this
* traverses all levels of the argument array. The array is recursively checked to ensure that all
* elements at every array level are non-null.
*
* @param <T> the component type of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*
* @see #castNonNull(Object)
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T @NonNull [] castNonNullDeep(
T @Nullable [] arr) {
return castNonNullArray( arr, null );
}
/**
* Like castNonNull, but whereas that method only checks and casts the reference itself, this
* traverses all levels of the argument array. The array is recursively checked to ensure that all
* elements at every array level are non-null.
*
* @param <T> the component type of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
* @param message text to include if this method is misused
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*
* @see #castNonNull(Object)
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T @NonNull [] castNonNullDeep(
T @Nullable [] arr, String message) {
return castNonNullArray( arr, message );
}
/**
* Like castNonNull, but whereas that method only checks and casts the reference itself, this
* traverses all levels of the argument array. The array is recursively checked to ensure that all
* elements at every array level are non-null.
*
* @param <T> the component type of the component type of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*
* @see #castNonNull(Object)
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T @NonNull [][] castNonNullDeep(
T @Nullable [] @Nullable [] arr) {
return castNonNullArray( arr, null );
}
/**
* Like castNonNull, but whereas that method only checks and casts the reference itself, this
* traverses all levels of the argument array. The array is recursively checked to ensure that all
* elements at every array level are non-null.
*
* @param <T> the component type of the component type of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
* @param message text to include if this method is misused
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*
* @see #castNonNull(Object)
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T @NonNull [][] castNonNullDeep(
T @Nullable [] @Nullable [] arr, String message) {
return castNonNullArray( arr, message );
}
/**
* Like castNonNull, but whereas that method only checks and casts the reference itself, this
* traverses all levels of the argument array. The array is recursively checked to ensure that all
* elements at every array level are non-null.
*
* @param <T> the component type (three levels in) of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*
* @see #castNonNull(Object)
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T @NonNull [][][] castNonNullDeep(
T @Nullable [] @Nullable [] @Nullable [] arr) {
return castNonNullArray( arr, null );
}
/**
* Like castNonNull, but whereas that method only checks and casts the reference itself, this
* traverses all levels of the argument array. The array is recursively checked to ensure that all
* elements at every array level are non-null.
*
* @param <T> the component type (three levels in) of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
* @param message text to include if this method is misused
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*
* @see #castNonNull(Object)
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T @NonNull [][][] castNonNullDeep(
T @Nullable [] @Nullable [] @Nullable [] arr, String message) {
return castNonNullArray( arr, message );
}
/**
* Like castNonNull, but whereas that method only checks and casts the reference itself, this
* traverses all levels of the argument array. The array is recursively checked to ensure that all
* elements at every array level are non-null.
*
* @param <T> the component type of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*
* @see #castNonNull(Object)
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T @NonNull [][][][] castNonNullDeep(
T @Nullable [] @Nullable [] @Nullable [] @Nullable [] arr) {
return castNonNullArray( arr, null );
}
/**
* Like castNonNull, but whereas that method only checks and casts the reference itself, this
* traverses all levels of the argument array. The array is recursively checked to ensure that all
* elements at every array level are non-null.
*
* @param <T> the component type (four levels in) of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
* @param message text to include if this method is misused
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*
* @see #castNonNull(Object)
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T @NonNull [][][][] castNonNullDeep(
T @Nullable [] @Nullable [] @Nullable [] @Nullable [] arr, String message) {
return castNonNullArray( arr, message );
}
/**
* Like castNonNull, but whereas that method only checks and casts the reference itself, this
* traverses all levels of the argument array. The array is recursively checked to ensure that all
* elements at every array level are non-null.
*
* @param <T> the component type (four levels in) of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*
* @see #castNonNull(Object)
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T @NonNull [][][][][] castNonNullDeep(
T @Nullable [] @Nullable [] @Nullable [] @Nullable [] @Nullable [] arr) {
return castNonNullArray( arr, null );
}
/**
* Like castNonNull, but whereas that method only checks and casts the reference itself, this
* traverses all levels of the argument array. The array is recursively checked to ensure that all
* elements at every array level are non-null.
*
* @param <T> the component type (five levels in) of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
* @param message text to include if this method is misused
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*
* @see #castNonNull(Object)
*/
@EnsuresNonNull("#1")
public static <T extends @Nullable Object> @NonNull T @NonNull [][][][][] castNonNullDeep(
T @Nullable [] @Nullable [] @Nullable [] @Nullable [] @Nullable [] arr, String message) {
return castNonNullArray( arr, message );
}
/**
* The implementation of castNonNullDeep.
*
* @param <T> the component type (five levels in) of the array
* @param arr an array all of whose elements, and their elements recursively, are non-null at run
* time
* @param message text to include if there is a non-null value, or null to use uncustomized
* message
*
* @return the argument, cast to have the type qualifier @NonNull at all levels
*/
private static <T extends @Nullable Object> @NonNull T @NonNull [] castNonNullArray(
T @Nullable [] arr, @Nullable String message) {
assert arr != null
: "Misuse of castNonNullArray: called with a null array argument"
+ ( message == null ? "" : ": " + message );
for ( int i = 0; i < arr.length; ++i ) {
assert arr[i] != null
: "Misuse of castNonNull: called with a null array element"
+ ( message == null ? "" : ": " + message );
checkIfArray( arr[i], message );
}
return arr;
}
/**
* If the argument is an array, requires it to be non-null at all levels.
*
* @param ref a value; if an array, all of its elements, and their elements recursively, are
* non-null at run time
* @param message text to include if there is a non-null value, or null to use uncustomized
* message
*/
private static void checkIfArray(@NonNull Object ref, @Nullable String message) {
assert ref != null
: "Misuse of checkIfArray: called with a null argument"
+ ( ( message == null ) ? "" : ( ": " + message ) );
Class<?> comp = ref.getClass().getComponentType();
if ( comp != null ) {
// comp is non-null for arrays, otherwise null.
if ( comp.isPrimitive() ) {
// Nothing to do for arrays of primitive type: primitives are
// never null.
}
else {
castNonNullArray( (Object[]) ref, message );
}
}
}
}
| NullnessUtil |
java | apache__flink | flink-formats/flink-json/src/test/java/org/apache/flink/formats/utils/SerializationSchemaMatcher.java | {
"start": 5265,
"end": 6795
} | class ____ {
private SerializationSchema<Row> serializationSchema;
private DeserializationSchema<Row> deserializationSchema;
private SerializationWithDeserializationSchemaMatcherBuilder(
SerializationSchema<Row> serializationSchema,
DeserializationSchema<Row> deserializationSchema) {
try {
// we serialize and deserialize the schema to test runtime behavior
// when the schema is shipped to the cluster
this.serializationSchema =
deserializeObject(
serializeObject(serializationSchema),
this.getClass().getClassLoader());
open(this.serializationSchema);
this.deserializationSchema =
deserializeObject(
serializeObject(deserializationSchema),
this.getClass().getClassLoader());
open(this.deserializationSchema);
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public SerializationSchemaMatcher equalsTo(Row expected) {
return new SerializationSchemaResultMatcher(
serializationSchema, deserializationSchema, expected);
}
}
/** Builder for {@link SerializationSchemaMatcher}. */
public static | SerializationWithDeserializationSchemaMatcherBuilder |
java | grpc__grpc-java | api/src/main/java/io/grpc/LoadBalancerProvider.java | {
"start": 1700,
"end": 2861
} | class ____ extends LoadBalancer.Factory {
/**
* A sentinel value indicating that service config is not supported. This can be used to
* indicate that parsing of the service config is neither right nor wrong, but doesn't have
* any meaning.
*/
private static final ConfigOrError UNKNOWN_CONFIG = ConfigOrError.fromConfig(new UnknownConfig());
/**
* Whether this provider is available for use, taking the current environment into consideration.
* If {@code false}, {@link #newLoadBalancer} is not safe to be called.
*/
public abstract boolean isAvailable();
/**
* A priority, from 0 to 10 that this provider should be used, taking the current environment into
* consideration. 5 should be considered the default, and then tweaked based on environment
* detection. A priority of 0 does not imply that the provider wouldn't work; just that it should
* be last in line.
*/
public abstract int getPriority();
/**
* Returns the load-balancing policy name associated with this provider, which makes it selectable
* via {@link LoadBalancerRegistry#getProvider}. This is called only when the | LoadBalancerProvider |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/DeleteRowsCoordinatorStandard.java | {
"start": 771,
"end": 3537
} | class ____ implements DeleteRowsCoordinator {
private final CollectionMutationTarget mutationTarget;
private final RowMutationOperations rowMutationOperations;
private final boolean deleteByIndex;
private final BasicBatchKey batchKey;
private final MutationExecutorService mutationExecutorService;
private MutationOperationGroup operationGroup;
public DeleteRowsCoordinatorStandard(
CollectionMutationTarget mutationTarget,
RowMutationOperations rowMutationOperations,
boolean deleteByIndex,
ServiceRegistry serviceRegistry) {
this.mutationTarget = mutationTarget;
this.rowMutationOperations = rowMutationOperations;
this.deleteByIndex = deleteByIndex;
batchKey = new BasicBatchKey( mutationTarget.getRolePath() + "#DELETE" );
mutationExecutorService = serviceRegistry.getService( MutationExecutorService.class );
}
@Override
public CollectionMutationTarget getMutationTarget() {
return mutationTarget;
}
@Override
public void deleteRows(PersistentCollection<?> collection, Object key, SharedSessionContractImplementor session) {
if ( operationGroup == null ) {
operationGroup = createOperationGroup();
}
if ( MODEL_MUTATION_LOGGER.isTraceEnabled() ) {
MODEL_MUTATION_LOGGER.deletingRemovedCollectionRows( mutationTarget.getRolePath(), key );
}
final var mutationExecutor = mutationExecutorService.createExecutor(
() -> batchKey,
operationGroup,
session
);
final var jdbcValueBindings = mutationExecutor.getJdbcValueBindings();
try {
final var pluralAttribute = mutationTarget.getTargetPart();
final var collectionDescriptor = pluralAttribute.getCollectionDescriptor();
final var deletes = collection.getDeletes( collectionDescriptor, !deleteByIndex );
if ( !deletes.hasNext() ) {
MODEL_MUTATION_LOGGER.noRowsToDelete();
return;
}
int deletionCount = 0;
final var restrictions = rowMutationOperations.getDeleteRowRestrictions();
while ( deletes.hasNext() ) {
final Object removal = deletes.next();
restrictions.applyRestrictions(
collection,
key,
removal,
deletionCount,
session,
jdbcValueBindings
);
mutationExecutor.execute( removal, null, null, null, session );
deletionCount++;
}
MODEL_MUTATION_LOGGER.doneDeletingCollectionRows( deletionCount, mutationTarget.getRolePath() );
}
finally {
mutationExecutor.release();
}
}
private MutationOperationGroup createOperationGroup() {
assert mutationTarget.getTargetPart() != null
&& mutationTarget.getTargetPart().getKeyDescriptor() != null;
final var operation = rowMutationOperations.getDeleteRowOperation();
return singleOperation( MutationType.DELETE, mutationTarget, operation );
}
}
| DeleteRowsCoordinatorStandard |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/IntroductionAdvisor.java | {
"start": 760,
"end": 1087
} | interface ____ be implemented directly; subinterfaces must
* provide the advice type implementing the introduction.
*
* <p>Introduction is the implementation of additional interfaces
* (not implemented by a target) via AOP advice.
*
* @author Rod Johnson
* @since 04.04.2003
* @see IntroductionInterceptor
*/
public | cannot |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullableTest.java | {
"start": 33922,
"end": 34168
} | interface ____ {}
""")
.addSourceLines(
"com/google/errorprone/bugpatterns/nullness/TypeAnnoReturnTest.java",
"""
package com.google.errorprone.bugpatterns.nullness;
public | Nullable |
java | apache__camel | components/camel-openstack/src/main/java/org/apache/camel/component/openstack/keystone/producer/RegionProducer.java | {
"start": 1485,
"end": 4281
} | class ____ extends AbstractKeystoneProducer {
public RegionProducer(KeystoneEndpoint endpoint, OSClient client) {
super(endpoint, client);
}
@Override
public void process(Exchange exchange) throws Exception {
final String operation = getOperation(exchange);
switch (operation) {
case OpenstackConstants.CREATE:
doCreate(exchange);
break;
case OpenstackConstants.GET:
doGet(exchange);
break;
case OpenstackConstants.GET_ALL:
doGetAll(exchange);
break;
case OpenstackConstants.UPDATE:
doUpdate(exchange);
break;
case OpenstackConstants.DELETE:
doDelete(exchange);
break;
default:
throw new IllegalArgumentException("Unsupported operation " + operation);
}
}
private void doCreate(Exchange exchange) {
final Region in = messageToRegion(exchange.getIn());
final Region out = osV3Client.identity().regions().create(in);
exchange.getIn().setBody(out);
}
private void doGet(Exchange exchange) {
final String id = exchange.getIn().getHeader(OpenstackConstants.ID, String.class);
StringHelper.notEmpty(id, "Region ID");
final Region out = osV3Client.identity().regions().get(id);
exchange.getIn().setBody(out);
}
private void doGetAll(Exchange exchange) {
final List<? extends Region> out = osV3Client.identity().regions().list();
exchange.getIn().setBody(out);
}
private void doUpdate(Exchange exchange) {
final Message msg = exchange.getIn();
final Region in = messageToRegion(msg);
final Region out = osV3Client.identity().regions().update(in);
msg.setBody(out);
}
private void doDelete(Exchange exchange) {
final Message msg = exchange.getIn();
final String id = msg.getHeader(OpenstackConstants.ID, String.class);
StringHelper.notEmpty(id, "Region ID");
final ActionResponse response = osV3Client.identity().regions().delete(id);
checkFailure(response, exchange, "Delete network" + id);
}
private Region messageToRegion(Message message) {
Region region = message.getBody(Region.class);
if (region == null) {
Map headers = message.getHeaders();
RegionBuilder builder = Builders.region();
if (headers.containsKey(KeystoneConstants.DESCRIPTION)) {
builder.description(message.getHeader(KeystoneConstants.DESCRIPTION, String.class));
}
region = builder.build();
}
return region;
}
}
| RegionProducer |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/tracing/TraceContext.java | {
"start": 212,
"end": 294
} | interface ____ {
TraceContext EMPTY = new TraceContext() {
};
}
| TraceContext |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/error/ShouldNotContainSubsequence.java | {
"start": 1056,
"end": 2786
} | class ____ extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldNotContainSubsequence}</code>.
*
* @param actual the actual value in the failed assertion.
* @param subsequence the subsequence of values expected to be in {@code actual}.
* @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion.
* @param index the index of the unexpected subsequence.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldNotContainSubsequence(Object actual, Object subsequence,
ComparisonStrategy comparisonStrategy, int index) {
return new ShouldNotContainSubsequence(actual, subsequence, comparisonStrategy, index);
}
/**
* Creates a new <code>{@link ShouldNotContainSubsequence}</code>.
*
* @param actual the actual value in the failed assertion.
* @param subsequence the subsequence of values expected to be in {@code actual}.
* @param index the index of the unexpected subsequence.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldNotContainSubsequence(Object actual, Object subsequence, int index) {
return new ShouldNotContainSubsequence(actual, subsequence, StandardComparisonStrategy.instance(), index);
}
private ShouldNotContainSubsequence(Object actual, Object subsequence, ComparisonStrategy comparisonStrategy,
int index) {
super("%nExpecting actual:%n %s%nto not contain subsequence:%n %s%nbut was found starting at index %s%n%s",
actual, subsequence, index, comparisonStrategy);
}
}
| ShouldNotContainSubsequence |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchyBuilder.java | {
"start": 11277,
"end": 11686
} | class ____ {
private final MappingDocument sourceMappingDocument;
private final JaxbHbmSubclassEntityBaseDefinition jaxbSubEntityMapping;
public ExtendsQueueEntry(
MappingDocument sourceMappingDocument,
JaxbHbmSubclassEntityBaseDefinition jaxbSubEntityMapping) {
this.sourceMappingDocument = sourceMappingDocument;
this.jaxbSubEntityMapping = jaxbSubEntityMapping;
}
}
}
| ExtendsQueueEntry |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/CorsConfigurerTests.java | {
"start": 2804,
"end": 8768
} | class ____ {
public final SpringTestContext spring = new SpringTestContext(this);
@Autowired
MockMvc mvc;
@Test
public void configureWhenNoMvcThenException() {
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(DefaultCorsConfig.class).autowire())
.withMessageContaining(
"Please ensure that you are using `@EnableWebMvc`, are publishing a `WebMvcConfigurer`, "
+ "or are publishing a `CorsConfigurationSource` bean.");
}
@Test
public void getWhenCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void optionsWhenCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsConfig.class).autowire();
this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void getWhenDefaultsInLambdaAndCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsInLambdaConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void optionsWhenDefaultsInLambdaAndCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsInLambdaConfig.class).autowire();
this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void getWhenCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(ConfigSourceConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void optionsWhenCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(ConfigSourceConfig.class).autowire();
this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void getWhenMvcCorsInLambdaConfigAndCorsConfigurationSourceBeanThenRespondsWithCorsHeaders()
throws Exception {
this.spring.register(ConfigSourceInLambdaConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void optionsWhenMvcCorsInLambdaConfigAndCorsConfigurationSourceBeanThenRespondsWithCorsHeaders()
throws Exception {
this.spring.register(ConfigSourceInLambdaConfig.class).autowire();
this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void getWhenCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void optionsWhenCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterConfig.class).autowire();
this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void getWhenConfigSourceInLambdaConfigAndCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterInLambdaConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Test
public void optionsWhenConfigSourceInLambdaConfigAndCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterInLambdaConfig.class).autowire();
this.mvc
.perform(options("/")
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
.header(HttpHeaders.ORIGIN, "https://example.com"))
.andExpect(status().isOk())
.andExpect(header().exists("Access-Control-Allow-Origin"))
.andExpect(header().exists("X-Content-Type-Options"));
}
@Configuration
@EnableWebSecurity
static | CorsConfigurerTests |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/http/impl/http1x/VertxHttpResponseEncoder.java | {
"start": 1235,
"end": 1971
} | class ____ extends HttpResponseEncoder {
private final boolean cacheImmutableResponseHeaders = SysProps.CACHE_IMMUTABLE_HTTP_RESPONSE_HEADERS.getBoolean();
@Override
protected void encodeHeaders(HttpHeaders headers, ByteBuf buf) {
if (headers instanceof Http1xHeaders) {
Http1xHeaders vertxHeaders = (Http1xHeaders) headers;
vertxHeaders.encode(buf, cacheImmutableResponseHeaders);
} else {
super.encodeHeaders(headers, buf);
}
}
@Override
public boolean acceptOutboundMessage(Object msg) throws Exception {
// fast-path singleton(s)
if (msg == Unpooled.EMPTY_BUFFER || msg == LastHttpContent.EMPTY_LAST_CONTENT) {
return true;
}
// fast-path exact | VertxHttpResponseEncoder |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/shortarrays/ShortArrays_assertContains_at_Index_Test.java | {
"start": 1769,
"end": 7579
} | class ____ extends ShortArraysBaseTest {
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContains(someInfo(), null, (short) 8,
someIndex()))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_is_empty() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContains(someInfo(), emptyArray(), (short) 8,
someIndex()))
.withMessage(actualIsEmpty());
}
@Test
void should_throw_error_if_Index_is_null() {
assertThatNullPointerException().isThrownBy(() -> arrays.assertContains(someInfo(), actual, (short) 8, null))
.withMessage("Index should not be null");
}
@Test
void should_throw_error_if_Index_is_out_of_bounds() {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> arrays.assertContains(someInfo(),
actual, (short) 8,
atIndex(6)))
.withMessageContaining("Index should be between <0> and <2> (inclusive) but was:%n <6>".formatted());
}
@Test
void should_fail_if_actual_does_not_contain_value_at_index() {
AssertionInfo info = someInfo();
short value = 6;
Index index = atIndex(1);
Throwable error = catchThrowable(() -> arrays.assertContains(info, actual, value, index));
assertThat(error).isInstanceOf(AssertionError.class);
short found = 8;
verify(failures).failure(info, shouldContainAtIndex(actual, value, index, found));
}
@Test
void should_pass_if_actual_contains_value_at_index() {
arrays.assertContains(someInfo(), actual, (short) 8, atIndex(1));
}
@Test
void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(),
null,
(short) 8,
someIndex()))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_is_empty_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(),
emptyArray(),
(short) 8,
someIndex()))
.withMessage(actualIsEmpty());
}
@Test
void should_throw_error_if_Index_is_null_whatever_custom_comparison_strategy_is() {
assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(),
actual,
(short) 8,
null))
.withMessage("Index should not be null");
}
@Test
void should_throw_error_if_Index_is_out_of_bounds_whatever_custom_comparison_strategy_is() {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(),
actual,
(short) 8,
atIndex(6)))
.withMessageContaining("Index should be between <0> and <2> (inclusive) but was:%n <6>".formatted());
}
@Test
void should_fail_if_actual_does_not_contain_value_at_index_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
short value = 6;
Index index = atIndex(1);
Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertContains(info, actual, value, index));
assertThat(error).isInstanceOf(AssertionError.class);
short found = 8;
verify(failures).failure(info, shouldContainAtIndex(actual, value, index, found, absValueComparisonStrategy));
}
@Test
void should_pass_if_actual_contains_value_at_index_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertContains(someInfo(), actual, (short) -8, atIndex(1));
}
}
| ShortArrays_assertContains_at_Index_Test |
java | square__javapoet | src/main/java/com/squareup/javapoet/TypeSpec.java | {
"start": 24499,
"end": 26200
} | class ____ {
*
* }
* }
* </code></pre>
*
* <p>
* Then this would add {@code "NestedTypeA"} and {@code "NestedTypeB"} as names that should
* always be qualified via {@link #alwaysQualify(String...)}. This way they would avoid
* possible import conflicts when this JavaFile is written.
*
* @param typeElement the {@link TypeElement} with nested types to avoid clashes with.
* @return this builder instance.
*/
public Builder avoidClashesWithNestedClasses(TypeElement typeElement) {
checkArgument(typeElement != null, "typeElement == null");
for (TypeElement nestedType : ElementFilter.typesIn(typeElement.getEnclosedElements())) {
alwaysQualify(nestedType.getSimpleName().toString());
}
TypeMirror superclass = typeElement.getSuperclass();
if (!(superclass instanceof NoType) && superclass instanceof DeclaredType) {
TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement();
avoidClashesWithNestedClasses(superclassElement);
}
for (TypeMirror superinterface : typeElement.getInterfaces()) {
if (superinterface instanceof DeclaredType) {
TypeElement superinterfaceElement
= (TypeElement) ((DeclaredType) superinterface).asElement();
avoidClashesWithNestedClasses(superinterfaceElement);
}
}
return this;
}
/**
* Call this to always fully qualify any types that would conflict with possibly nested types of
* this {@code typeElement}. For example - if the following type was passed in as the
* typeElement:
*
* <pre><code>
* | NestedTypeB |
java | google__guava | android/guava/src/com/google/common/cache/ForwardingCache.java | {
"start": 1364,
"end": 3370
} | class ____<K, V> extends ForwardingObject implements Cache<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingCache() {}
@Override
protected abstract Cache<K, V> delegate();
/**
* @since 11.0
*/
@Override
public @Nullable V getIfPresent(Object key) {
return delegate().getIfPresent(key);
}
/**
* @since 11.0
*/
@Override
public V get(K key, Callable<? extends V> valueLoader) throws ExecutionException {
return delegate().get(key, valueLoader);
}
/**
* @since 11.0
*/
@Override
/*
* <? extends Object> is mostly the same as <?> to plain Java. But to nullness checkers, they
* differ: <? extends Object> means "non-null types," while <?> means "all types."
*/
public ImmutableMap<K, V> getAllPresent(Iterable<? extends Object> keys) {
return delegate().getAllPresent(keys);
}
/**
* @since 11.0
*/
@Override
public void put(K key, V value) {
delegate().put(key, value);
}
/**
* @since 12.0
*/
@Override
public void putAll(Map<? extends K, ? extends V> m) {
delegate().putAll(m);
}
@Override
public void invalidate(Object key) {
delegate().invalidate(key);
}
/**
* @since 11.0
*/
@Override
// For discussion of <? extends Object>, see getAllPresent.
public void invalidateAll(Iterable<? extends Object> keys) {
delegate().invalidateAll(keys);
}
@Override
public void invalidateAll() {
delegate().invalidateAll();
}
@Override
public long size() {
return delegate().size();
}
@Override
public CacheStats stats() {
return delegate().stats();
}
@Override
public ConcurrentMap<K, V> asMap() {
return delegate().asMap();
}
@Override
public void cleanUp() {
delegate().cleanUp();
}
/**
* A simplified version of {@link ForwardingCache} where subclasses can pass in an already
* constructed {@link Cache} as the delegate.
*
* @since 10.0
*/
public abstract static | ForwardingCache |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/RedissonNodeInitializer.java | {
"start": 761,
"end": 972
} | interface ____ {
/**
* Invoked during Redisson Node startup
*
* @param redissonNode - Redisson Node instance
*/
void onStartup(RedissonNode redissonNode);
}
| RedissonNodeInitializer |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/scheduler/OpportunisticContainerAllocator.java | {
"start": 5209,
"end": 6043
} | class ____ {
protected volatile AtomicLong containerIdCounter = new AtomicLong(1);
/**
* This method can reset the generator to a specific value.
* @param containerIdStart containerId
*/
public void resetContainerIdCounter(long containerIdStart) {
this.containerIdCounter.set(containerIdStart);
}
/**
* Generates a new long value. Default implementation increments the
* underlying AtomicLong. Sub classes are encouraged to over-ride this
* behaviour.
* @return Counter.
*/
public long generateContainerId() {
return this.containerIdCounter.incrementAndGet();
}
}
/**
* Class that includes two lists of {@link ResourceRequest}s: one for
* GUARANTEED and one for OPPORTUNISTIC {@link ResourceRequest}s.
*/
public static | ContainerIdGenerator |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/event/EagerTestExecutionEventPublishingTests.java | {
"start": 4666,
"end": 4723
} | class ____ extends LazyTestCase1 {
}
static | EagerTestCase1 |
java | spring-projects__spring-framework | spring-expression/src/jmh/java/org/springframework/expression/spel/SpelBenchmark.java | {
"start": 1451,
"end": 2065
} | class ____ {
public ExpressionParser parser = new SpelExpressionParser();
public EvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext();
}
@Benchmark
public Object propertyAccessParseAndExecution(BenchmarkData data) {
Expression expr = data.parser.parseExpression("placeOfBirth.city");
return expr.getValue(data.eContext);
}
@Benchmark
public Object methodAccessParseAndExecution(BenchmarkData data) {
Expression expr = data.parser.parseExpression("getPlaceOfBirth().getCity()");
return expr.getValue(data.eContext);
}
@State(Scope.Benchmark)
public static | BenchmarkData |
java | apache__camel | components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyTextlineInOutSynchronousFalseTest.java | {
"start": 1179,
"end": 3071
} | class ____ extends BaseNettyTest {
private static String beforeThreadName;
private static String afterThreadName;
@Test
public void testSynchronous() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
String reply = template.requestBody("direct:start", "Hello World", String.class);
assertEquals("Bye World", reply);
MockEndpoint.assertIsSatisfied(context);
assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should not same threads");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.to("log:before")
.process(new Processor() {
public void process(Exchange exchange) {
beforeThreadName = Thread.currentThread().getName();
}
})
.to("netty:tcp://localhost:{{port}}?textline=true&sync=true&synchronous=false")
.process(new Processor() {
public void process(Exchange exchange) {
afterThreadName = Thread.currentThread().getName();
}
})
.to("log:after")
.to("mock:result");
from("netty:tcp://localhost:{{port}}?textline=true&sync=true&synchronous=false")
// body should be a String when using textline codec
.validate(body().isInstanceOf(String.class))
.transform(body().regexReplaceAll("Hello", "Bye"));
}
};
}
}
| NettyTextlineInOutSynchronousFalseTest |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customproviders/AsyncResponseWithExceptionAndFiltersTargetTest.java | {
"start": 5076,
"end": 5401
} | class ____ implements ExceptionMapper<DummyException> {
@Override
public Response toResponse(DummyException exception) {
if (exception.isHandle()) {
return Response.status(999).build();
}
throw exception;
}
}
public static | DummyExceptionMapper |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/input/InputBuilders.java | {
"start": 899,
"end": 1934
} | class ____ {
private InputBuilders() {}
public static NoneInput.Builder noneInput() {
return NoneInput.builder();
}
public static SearchInput.Builder searchInput(WatcherSearchTemplateRequest request) {
return SearchInput.builder(request);
}
public static SimpleInput.Builder simpleInput() {
return simpleInput(new HashMap<>());
}
public static SimpleInput.Builder simpleInput(String key, Object value) {
return simpleInput(Map.of(key, value));
}
public static SimpleInput.Builder simpleInput(Map<String, Object> data) {
return SimpleInput.builder(new Payload.Simple(data));
}
public static HttpInput.Builder httpInput(HttpRequestTemplate.Builder request) {
return httpInput(request.build());
}
public static HttpInput.Builder httpInput(HttpRequestTemplate request) {
return HttpInput.builder(request);
}
public static ChainInput.Builder chainInput() {
return ChainInput.builder();
}
}
| InputBuilders |
java | apache__camel | core/camel-core-reifier/src/main/java/org/apache/camel/reifier/validator/ValidatorReifier.java | {
"start": 1390,
"end": 4039
} | class ____<T> extends AbstractReifier {
// for custom reifiers
private static final Map<Class<?>, BiFunction<CamelContext, ValidatorDefinition, ValidatorReifier<? extends ValidatorDefinition>>> VALIDATORS
= new HashMap<>(0);
protected final T definition;
public ValidatorReifier(CamelContext camelContext, T definition) {
super(camelContext);
this.definition = definition;
}
public static void registerReifier(
Class<?> processorClass,
BiFunction<CamelContext, ValidatorDefinition, ValidatorReifier<? extends ValidatorDefinition>> creator) {
if (VALIDATORS.isEmpty()) {
ReifierStrategy.addReifierClearer(ValidatorReifier::clearReifiers);
}
VALIDATORS.put(processorClass, creator);
}
public static ValidatorReifier<? extends ValidatorDefinition> reifier(
CamelContext camelContext, ValidatorDefinition definition) {
ValidatorReifier<? extends ValidatorDefinition> answer = null;
if (!VALIDATORS.isEmpty()) {
// custom take precedence
BiFunction<CamelContext, ValidatorDefinition, ValidatorReifier<? extends ValidatorDefinition>> reifier
= VALIDATORS.get(definition.getClass());
if (reifier != null) {
answer = reifier.apply(camelContext, definition);
}
}
if (answer == null) {
answer = coreReifier(camelContext, definition);
}
if (answer == null) {
throw new IllegalStateException("Unsupported definition: " + definition);
}
return answer;
}
private static ValidatorReifier<? extends ValidatorDefinition> coreReifier(
CamelContext camelContext, ValidatorDefinition definition) {
if (definition instanceof CustomValidatorDefinition) {
return new CustomValidatorReifier(camelContext, definition);
} else if (definition instanceof EndpointValidatorDefinition) {
return new EndpointValidatorReifier(camelContext, definition);
} else if (definition instanceof PredicateValidatorDefinition) {
return new PredicateValidatorReifier(camelContext, definition);
}
return null;
}
public static void clearReifiers() {
VALIDATORS.clear();
}
// Returns a Validator object. This is a Service implementing AutoCloseable interface. Make sure to close
// the object accordingly.
public Validator createValidator() {
return doCreateValidator();
}
protected abstract Validator doCreateValidator();
}
| ValidatorReifier |
java | apache__camel | components/camel-google/camel-google-calendar/src/generated/java/org/apache/camel/component/google/calendar/CalendarCalendarsEndpointConfigurationConfigurer.java | {
"start": 758,
"end": 7756
} | class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("AccessToken", java.lang.String.class);
map.put("ApiName", org.apache.camel.component.google.calendar.internal.GoogleCalendarApiName.class);
map.put("ApplicationName", java.lang.String.class);
map.put("CalendarId", java.lang.String.class);
map.put("ClientId", java.lang.String.class);
map.put("ClientSecret", java.lang.String.class);
map.put("Content", com.google.api.services.calendar.model.Calendar.class);
map.put("Delegate", java.lang.String.class);
map.put("EmailAddress", java.lang.String.class);
map.put("MethodName", java.lang.String.class);
map.put("P12FileName", java.lang.String.class);
map.put("RefreshToken", java.lang.String.class);
map.put("Scopes", java.lang.String.class);
map.put("ServiceAccountKey", java.lang.String.class);
map.put("User", java.lang.String.class);
ALL_OPTIONS = map;
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
org.apache.camel.component.google.calendar.CalendarCalendarsEndpointConfiguration target = (org.apache.camel.component.google.calendar.CalendarCalendarsEndpointConfiguration) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": target.setAccessToken(property(camelContext, java.lang.String.class, value)); return true;
case "apiname":
case "apiName": target.setApiName(property(camelContext, org.apache.camel.component.google.calendar.internal.GoogleCalendarApiName.class, value)); return true;
case "applicationname":
case "applicationName": target.setApplicationName(property(camelContext, java.lang.String.class, value)); return true;
case "calendarid":
case "calendarId": target.setCalendarId(property(camelContext, java.lang.String.class, value)); return true;
case "clientid":
case "clientId": target.setClientId(property(camelContext, java.lang.String.class, value)); return true;
case "clientsecret":
case "clientSecret": target.setClientSecret(property(camelContext, java.lang.String.class, value)); return true;
case "content": target.setContent(property(camelContext, com.google.api.services.calendar.model.Calendar.class, value)); return true;
case "delegate": target.setDelegate(property(camelContext, java.lang.String.class, value)); return true;
case "emailaddress":
case "emailAddress": target.setEmailAddress(property(camelContext, java.lang.String.class, value)); return true;
case "methodname":
case "methodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true;
case "p12filename":
case "p12FileName": target.setP12FileName(property(camelContext, java.lang.String.class, value)); return true;
case "refreshtoken":
case "refreshToken": target.setRefreshToken(property(camelContext, java.lang.String.class, value)); return true;
case "scopes": target.setScopes(property(camelContext, java.lang.String.class, value)); return true;
case "serviceaccountkey":
case "serviceAccountKey": target.setServiceAccountKey(property(camelContext, java.lang.String.class, value)); return true;
case "user": target.setUser(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": return java.lang.String.class;
case "apiname":
case "apiName": return org.apache.camel.component.google.calendar.internal.GoogleCalendarApiName.class;
case "applicationname":
case "applicationName": return java.lang.String.class;
case "calendarid":
case "calendarId": return java.lang.String.class;
case "clientid":
case "clientId": return java.lang.String.class;
case "clientsecret":
case "clientSecret": return java.lang.String.class;
case "content": return com.google.api.services.calendar.model.Calendar.class;
case "delegate": return java.lang.String.class;
case "emailaddress":
case "emailAddress": return java.lang.String.class;
case "methodname":
case "methodName": return java.lang.String.class;
case "p12filename":
case "p12FileName": return java.lang.String.class;
case "refreshtoken":
case "refreshToken": return java.lang.String.class;
case "scopes": return java.lang.String.class;
case "serviceaccountkey":
case "serviceAccountKey": return java.lang.String.class;
case "user": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
org.apache.camel.component.google.calendar.CalendarCalendarsEndpointConfiguration target = (org.apache.camel.component.google.calendar.CalendarCalendarsEndpointConfiguration) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": return target.getAccessToken();
case "apiname":
case "apiName": return target.getApiName();
case "applicationname":
case "applicationName": return target.getApplicationName();
case "calendarid":
case "calendarId": return target.getCalendarId();
case "clientid":
case "clientId": return target.getClientId();
case "clientsecret":
case "clientSecret": return target.getClientSecret();
case "content": return target.getContent();
case "delegate": return target.getDelegate();
case "emailaddress":
case "emailAddress": return target.getEmailAddress();
case "methodname":
case "methodName": return target.getMethodName();
case "p12filename":
case "p12FileName": return target.getP12FileName();
case "refreshtoken":
case "refreshToken": return target.getRefreshToken();
case "scopes": return target.getScopes();
case "serviceaccountkey":
case "serviceAccountKey": return target.getServiceAccountKey();
case "user": return target.getUser();
default: return null;
}
}
}
| CalendarCalendarsEndpointConfigurationConfigurer |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/AnnotationIsolationTest.java | {
"start": 3573,
"end": 4276
} | class ____ {
@Bean
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("zookeeper://127.0.0.1:2181");
return registryConfig;
}
@Bean
public ApplicationConfig applicationConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig("consumer-app");
return applicationConfig;
}
}
// note scanBasePackages, expose three service with dubbo and tri protocol
@Configuration
@EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.isolation.spring.annotation.provider")
static | ConsumerConfiguration |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DataStreamer.java | {
"start": 6817,
"end": 8702
} | class ____ implements java.io.Closeable {
private Socket sock = null;
private DataOutputStream out = null;
private DataInputStream in = null;
StreamerStreams(final DatanodeInfo src,
final long writeTimeout, final long readTimeout,
final Token<BlockTokenIdentifier> blockToken)
throws IOException {
sock = createSocketForPipeline(src, 2, dfsClient);
OutputStream unbufOut = NetUtils.getOutputStream(sock, writeTimeout);
InputStream unbufIn = NetUtils.getInputStream(sock, readTimeout);
IOStreamPair saslStreams = dfsClient.saslClient
.socketSend(sock, unbufOut, unbufIn, dfsClient, blockToken, src);
unbufOut = saslStreams.out;
unbufIn = saslStreams.in;
out = new DataOutputStream(new BufferedOutputStream(unbufOut,
DFSUtilClient.getSmallBufferSize(dfsClient.getConfiguration())));
in = new DataInputStream(unbufIn);
}
void sendTransferBlock(final DatanodeInfo[] targets,
final StorageType[] targetStorageTypes,
final String[] targetStorageIDs,
final Token<BlockTokenIdentifier> blockToken) throws IOException {
//send the TRANSFER_BLOCK request
new Sender(out).transferBlock(block.getCurrentBlock(), blockToken,
dfsClient.clientName, targets, targetStorageTypes,
targetStorageIDs);
out.flush();
//ack
BlockOpResponseProto transferResponse = BlockOpResponseProto
.parseFrom(PBHelperClient.vintPrefixed(in));
if (SUCCESS != transferResponse.getStatus()) {
throw new IOException("Failed to add a datanode. Response status: "
+ transferResponse.getStatus());
}
}
@Override
public void close() throws IOException {
IOUtils.closeStream(in);
IOUtils.closeStream(out);
IOUtils.closeSocket(sock);
}
}
static | StreamerStreams |
java | playframework__playframework | core/play/src/test/java/play/mvc/RangeResultsTest.java | {
"start": 1041,
"end": 15660
} | class ____ {
private static Path path;
@BeforeClass
public static void createFile() throws IOException {
path = Paths.get("test.tmp");
Files.createFile(path);
Files.write(path, "Some content for the file".getBytes(), StandardOpenOption.APPEND);
}
@AfterClass
public static void deleteFile() throws IOException {
Files.deleteIfExists(path);
}
// -- InputStreams
@Test
public void shouldNotReturnRangeResultForInputStreamWhenHeaderIsNotPresent() throws IOException {
Http.Request req = mockRegularRequest();
try (InputStream stream = Files.newInputStream(path)) {
Result result = RangeResults.ofStream(req, stream);
assertEquals(OK, result.status());
assertEquals(BINARY, result.body().contentType().orElse(""));
}
}
@Test
public void shouldReturnRangeResultForInputStreamWhenHeaderIsPresentAndContentTypeWasSpecified()
throws IOException {
Http.Request req = mockRangeRequest();
try (InputStream stream = Files.newInputStream(path)) {
Result result = RangeResults.ofStream(req, stream, Files.size(path), "file.txt", HTML);
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(HTML, result.body().contentType().orElse(""));
}
}
@Test
public void shouldReturnRangeResultForInputStreamWithCustomFilename() throws IOException {
Http.Request req = mockRangeRequest();
try (InputStream stream = Files.newInputStream(path)) {
Result result = RangeResults.ofStream(req, stream, Files.size(path), "file.txt");
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(
"attachment; filename=\"file.txt\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
}
@Test
public void shouldNotReturnRangeResultForInputStreamWhenHeaderIsNotPresentWithCustomFilename()
throws IOException {
Http.Request req = mockRegularRequest();
try (InputStream stream = Files.newInputStream(path)) {
Result result = RangeResults.ofStream(req, stream, Files.size(path), "file.txt");
assertEquals(OK, result.status());
assertEquals(BINARY, result.body().contentType().orElse(""));
assertEquals(
"attachment; filename=\"file.txt\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
}
@Test
public void shouldReturnPartialContentForInputStreamWithGivenEntityLength() throws IOException {
Http.Request req = mockRangeRequest();
try (InputStream stream = Files.newInputStream(path)) {
Result result = RangeResults.ofStream(req, stream, Files.size(path));
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals("bytes 0-1/" + Files.size(path), result.header(CONTENT_RANGE).get());
}
}
@Test
public void shouldReturnPartialContentForInputStreamWithGivenNameAndContentType()
throws IOException {
Http.Request req = mockRangeRequest();
try (InputStream stream = Files.newInputStream(path)) {
Result result = RangeResults.ofStream(req, stream, Files.size(path), "file.txt", TEXT);
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(TEXT, result.body().contentType().orElse(""));
assertEquals(
"attachment; filename=\"file.txt\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
}
// -- Paths
@Test
public void shouldReturnRangeResultForPath() {
Http.Request req = mockRangeRequest();
Result result = RangeResults.ofPath(req, path);
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(
"attachment; filename=\"test.tmp\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldNotReturnRangeResultForPathWhenHeaderIsNotPresent() {
Http.Request req = mockRegularRequest();
Result result = RangeResults.ofPath(req, path);
assertEquals(OK, result.status());
assertEquals(
"attachment; filename=\"test.tmp\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldReturnRangeResultForPathWithCustomFilename() {
Http.Request req = mockRangeRequest();
Result result = RangeResults.ofPath(req, path, "file.txt");
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(
"attachment; filename=\"file.txt\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldNotReturnRangeResultForPathWhenHeaderIsNotPresentWithCustomFilename() {
Http.Request req = mockRegularRequest();
Result result = RangeResults.ofPath(req, path, "file.txt");
assertEquals(OK, result.status());
assertEquals(
"attachment; filename=\"file.txt\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldReturnRangeResultForPathWhenFilenameHasSpecialChars() {
Http.Request req = mockRangeRequest();
Result result = RangeResults.ofPath(req, path, "测 试.tmp");
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(
"attachment; filename=\"? ?.tmp\"; filename*=utf-8''%e6%b5%8b%20%e8%af%95.tmp",
result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldNotReturnRangeResultForPathWhenFilenameHasSpecialChars() {
Http.Request req = mockRegularRequest();
Result result = RangeResults.ofPath(req, path, "测 试.tmp");
assertEquals(OK, result.status());
assertEquals(
"attachment; filename=\"? ?.tmp\"; filename*=utf-8''%e6%b5%8b%20%e8%af%95.tmp",
result.header(CONTENT_DISPOSITION).orElse(""));
}
// -- Files
@Test
public void shouldReturnRangeResultForFile() {
Http.Request req = mockRangeRequest();
Result result = RangeResults.ofFile(req, path.toFile());
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(
"attachment; filename=\"test.tmp\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldNotReturnRangeResultForFileWhenHeaderIsNotPresent() {
Http.Request req = mockRegularRequest();
Result result = RangeResults.ofFile(req, path.toFile());
assertEquals(OK, result.status());
assertEquals(
"attachment; filename=\"test.tmp\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldReturnRangeResultForFileWithCustomFilename() {
Http.Request req = mockRangeRequest();
Result result = RangeResults.ofFile(req, path.toFile(), "file.txt");
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(
"attachment; filename=\"file.txt\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldNotReturnRangeResultForFileWhenHeaderIsNotPresentWithCustomFilename() {
Http.Request req = mockRegularRequest();
Result result = RangeResults.ofFile(req, path.toFile(), "file.txt");
assertEquals(OK, result.status());
assertEquals(
"attachment; filename=\"file.txt\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldReturnRangeResultForFileWhenFilenameHasSpecialChars() {
Http.Request req = mockRangeRequest();
Result result = RangeResults.ofFile(req, path.toFile(), "测 试.tmp");
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(
"attachment; filename=\"? ?.tmp\"; filename*=utf-8''%e6%b5%8b%20%e8%af%95.tmp",
result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldNotReturnRangeResultForFileWhenFilenameHasSpecialChars() {
Http.Request req = mockRegularRequest();
Result result = RangeResults.ofFile(req, path.toFile(), "测 试.tmp");
assertEquals(OK, result.status());
assertEquals(
"attachment; filename=\"? ?.tmp\"; filename*=utf-8''%e6%b5%8b%20%e8%af%95.tmp",
result.header(CONTENT_DISPOSITION).orElse(""));
}
// -- Sources
@Test
public void shouldNotReturnRangeResultForSourceWhenHeaderIsNotPresent() throws IOException {
Http.Request req = mockRegularRequest();
Source<ByteString, CompletionStage<IOResult>> source = FileIO.fromPath(path);
Result result =
RangeResults.ofSource(req, Files.size(path), source, path.toFile().getName(), BINARY);
assertEquals(OK, result.status());
assertEquals(BINARY, result.body().contentType().orElse(""));
}
@Test
public void shouldReturnRangeResultForSourceWhenHeaderIsPresentAndContentTypeWasSpecified()
throws IOException {
Http.Request req = mockRangeRequest();
Source<ByteString, CompletionStage<IOResult>> source = FileIO.fromPath(path);
Result result =
RangeResults.ofSource(req, Files.size(path), source, path.toFile().getName(), TEXT);
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(TEXT, result.body().contentType().orElse(""));
}
@Test
public void shouldReturnRangeResultForSourceWithCustomFilename() throws IOException {
Http.Request req = mockRangeRequest();
Source<ByteString, CompletionStage<IOResult>> source = FileIO.fromPath(path);
Result result = RangeResults.ofSource(req, Files.size(path), source, "file.txt", BINARY);
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(BINARY, result.body().contentType().orElse(""));
assertEquals(
"attachment; filename=\"file.txt\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldNotReturnRangeResultForSourceWhenHeaderIsNotPresentWithCustomFilename()
throws IOException {
Http.Request req = mockRegularRequest();
Source<ByteString, CompletionStage<IOResult>> source = FileIO.fromPath(path);
Result result = RangeResults.ofSource(req, Files.size(path), source, "file.txt", BINARY);
assertEquals(OK, result.status());
assertEquals(BINARY, result.body().contentType().orElse(""));
assertEquals(
"attachment; filename=\"file.txt\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldReturnPartialContentForSourceWithGivenEntityLength() throws IOException {
Http.Request req = mockRangeRequest();
long entityLength = Files.size(path);
Source<ByteString, CompletionStage<IOResult>> source = FileIO.fromPath(path);
Result result = RangeResults.ofSource(req, entityLength, source, "file.txt", TEXT);
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(TEXT, result.body().contentType().orElse(""));
assertEquals(
"attachment; filename=\"file.txt\"", result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldNotReturnRangeResultForStreamWhenFilenameHasSpecialChars() throws IOException {
Http.Request req = mockRegularRequest();
Source<ByteString, CompletionStage<IOResult>> source = FileIO.fromPath(path);
Result result = RangeResults.ofSource(req, Files.size(path), source, "测 试.tmp", BINARY);
assertEquals(OK, result.status());
assertEquals(BINARY, result.body().contentType().orElse(""));
assertEquals(
"attachment; filename=\"? ?.tmp\"; filename*=utf-8''%e6%b5%8b%20%e8%af%95.tmp",
result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldReturnRangeResultForStreamWhenFilenameHasSpecialChars() throws IOException {
Http.Request req = mockRangeRequest();
long entityLength = Files.size(path);
Source<ByteString, CompletionStage<IOResult>> source = FileIO.fromPath(path);
Result result = RangeResults.ofSource(req, entityLength, source, "测 试.tmp", TEXT);
assertEquals(PARTIAL_CONTENT, result.status());
assertEquals(TEXT, result.body().contentType().orElse(""));
assertEquals(
"attachment; filename=\"? ?.tmp\"; filename*=utf-8''%e6%b5%8b%20%e8%af%95.tmp",
result.header(CONTENT_DISPOSITION).orElse(""));
}
@Test
public void shouldHandlePreSeekingSource() throws Exception {
Http.Request req = mockRangeRequestWithOffset();
long entityLength = Files.size(path);
byte[] data = "abcdefghijklmnopqrstuvwxyz".getBytes();
Result result =
RangeResults.ofSource(req, entityLength, preSeekingSourceFunction(data), "file.tmp", TEXT);
assertEquals("bc", getBody(result));
}
@Test
public void shouldHandleNoSeekingSource() throws Exception {
Http.Request req = mockRangeRequestWithOffset();
long entityLength = Files.size(path);
byte[] data = "abcdefghijklmnopqrstuvwxyz".getBytes();
Result result =
RangeResults.ofSource(req, entityLength, noSeekingSourceFunction(data), "file.tmp", TEXT);
assertEquals("bc", getBody(result));
}
@Test(expected = IllegalArgumentException.class)
public void shouldRejectBrokenSourceFunction() throws Exception {
Http.Request req = mockRangeRequestWithOffset();
long entityLength = Files.size(path);
byte[] data = "abcdefghijklmnopqrstuvwxyz".getBytes();
RangeResults.ofSource(req, entityLength, brokenSeekingSourceFunction(data), "file.tmp", TEXT);
}
private RangeResults.SourceFunction preSeekingSourceFunction(byte[] data) {
return offset -> {
ByteString bytes = ByteString.fromArray(data).drop((int) offset);
return new RangeResults.SourceAndOffset(offset, Source.single(bytes));
};
}
private RangeResults.SourceFunction noSeekingSourceFunction(byte[] data) {
return offset -> {
ByteString bytes = ByteString.fromArray(data);
return new RangeResults.SourceAndOffset(0, Source.single(bytes));
};
}
/** A SourceFunction that seeks past the request offset - a bug. */
private RangeResults.SourceFunction brokenSeekingSourceFunction(byte[] data) {
return offset -> {
ByteString bytes = ByteString.fromArray(data).drop((int) offset + 1);
return new RangeResults.SourceAndOffset(offset + 1, Source.single(bytes));
};
}
private Http.Request mockRegularRequest() {
Http.Request request = mock(Http.Request.class);
when(request.header(RANGE)).thenReturn(Optional.empty());
return request;
}
private Http.Request mockRangeRequest() {
Http.Request request = mock(Http.Request.class);
when(request.header(RANGE)).thenReturn(Optional.of("bytes=0-1"));
return request;
}
private Http.Request mockRangeRequestWithOffset() {
Http.Request request = mock(Http.Request.class);
when(request.header(RANGE)).thenReturn(Optional.of("bytes=1-2"));
return request;
}
private String getBody(Result result) throws Exception {
ActorSystem actorSystem = ActorSystem.create("TestSystem");
Materializer mat = Materializer.matFromSystem(actorSystem);
ByteString bs =
Await.result(
FutureConverters.asScala(result.body().consumeData(mat)), Duration.create("60s"));
return bs.utf8String();
}
}
| RangeResultsTest |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.java | {
"start": 2330,
"end": 3506
} | class ____ implements PreparedStatementCallback<Integer> {
private final LobHandler lobHandler;
/**
* Create a new AbstractLobCreatingPreparedStatementCallback for the
* given LobHandler.
* @param lobHandler the LobHandler to create LobCreators with
*/
public AbstractLobCreatingPreparedStatementCallback(LobHandler lobHandler) {
Assert.notNull(lobHandler, "LobHandler must not be null");
this.lobHandler = lobHandler;
}
@Override
public final Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
try (LobCreator lobCreator = this.lobHandler.getLobCreator()) {
setValues(ps, lobCreator);
return ps.executeUpdate();
}
}
/**
* Set values on the given PreparedStatement, using the given
* LobCreator for BLOB/CLOB arguments.
* @param ps the PreparedStatement to use
* @param lobCreator the LobCreator to use
* @throws SQLException if thrown by JDBC methods
* @throws DataAccessException in case of custom exceptions
*/
protected abstract void setValues(PreparedStatement ps, LobCreator lobCreator)
throws SQLException, DataAccessException;
}
| AbstractLobCreatingPreparedStatementCallback |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/AutoValueImmutableFieldsTest.java | {
"start": 5901,
"end": 6403
} | class ____ {
// BUG: Diagnostic contains: ImmutableTable
public abstract Table<String, String, String> countries();
}
""")
.doTest();
}
@Test
public void matchesTwoProperties() {
compilationHelper
.addSourceLines(
"in/Test.java",
"""
import com.google.auto.value.AutoValue;
import java.util.Map;
import java.util.Set;
@AutoValue
abstract | Test |
java | alibaba__nacos | common/src/main/java/com/alibaba/nacos/common/constant/RequestUrlConstants.java | {
"start": 732,
"end": 850
} | interface ____ {
String HTTP_PREFIX = "http://";
String HTTPS_PREFIX = "https://";
}
| RequestUrlConstants |
java | apache__camel | dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/common/JSonHelper.java | {
"start": 1028,
"end": 2649
} | class ____ {
private JSonHelper() {
}
/**
* Prints the JSon in pretty mode with no color
*/
public static String prettyPrint(String json, int spaces) {
return Jsoner.prettyPrint(json, spaces);
}
/**
* Prints the JSon with ANSi color (similar to jq)
*/
public static String colorPrint(String json, int spaces, boolean pretty) {
return Jsoner.colorPrint(json, spaces, pretty, new Jsoner.ColorPrintElement() {
Yytoken.Types prev;
@Override
public String color(Yytoken.Types type, Object value) {
String s = value != null ? value.toString() : "null";
switch (type) {
case COLON, COMMA, LEFT_SQUARE, RIGHT_SQUARE, LEFT_BRACE, RIGHT_BRACE ->
s = Ansi.ansi().bgDefault().bold().a(s).reset().toString();
case VALUE -> {
if (Yytoken.Types.COLON == prev) {
if (StringHelper.isQuoted(s)) {
s = Ansi.ansi().fg(Ansi.Color.GREEN).a(s).reset().toString();
} else {
s = Ansi.ansi().bgDefault().a(s).reset().toString();
}
} else {
s = Ansi.ansi().fgBright(Ansi.Color.BLUE).a(s).reset().toString();
}
}
default -> {
}
}
prev = type;
return s;
}
});
}
}
| JSonHelper |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/utils/HandwrittenSelectorUtil.java | {
"start": 1588,
"end": 2002
} | class ____ {
/** Create a RowDataKeySelector to extract keys of {@link RowData}. */
public static RowDataKeySelector getRowDataSelector(
int[] keyFields, LogicalType[] inputFieldTypes) {
return keyFields.length > 0
? new HandwrittenKeySelector(keyFields, inputFieldTypes)
: EmptyRowDataKeySelector.INSTANCE;
}
private static | HandwrittenSelectorUtil |
java | apache__camel | core/camel-management/src/main/java/org/apache/camel/management/mbean/ManagedDataFormat.java | {
"start": 1339,
"end": 2839
} | class ____ implements ManagedInstance, ManagedDataFormatMBean {
private final CamelContext camelContext;
private final DataFormat dataFormat;
public ManagedDataFormat(CamelContext camelContext, DataFormat dataFormat) {
this.camelContext = camelContext;
this.dataFormat = dataFormat;
}
public void init(ManagementStrategy strategy) {
// noop
}
public DataFormat getDataFormat() {
return dataFormat;
}
public CamelContext getContext() {
return camelContext;
}
@Override
public String getName() {
if (dataFormat instanceof DataFormatName dataFormatName) {
return dataFormatName.getDataFormatName();
}
return null;
}
@Override
public String getCamelId() {
return camelContext.getName();
}
@Override
public String getCamelManagementName() {
return camelContext.getManagementName();
}
@Override
public String getState() {
// must use String type to be sure remote JMX can read the attribute without requiring Camel classes.
if (dataFormat instanceof StatefulService statefulService) {
ServiceStatus status = statefulService.getStatus();
return status.name();
}
// assume started if not a ServiceSupport instance
return ServiceStatus.Started.name();
}
@Override
public DataFormat getInstance() {
return dataFormat;
}
}
| ManagedDataFormat |
java | apache__flink | flink-python/src/main/java/org/apache/flink/client/python/PythonDriverOptions.java | {
"start": 1121,
"end": 2230
} | class ____ {
private final Configuration pythonDependencyConfig;
@Nullable private final String entryPointModule;
@Nullable private final String entryPointScript;
@Nonnull private final List<String> programArgs;
@Nonnull
Configuration getPythonDependencyConfig() {
return pythonDependencyConfig;
}
@Nullable
String getEntryPointModule() {
return entryPointModule;
}
Optional<String> getEntryPointScript() {
return Optional.ofNullable(entryPointScript);
}
@Nonnull
List<String> getProgramArgs() {
return programArgs;
}
PythonDriverOptions(
@Nonnull Configuration pythonDependencyConfig,
@Nullable String entryPointModule,
@Nullable String entryPointScript,
List<String> programArgs) {
this.pythonDependencyConfig = requireNonNull(pythonDependencyConfig);
this.entryPointModule = entryPointModule;
this.entryPointScript = entryPointScript;
this.programArgs = requireNonNull(programArgs, "programArgs");
}
}
| PythonDriverOptions |
java | spring-projects__spring-security | oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolverTests.java | {
"start": 2602,
"end": 32501
} | class ____ {
private ClientRegistration registration1;
private ClientRegistration registration2;
private ClientRegistration pkceClientRegistration;
private ClientRegistration fineRedirectUriTemplateRegistration;
private ClientRegistration publicClientRegistration;
private ClientRegistration oidcRegistration;
private ClientRegistrationRepository clientRegistrationRepository;
private final String authorizationRequestBaseUri = "/oauth2/authorization";
private DefaultOAuth2AuthorizationRequestResolver resolver;
@BeforeEach
public void setUp() {
this.registration1 = TestClientRegistrations.clientRegistration().build();
this.registration2 = TestClientRegistrations.clientRegistration2().build();
this.pkceClientRegistration = pkceClientRegistration().build();
this.fineRedirectUriTemplateRegistration = fineRedirectUriTemplateClientRegistration().build();
// @formatter:off
this.publicClientRegistration = TestClientRegistrations.clientRegistration()
.registrationId("public-client-registration-id")
.clientId("public-client-id")
.clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
.clientSecret(null)
.build();
this.oidcRegistration = TestClientRegistrations.clientRegistration()
.registrationId("oidc-registration-id")
.scope(OidcScopes.OPENID)
.build();
// @formatter:on
this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1,
this.registration2, this.pkceClientRegistration, this.fineRedirectUriTemplateRegistration,
this.publicClientRegistration, this.oidcRegistration);
this.resolver = new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository,
this.authorizationRequestBaseUri);
}
@Test
void authorizationRequestBaseUriEqualToRedirectFilter() {
assertThat(DefaultOAuth2AuthorizationRequestResolver.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI)
.isEqualTo(OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultOAuth2AuthorizationRequestResolver(null, this.authorizationRequestBaseUri));
}
@Test
public void constructorWhenAuthorizationRequestBaseUriIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, null));
}
@Test
public void setAuthorizationRequestCustomizerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.resolver.setAuthorizationRequestCustomizer(null));
}
@Test
public void resolveWhenNotAuthorizationRequestThenDoesNotResolve() {
String requestUri = "/path";
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest).isNull();
}
// gh-8650
@Test
public void resolveWhenNotAuthorizationRequestThenRequestBodyNotConsumed() throws IOException {
String requestUri = "/path";
MockHttpServletRequest request = post(requestUri).build();
request.setContent("foo".getBytes(StandardCharsets.UTF_8));
request.setCharacterEncoding(StandardCharsets.UTF_8.name());
HttpServletRequest spyRequest = Mockito.spy(request);
this.resolver.resolve(spyRequest);
Mockito.verify(spyRequest, Mockito.never()).getReader();
Mockito.verify(spyRequest, Mockito.never()).getInputStream();
Mockito.verify(spyRequest, Mockito.never()).getParameter(ArgumentMatchers.anyString());
Mockito.verify(spyRequest, Mockito.never()).getParameterMap();
Mockito.verify(spyRequest, Mockito.never()).getParameterNames();
Mockito.verify(spyRequest, Mockito.never()).getParameterValues(ArgumentMatchers.anyString());
}
@Test
public void resolveWhenAuthorizationRequestWithInvalidClientThenThrowIllegalArgumentException() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId()
+ "-invalid";
MockHttpServletRequest request = get(requestUri).build();
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.resolver.resolve(request))
.withMessage("Invalid Client Registration with Id: " + clientRegistration.getRegistrationId() + "-invalid");
// @formatter:on
}
@Test
public void resolveWhenAuthorizationRequestWithValidClientThenResolves() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest).isNotNull();
assertThat(authorizationRequest.getAuthorizationUri())
.isEqualTo(clientRegistration.getProviderDetails().getAuthorizationUri());
assertThat(authorizationRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
assertThat(authorizationRequest.getResponseType()).isEqualTo(OAuth2AuthorizationResponseType.CODE);
assertThat(authorizationRequest.getClientId()).isEqualTo(clientRegistration.getClientId());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
assertThat(authorizationRequest.getScopes()).isEqualTo(clientRegistration.getScopes());
assertThat(authorizationRequest.getState()).isNotNull();
assertThat(authorizationRequest.getAdditionalParameters())
.doesNotContainKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAttributes()).containsExactly(
entry(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()),
entry(PkceParameterNames.CODE_VERIFIER,
authorizationRequest.getAttributes().get(PkceParameterNames.CODE_VERIFIER)));
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
@Test
public void resolveWhenClientAuthorizationRequiredExceptionAvailableThenResolves() {
ClientRegistration clientRegistration = this.registration2;
String requestUri = "/path";
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request,
clientRegistration.getRegistrationId());
assertThat(authorizationRequest).isNotNull();
assertThat(authorizationRequest.getAttributes()).containsExactly(
entry(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()),
entry(PkceParameterNames.CODE_VERIFIER,
authorizationRequest.getAttributes().get(PkceParameterNames.CODE_VERIFIER)));
}
@Test
public void resolveWhenAuthorizationRequestRedirectUriTemplatedThenRedirectUriExpanded() {
ClientRegistration clientRegistration = this.registration2;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestRedirectUriTemplatedThenHttpRedirectUriWithExtraVarsExpanded() {
ClientRegistration clientRegistration = this.fineRedirectUriTemplateRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get("localhost:8080" + requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost:8080/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestRedirectUriTemplatedThenHttpsRedirectUriWithExtraVarsExpanded() {
ClientRegistration clientRegistration = this.fineRedirectUriTemplateRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get("https://localhost:8081" + requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("https://localhost:8081/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestIncludesPort80ThenExpandedRedirectUriWithExtraVarsExcludesPort() {
ClientRegistration clientRegistration = this.fineRedirectUriTemplateRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get("http://localhost" + requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestIncludesPort443ThenExpandedRedirectUriWithExtraVarsExcludesPort() {
ClientRegistration clientRegistration = this.fineRedirectUriTemplateRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get("https://localhost:443" + requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("https://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestHasNoPortThenInvalidUrlException() {
ClientRegistration clientRegistration = this.fineRedirectUriTemplateRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).port(-1).build();
assertThatExceptionOfType(InvalidUrlException.class).isThrownBy(() -> this.resolver.resolve(request));
}
// gh-5520
@Test
public void resolveWhenAuthorizationRequestRedirectUriTemplatedThenRedirectUriExpandedExcludesQueryString() {
ClientRegistration clientRegistration = this.registration2;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri + "?foo=bar").build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestIncludesPort80ThenExpandedRedirectUriExcludesPort() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id"
+ "&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
@Test
public void resolveWhenAuthorizationRequestIncludesPort443ThenExpandedRedirectUriExcludesPort() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get("https://example.com:443" + requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=https://example.com/login/oauth2/code/registration-id"
+ "&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
@Test
public void resolveWhenClientAuthorizationRequiredExceptionAvailableThenRedirectUriIsAuthorize() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = "/path";
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request,
clientRegistration.getRegistrationId());
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/authorize/oauth2/code/registration-id&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
@Test
public void resolveWhenAuthorizationRequestOAuth2LoginThenRedirectUriIsLogin() {
ClientRegistration clientRegistration = this.registration2;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id-2&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id-2"
+ "&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
@Test
public void resolveWhenAuthorizationRequestHasActionParameterAuthorizeThenRedirectUriIsAuthorize() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).param("action", "authorize").build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/authorize/oauth2/code/registration-id&"
+ "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
@Test
public void resolveWhenAuthorizationRequestHasActionParameterLoginThenRedirectUriIsLogin() {
ClientRegistration clientRegistration = this.registration2;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).param("action", "login").build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id-2&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id-2&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
@Test
public void resolveWhenAuthorizationRequestWithValidPublicClientThenResolves() {
ClientRegistration clientRegistration = this.publicClientRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest).isNotNull();
assertThat(authorizationRequest.getAuthorizationUri())
.isEqualTo(clientRegistration.getProviderDetails().getAuthorizationUri());
assertThat(authorizationRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
assertThat(authorizationRequest.getResponseType()).isEqualTo(OAuth2AuthorizationResponseType.CODE);
assertThat(authorizationRequest.getClientId()).isEqualTo(clientRegistration.getClientId());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
assertThat(authorizationRequest.getScopes()).isEqualTo(clientRegistration.getScopes());
assertThat(authorizationRequest.getState()).isNotNull();
assertThat(authorizationRequest.getAdditionalParameters())
.doesNotContainKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAdditionalParameters()).containsKey(PkceParameterNames.CODE_CHALLENGE);
assertThat(authorizationRequest.getAdditionalParameters())
.contains(entry(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"));
assertThat(authorizationRequest.getAttributes())
.contains(entry(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()));
assertThat(authorizationRequest.getAttributes()).containsKey(PkceParameterNames.CODE_VERIFIER);
assertThat((String) authorizationRequest.getAttribute(PkceParameterNames.CODE_VERIFIER))
.matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=public-client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/public-client-registration-id&"
+ "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "code_challenge_method=S256");
}
// gh-6548
@Test
public void resolveWhenAuthorizationRequestApplyPkceToConfidentialClientsThenApplied() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertPkceApplied(authorizationRequest, clientRegistration);
clientRegistration = this.registration2;
requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
request = get(requestUri).build();
authorizationRequest = this.resolver.resolve(request);
assertPkceApplied(authorizationRequest, clientRegistration);
}
private void assertPkceApplied(OAuth2AuthorizationRequest authorizationRequest,
ClientRegistration clientRegistration) {
assertThat(authorizationRequest.getAdditionalParameters()).containsKey(PkceParameterNames.CODE_CHALLENGE);
assertThat(authorizationRequest.getAdditionalParameters())
.contains(entry(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"));
assertThat(authorizationRequest.getAttributes()).containsKey(PkceParameterNames.CODE_VERIFIER);
assertThat((String) authorizationRequest.getAttribute(PkceParameterNames.CODE_VERIFIER))
.matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&" + "client_id="
+ clientRegistration.getClientId() + "&" + "scope=read:user&" + "state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId() + "&"
+ "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "code_challenge_method=S256");
}
private void assertPkceNotApplied(OAuth2AuthorizationRequest authorizationRequest,
ClientRegistration clientRegistration) {
assertThat(authorizationRequest.getAdditionalParameters()).doesNotContainKey(PkceParameterNames.CODE_CHALLENGE);
assertThat(authorizationRequest.getAdditionalParameters())
.doesNotContainKey(PkceParameterNames.CODE_CHALLENGE_METHOD);
assertThat(authorizationRequest.getAttributes()).doesNotContainKey(PkceParameterNames.CODE_VERIFIER);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&" + "client_id="
+ clientRegistration.getClientId() + "&" + "scope=read:user&" + "state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthenticationRequestWithValidOidcClientThenResolves() {
ClientRegistration clientRegistration = this.oidcRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest).isNotNull();
assertThat(authorizationRequest.getAuthorizationUri())
.isEqualTo(clientRegistration.getProviderDetails().getAuthorizationUri());
assertThat(authorizationRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
assertThat(authorizationRequest.getResponseType()).isEqualTo(OAuth2AuthorizationResponseType.CODE);
assertThat(authorizationRequest.getClientId()).isEqualTo(clientRegistration.getClientId());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
assertThat(authorizationRequest.getScopes()).isEqualTo(clientRegistration.getScopes());
assertThat(authorizationRequest.getState()).isNotNull();
assertThat(authorizationRequest.getAdditionalParameters())
.doesNotContainKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAdditionalParameters()).containsKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes())
.contains(entry(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()));
assertThat(authorizationRequest.getAttributes()).containsKey(OidcParameterNames.NONCE);
assertThat((String) authorizationRequest.getAttribute(OidcParameterNames.NONCE))
.matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=openid&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/oidc-registration-id&"
+ "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
// gh-7696
@Test
public void resolveWhenAuthorizationRequestCustomizerRemovesNonceThenQueryExcludesNonce() {
ClientRegistration clientRegistration = this.oidcRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
this.resolver.setAuthorizationRequestCustomizer(
(builder) -> builder.additionalParameters((params) -> params.remove(OidcParameterNames.NONCE))
.attributes((attrs) -> attrs.remove(OidcParameterNames.NONCE)));
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAdditionalParameters()).doesNotContainKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes()).doesNotContainKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes()).containsKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=openid&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/oidc-registration-id&"
+ "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
}
@Test
public void resolveWhenAuthorizationRequestCustomizerAddsParameterThenQueryIncludesParameter() {
ClientRegistration clientRegistration = this.oidcRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.authorizationRequestUri((uriBuilder) -> {
uriBuilder.queryParam("param1", "value1");
return uriBuilder.build();
}));
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=openid&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/oidc-registration-id&"
+ "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}"
+ "&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256¶m1=value1");
}
@Test
public void resolveWhenAuthorizationRequestCustomizerOverridesParameterThenQueryIncludesParameter() {
ClientRegistration clientRegistration = this.oidcRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.parameters((params) -> {
params.put("appid", params.get("client_id"));
params.remove("client_id");
}));
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri()).matches(
"https://example.com/login/oauth/authorize\\?" + "response_type=code&" + "scope=openid&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/oidc-registration-id&"
+ "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}"
+ "&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256&appid=client-id");
}
@Test
public void resolveWhenAuthorizationRequestNoProvideAuthorizationRequestBaseUri() {
OAuth2AuthorizationRequestResolver resolver = new DefaultOAuth2AuthorizationRequestResolver(
this.clientRegistrationRepository);
String requestUri = this.authorizationRequestBaseUri + "/" + this.registration2.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + this.registration2.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestProvideCodeChallengeMethod() {
ClientRegistration clientRegistration = this.pkceClientRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = get(requestUri).build();
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAdditionalParameters().containsKey(PkceParameterNames.CODE_CHALLENGE_METHOD))
.isTrue();
}
private static ClientRegistration.Builder pkceClientRegistration() {
return ClientRegistration.withRegistrationId("pkce")
.redirectUri("{baseUrl}/{action}/oauth2/code/{registrationId}")
.clientSettings(ClientRegistration.ClientSettings.builder().requireProofKey(true).build())
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.scope("read:user")
.authorizationUri("https://example.com/login/oauth/authorize")
.tokenUri("https://example.com/login/oauth/access_token")
.userInfoUri("https://api.example.com/user")
.userNameAttributeName("id")
.clientName("Client Name")
.clientId("client-id-3")
.clientSecret("client-secret");
}
private static ClientRegistration.Builder fineRedirectUriTemplateClientRegistration() {
// @formatter:off
return ClientRegistration.withRegistrationId("fine-redirect-uri-template-client-registration")
.redirectUri("{baseScheme}://{baseHost}{basePort}{basePath}/{action}/oauth2/code/{registrationId}")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.scope("read:user")
.authorizationUri("https://example.com/login/oauth/authorize")
.tokenUri("https://example.com/login/oauth/access_token")
.userInfoUri("https://api.example.com/user")
.userNameAttributeName("id")
.clientName("Fine Redirect Uri Template Client")
.clientId("fine-redirect-uri-template-client")
.clientSecret("client-secret");
// @formatter:on
}
}
| DefaultOAuth2AuthorizationRequestResolverTests |
java | eclipse-vertx__vert.x | vertx-core/src/test/java/io/vertx/tests/http/SharedHttpClientTest.java | {
"start": 7854,
"end": 9100
} | class ____ extends AbstractVerticle implements Handler<HttpServerRequest> {
volatile Promise<Void> replyLatch;
Set<HttpConnection> connections = Collections.synchronizedSet(new HashSet<>());
volatile int maxConnections;
@Override
public void start(Promise<Void> startPromise) throws Exception {
replyLatch = ((VertxInternal) vertx).promise();
vertx.createHttpServer()
.connectionHandler(conn -> {
connections.add(conn);
conn.closeHandler(v -> connections.remove(conn));
maxConnections = Math.max(maxConnections, connections.size());
})
.requestHandler(this)
.listen(HttpTest.DEFAULT_HTTP_PORT)
.<Void>mapEmpty()
.onComplete(startPromise);
}
@Override
public void handle(HttpServerRequest req) {
replyLatch.future().onComplete(ar -> req.response().end());
}
}
private static DeploymentOptions deploymentOptions(int instances, HttpClientOptions options, PoolOptions poolOptions) {
return new DeploymentOptions()
.setInstances(instances)
.setConfig(new JsonObject()
.put("httpClientOptions", options.toJson())
.put("poolOptions", poolOptions.toJson())
);
}
}
| ServerVerticle |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/ConcatFunctionProcessor.java | {
"start": 873,
"end": 3120
} | class ____ extends BinaryProcessor {
public static final String NAME = "scon";
public ConcatFunctionProcessor(Processor source1, Processor source2) {
super(source1, source2);
}
public ConcatFunctionProcessor(StreamInput in) throws IOException {
super(in);
}
@Override
public Object process(Object input) {
Object l = left().process(input);
checkParameter(l);
Object r = right().process(input);
checkParameter(r);
return doProcess(l, r);
}
@Override
protected Object doProcess(Object left, Object right) {
return process(left, right);
}
/**
* Used in Painless scripting
*/
public static Object process(Object source1, Object source2) {
if (source1 == null && source2 == null) {
return StringUtils.EMPTY;
}
if (source1 == null) {
return source2;
}
if (source2 == null) {
return source1;
}
if ((source1 instanceof String || source1 instanceof Character) == false) {
throw new SqlIllegalArgumentException("A string/char is required; received [{}]", source1);
}
if ((source2 instanceof String || source2 instanceof Character) == false) {
throw new SqlIllegalArgumentException("A string/char is required; received [{}]", source2);
}
String str1 = source1.toString();
String str2 = source2.toString();
checkResultLength(str1.length() + str2.length());
return str1.concat(str2);
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ConcatFunctionProcessor other = (ConcatFunctionProcessor) obj;
return Objects.equals(left(), other.left()) && Objects.equals(right(), other.right());
}
@Override
public int hashCode() {
return Objects.hash(left(), right());
}
@Override
protected void doWrite(StreamOutput out) throws IOException {}
}
| ConcatFunctionProcessor |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/matchers/text/MatcherToStringTest.java | {
"start": 857,
"end": 2764
} | class ____ extends MatcherWithDescription {
@Override
public boolean matches(Object argument) {
return false;
}
}
@Test
public void better_toString_for_matchers() {
assertEquals(
"<Matcher without description>",
MatcherToString.toString(new MatcherWithoutDescription()));
assertEquals(
"*my custom description*", MatcherToString.toString(new MatcherWithDescription()));
assertEquals(
"*my custom description*",
MatcherToString.toString(new MatcherWithInheritedDescription()));
}
@Test
public void default_name_for_anonymous_matchers() {
ArgumentMatcher<Object> anonymousMatcher =
new ArgumentMatcher<Object>() {
@Override
public boolean matches(Object argument) {
return false;
}
};
assertEquals("<custom argument matcher>", MatcherToString.toString(anonymousMatcher));
ArgumentMatcher<Object> anonymousDescriptiveMatcher =
new MatcherWithDescription() {
@Override
public boolean matches(Object argument) {
return false;
}
};
assertEquals(
"*my custom description*", MatcherToString.toString(anonymousDescriptiveMatcher));
}
@Test
public void default_name_for_synthetic_matchers() {
ArgumentMatcher<Object> lambdaMatcher = argument -> true;
assertEquals("<custom argument matcher>", MatcherToString.toString(lambdaMatcher));
ArgumentMatcher<Object> methodRefMatcher = lambdaMatcher::matches;
assertEquals("<custom argument matcher>", MatcherToString.toString(methodRefMatcher));
}
}
| MatcherWithInheritedDescription |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/internal/MappingMetamodelImpl.java | {
"start": 3908,
"end": 5827
} | class ____
implements MappingMetamodelImplementor, JpaMetamodel, Metamodel, QueryParameterBindingTypeResolver, BindingContext, Serializable {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// JpaMetamodel
private final JpaMetamodelImpl jpaMetamodel;
private final Map<Class<?>, String> entityProxyInterfaceMap = new ConcurrentHashMap<>();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// RuntimeModel
private final EntityPersisterConcurrentMap entityPersisterMap = new EntityPersisterConcurrentMap();
private final Map<String, CollectionPersister> collectionPersisterMap = new ConcurrentHashMap<>();
private final Map<String, Set<String>> collectionRolesByEntityParticipant = new ConcurrentHashMap<>();
private final Map<NavigableRole, EmbeddableValuedModelPart> embeddableValuedModelPart = new ConcurrentHashMap<>();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// DomainMetamodel
private final Set<EntityNameResolver> entityNameResolvers = new HashSet<>();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// NOTE: Relational/mapping information is not part of the JPA metamodel
// (type system). However, this relational/mapping info *is* part of the
// Hibernate metamodel. This is a mismatch. Normally this is not a problem
// - ignoring Hibernate's representation mode (entity mode), the Class
// object for an entity (or mapped superclass) always refers to the same
// JPA EntityType and Hibernate EntityPersister. The problem arises with
// embeddables. For an embeddable, as with the rest of its metamodel,
// Hibernate combines the embeddable's relational/mapping while JPA does
// not. This is perfectly consistent with each paradigm. But it results
// in a mismatch since JPA expects a single "type descriptor" for a
// given embeddable | MappingMetamodelImpl |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientHttpObservationDocumentation.java | {
"start": 3198,
"end": 3388
} | enum ____ implements KeyName {
/**
* The full HTTP request URI.
*/
HTTP_URL {
@Override
public String asString() {
return "http.url";
}
}
}
}
| HighCardinalityKeyNames |
java | apache__dubbo | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.java | {
"start": 2697,
"end": 8277
} | class ____<T> extends AbstractStateRouter<T> {
public static final String NAME = "SCRIPT_ROUTER";
private static final int SCRIPT_ROUTER_DEFAULT_PRIORITY = 0;
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ScriptStateRouter.class);
private static final ConcurrentMap<String, ScriptEngine> ENGINES = new ConcurrentHashMap<>();
private final ScriptEngine engine;
private final String rule;
private CompiledScript function;
private AccessControlContext accessControlContext;
{
// Just give permission of reflect to access member.
Permissions perms = new Permissions();
perms.add(new RuntimePermission("accessDeclaredMembers"));
// Cast to Certificate[] required because of ambiguity:
ProtectionDomain domain = new ProtectionDomain(new CodeSource(null, (Certificate[]) null), perms);
accessControlContext = new AccessControlContext(new ProtectionDomain[] {domain});
}
public ScriptStateRouter(URL url) {
super(url);
this.setUrl(url);
engine = getEngine(url);
rule = getRule(url);
try {
Compilable compilable = (Compilable) engine;
function = compilable.compile(rule);
} catch (ScriptException e) {
logger.error(
CLUSTER_SCRIPT_EXCEPTION,
"script route rule invalid",
"",
"script route error, rule has been ignored. rule: " + rule + ", url: "
+ RpcContext.getServiceContext().getUrl(),
e);
}
}
/**
* get rule from url parameters.
*/
private String getRule(URL url) {
String vRule = url.getParameterAndDecoded(RULE_KEY);
if (StringUtils.isEmpty(vRule)) {
throw new IllegalStateException("route rule can not be empty.");
}
return vRule;
}
/**
* create ScriptEngine instance by type from url parameters, then cache it
*/
private ScriptEngine getEngine(URL url) {
String type = url.getParameter(TYPE_KEY, DEFAULT_SCRIPT_TYPE_KEY);
return ConcurrentHashMapUtils.computeIfAbsent(ENGINES, type, t -> {
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(type);
if (scriptEngine == null) {
throw new IllegalStateException("unsupported route engine type: " + type);
}
return scriptEngine;
});
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (engine == null || function == null) {
if (needToPrintMessage) {
messageHolder.set("Directly Return. Reason: engine or function is null");
}
return invokers;
}
Bindings bindings = createBindings(invokers, invocation);
return getRoutedInvokers(
invokers,
AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> {
try {
return function.eval(bindings);
} catch (ScriptException e) {
logger.error(
CLUSTER_SCRIPT_EXCEPTION,
"Scriptrouter exec script error",
"",
"Script route error, rule has been ignored. rule: " + rule + ", method:"
+ RpcUtils.getMethodName(invocation) + ", url: "
+ RpcContext.getContext().getUrl(),
e);
return invokers;
}
},
accessControlContext));
}
/**
* get routed invokers from result of script rule evaluation
*/
@SuppressWarnings("unchecked")
protected BitList<Invoker<T>> getRoutedInvokers(BitList<Invoker<T>> invokers, Object obj) {
BitList<Invoker<T>> result = invokers.clone();
if (obj instanceof Invoker[]) {
result.retainAll(Arrays.asList((Invoker<T>[]) obj));
} else if (obj instanceof Object[]) {
result.retainAll(
Arrays.stream((Object[]) obj).map(item -> (Invoker<T>) item).collect(Collectors.toList()));
} else {
result.retainAll((List<Invoker<T>>) obj);
}
return result;
}
/**
* create bindings for script engine
*/
private Bindings createBindings(List<Invoker<T>> invokers, Invocation invocation) {
Bindings bindings = engine.createBindings();
// create a new List of invokers
bindings.put("invokers", new ArrayList<>(invokers));
bindings.put("invocation", invocation);
bindings.put("context", RpcContext.getClientAttachment());
return bindings;
}
@Override
public boolean isRuntime() {
return this.getUrl().getParameter(RUNTIME_KEY, false);
}
@Override
public boolean isForce() {
return this.getUrl().getParameter(FORCE_KEY, false);
}
}
| ScriptStateRouter |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/util/ServiceLoaderUtil.java | {
"start": 1308,
"end": 1524
} | class ____ be considered internal.
* </p>
* <p>
* A common source of {@link ServiceLoader} failures, when running in a multi-classloader environment, is the
* presence of multiple classes with the same | should |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/beanbuilder/TestBeanWithStaticCreator.java | {
"start": 49,
"end": 270
} | class ____ implements BeanWithStaticCreator {
private TestBeanWithStaticCreator() {}
public static TestBeanWithStaticCreator create() {
return new TestBeanWithStaticCreator();
}
}
| TestBeanWithStaticCreator |
java | apache__camel | components/camel-ibm/camel-ibm-watson-language/src/main/java/org/apache/camel/component/ibm/watson/language/WatsonLanguageConfiguration.java | {
"start": 1041,
"end": 4316
} | class ____ implements Cloneable {
@UriParam(label = "security", secret = true)
@Metadata(required = true)
private String apiKey;
@UriParam(label = "common")
private String serviceUrl;
@UriParam(label = "producer")
private WatsonLanguageOperations operation;
@UriParam(label = "producer", defaultValue = "true")
private boolean analyzeSentiment = true;
@UriParam(label = "producer")
private boolean analyzeEmotion;
@UriParam(label = "producer", defaultValue = "true")
private boolean analyzeEntities = true;
@UriParam(label = "producer", defaultValue = "true")
private boolean analyzeKeywords = true;
@UriParam(label = "producer")
private boolean analyzeConcepts;
@UriParam(label = "producer")
private boolean analyzeCategories;
public String getApiKey() {
return apiKey;
}
/**
* The IBM Cloud API key for authentication
*/
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getServiceUrl() {
return serviceUrl;
}
/**
* The service endpoint URL. If not specified, the default URL will be used.
*/
public void setServiceUrl(String serviceUrl) {
this.serviceUrl = serviceUrl;
}
public WatsonLanguageOperations getOperation() {
return operation;
}
/**
* The operation to perform
*/
public void setOperation(WatsonLanguageOperations operation) {
this.operation = operation;
}
public boolean isAnalyzeSentiment() {
return analyzeSentiment;
}
/**
* Enable sentiment analysis
*/
public void setAnalyzeSentiment(boolean analyzeSentiment) {
this.analyzeSentiment = analyzeSentiment;
}
public boolean isAnalyzeEmotion() {
return analyzeEmotion;
}
/**
* Enable emotion analysis
*/
public void setAnalyzeEmotion(boolean analyzeEmotion) {
this.analyzeEmotion = analyzeEmotion;
}
public boolean isAnalyzeEntities() {
return analyzeEntities;
}
/**
* Enable entity extraction
*/
public void setAnalyzeEntities(boolean analyzeEntities) {
this.analyzeEntities = analyzeEntities;
}
public boolean isAnalyzeKeywords() {
return analyzeKeywords;
}
/**
* Enable keyword extraction
*/
public void setAnalyzeKeywords(boolean analyzeKeywords) {
this.analyzeKeywords = analyzeKeywords;
}
public boolean isAnalyzeConcepts() {
return analyzeConcepts;
}
/**
* Enable concept extraction
*/
public void setAnalyzeConcepts(boolean analyzeConcepts) {
this.analyzeConcepts = analyzeConcepts;
}
public boolean isAnalyzeCategories() {
return analyzeCategories;
}
/**
* Enable category classification
*/
public void setAnalyzeCategories(boolean analyzeCategories) {
this.analyzeCategories = analyzeCategories;
}
public WatsonLanguageConfiguration copy() {
try {
return (WatsonLanguageConfiguration) clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeCamelException(e);
}
}
}
| WatsonLanguageConfiguration |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/jdbc/mutation/TableInclusionChecker.java | {
"start": 322,
"end": 546
} | interface ____ {
/**
* Perform the check
*
* @return {@code true} indicates the table should be included;
* {@code false} indicates it should not
*/
boolean include(TableMapping tableMapping);
}
| TableInclusionChecker |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ReferenceEqualityTest.java | {
"start": 7333,
"end": 7697
} | class ____ {
public boolean equals(Object o) {
return this == o;
}
}
""")
.doTest();
}
@Test
public void negative_enum() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import javax.lang.model.element.ElementKind;
| Test |
java | google__dagger | javatests/dagger/internal/codegen/DaggerSuperficialValidationTest.java | {
"start": 21475,
"end": 23111
} | class ____<T> : MissingType<T>",
"}"),
(processingEnv, superficialValidation) -> {
XTypeElement outerElement = processingEnv.findTypeElement("test.Outer");
XMethodElement getChildMethod = outerElement.getDeclaredMethods().get(0);
ValidationException exception =
assertThrows(
ValidationException.KnownErrorType.class,
() ->
superficialValidation.validateTypeHierarchyOf(
"return type", getChildMethod, getChildMethod.getReturnType()));
// TODO(b/248552462): Javac and KSP should match once this bug is fixed.
boolean isJavac = processingEnv.getBackend() == XProcessingEnv.Backend.JAVAC;
assertThat(exception)
.hasMessageThat()
.contains(
String.format(
NEW_LINES.join(
"Validation trace:",
" => element (CLASS): test.Outer",
" => element (METHOD): getChild()",
" => type (DECLARED return type): test.Outer.Child<java.lang.Long>",
" => type (DECLARED supertype): test.Outer.Parent<java.lang.Long>",
" => type (ERROR supertype): %s"),
isJavac ? "MissingType<T>" : "MissingType"));
});
}
@Test
public void invalidSuperclassTypeParameterInTypeHierarchy() {
runTest(
CompilerTests.javaSource(
"test.Outer",
"package test;",
"",
"final | Parent |
java | spring-projects__spring-framework | spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java | {
"start": 11980,
"end": 12629
} | class ____ {
@JsonView(MyJacksonView1.class)
private String withView1;
@JsonView({MyJacksonView1.class, MyJacksonView2.class})
private String withView2;
private String withoutView;
public String getWithView1() {
return withView1;
}
public void setWithView1(String withView1) {
this.withView1 = withView1;
}
public String getWithView2() {
return withView2;
}
public void setWithView2(String withView2) {
this.withView2 = withView2;
}
public String getWithoutView() {
return withoutView;
}
public void setWithoutView(String withoutView) {
this.withoutView = withoutView;
}
}
}
| JacksonViewBean |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/util/jpa/PersistenceUnitInfoPropertiesWrapper.java | {
"start": 684,
"end": 2424
} | class ____ implements PersistenceUnitInfo {
private final Properties properties;
public PersistenceUnitInfoPropertiesWrapper() {
properties = new Properties();
}
public PersistenceUnitInfoPropertiesWrapper(Properties properties) {
this.properties = properties;
}
public String getPersistenceUnitName() {
return "persistenceUnitAdapter";
}
public String getPersistenceProviderClassName() {
return HibernatePersistenceProvider.class.getName();
}
@Override
public String getScopeAnnotationName() {
return null;
}
@Override
public List<String> getQualifierAnnotationNames() {
return List.of();
}
@SuppressWarnings("removal")
public PersistenceUnitTransactionType getTransactionType() {
return null;
}
public DataSource getJtaDataSource() {
return null;
}
public DataSource getNonJtaDataSource() {
return null;
}
public List<String> getMappingFileNames() {
return Collections.emptyList();
}
public List<URL> getJarFileUrls() {
return Collections.emptyList();
}
public URL getPersistenceUnitRootUrl() {
return null;
}
public List<String> getManagedClassNames() {
return Collections.emptyList();
}
public boolean excludeUnlistedClasses() {
return false;
}
public SharedCacheMode getSharedCacheMode() {
return null;
}
public ValidationMode getValidationMode() {
return null;
}
public Properties getProperties() {
return properties;
}
public String getPersistenceXMLSchemaVersion() {
return null;
}
public ClassLoader getClassLoader() {
return currentThread().getContextClassLoader();
}
public void addTransformer(ClassTransformer transformer) {
}
public ClassLoader getNewTempClassLoader() {
return null;
}
}
| PersistenceUnitInfoPropertiesWrapper |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/RegisterNodeManagerResponsePBImpl.java | {
"start": 1825,
"end": 8613
} | class ____
extends RegisterNodeManagerResponse {
private RegisterNodeManagerResponseProto proto =
RegisterNodeManagerResponseProto.getDefaultInstance();
private RegisterNodeManagerResponseProto.Builder builder = null;
private boolean viaProto = false;
private Resource resource = null;
private MasterKey containerTokenMasterKey = null;
private MasterKey nmTokenMasterKey = null;
private boolean rebuild = false;
public RegisterNodeManagerResponsePBImpl() {
builder = RegisterNodeManagerResponseProto.newBuilder();
}
public RegisterNodeManagerResponsePBImpl(RegisterNodeManagerResponseProto proto) {
this.proto = proto;
viaProto = true;
}
public RegisterNodeManagerResponseProto getProto() {
if (rebuild)
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
private void mergeLocalToBuilder() {
if (this.containerTokenMasterKey != null) {
builder.setContainerTokenMasterKey(
convertToProtoFormat(this.containerTokenMasterKey));
}
if (this.nmTokenMasterKey != null) {
builder.setNmTokenMasterKey(
convertToProtoFormat(this.nmTokenMasterKey));
}
if (this.resource != null) {
builder.setResource(convertToProtoFormat(this.resource));
}
}
private void mergeLocalToProto() {
if (viaProto)
maybeInitBuilder();
mergeLocalToBuilder();
proto = builder.build();
rebuild = false;
viaProto = true;
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = RegisterNodeManagerResponseProto.newBuilder(proto);
}
viaProto = false;
}
@Override
public Resource getResource() {
RegisterNodeManagerResponseProtoOrBuilder p = viaProto ? proto : builder;
if (this.resource != null) {
return this.resource;
}
if (!p.hasResource()) {
return null;
}
this.resource = convertFromProtoFormat(p.getResource());
return this.resource;
}
@Override
public void setResource(Resource resource) {
maybeInitBuilder();
if (resource == null) {
builder.clearResource();
}
this.resource = resource;
}
@Override
public MasterKey getContainerTokenMasterKey() {
RegisterNodeManagerResponseProtoOrBuilder p = viaProto ? proto : builder;
if (this.containerTokenMasterKey != null) {
return this.containerTokenMasterKey;
}
if (!p.hasContainerTokenMasterKey()) {
return null;
}
this.containerTokenMasterKey =
convertFromProtoFormat(p.getContainerTokenMasterKey());
return this.containerTokenMasterKey;
}
@Override
public void setContainerTokenMasterKey(MasterKey masterKey) {
maybeInitBuilder();
if (masterKey == null)
builder.clearContainerTokenMasterKey();
this.containerTokenMasterKey = masterKey;
rebuild = true;
}
@Override
public MasterKey getNMTokenMasterKey() {
RegisterNodeManagerResponseProtoOrBuilder p = viaProto ? proto : builder;
if (this.nmTokenMasterKey != null) {
return this.nmTokenMasterKey;
}
if (!p.hasNmTokenMasterKey()) {
return null;
}
this.nmTokenMasterKey =
convertFromProtoFormat(p.getNmTokenMasterKey());
return this.nmTokenMasterKey;
}
@Override
public void setNMTokenMasterKey(MasterKey masterKey) {
maybeInitBuilder();
if (masterKey == null)
builder.clearNmTokenMasterKey();
this.nmTokenMasterKey = masterKey;
rebuild = true;
}
@Override
public String getDiagnosticsMessage() {
RegisterNodeManagerResponseProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasDiagnosticsMessage()) {
return null;
}
return p.getDiagnosticsMessage();
}
@Override
public void setDiagnosticsMessage(String diagnosticsMessage) {
maybeInitBuilder();
if (diagnosticsMessage == null) {
builder.clearDiagnosticsMessage();
return;
}
builder.setDiagnosticsMessage((diagnosticsMessage));
}
@Override
public String getRMVersion() {
RegisterNodeManagerResponseProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasRmVersion()) {
return null;
}
return p.getRmVersion();
}
@Override
public void setRMVersion(String rmVersion) {
maybeInitBuilder();
if (rmVersion == null) {
builder.clearRmIdentifier();
return;
}
builder.setRmVersion(rmVersion);
}
@Override
public NodeAction getNodeAction() {
RegisterNodeManagerResponseProtoOrBuilder p = viaProto ? proto : builder;
if(!p.hasNodeAction()) {
return null;
}
return convertFromProtoFormat(p.getNodeAction());
}
@Override
public void setNodeAction(NodeAction nodeAction) {
maybeInitBuilder();
if (nodeAction == null) {
builder.clearNodeAction();
} else {
builder.setNodeAction(convertToProtoFormat(nodeAction));
}
rebuild = true;
}
@Override
public long getRMIdentifier() {
RegisterNodeManagerResponseProtoOrBuilder p = viaProto ? proto : builder;
return (p.getRmIdentifier());
}
@Override
public void setRMIdentifier(long rmIdentifier) {
maybeInitBuilder();
builder.setRmIdentifier(rmIdentifier);
}
private NodeAction convertFromProtoFormat(NodeActionProto p) {
return NodeAction.valueOf(p.name());
}
private NodeActionProto convertToProtoFormat(NodeAction t) {
return NodeActionProto.valueOf(t.name());
}
private MasterKeyPBImpl convertFromProtoFormat(MasterKeyProto p) {
return new MasterKeyPBImpl(p);
}
private MasterKeyProto convertToProtoFormat(MasterKey t) {
return ((MasterKeyPBImpl)t).getProto();
}
private ResourcePBImpl convertFromProtoFormat(ResourceProto p) {
return new ResourcePBImpl(p);
}
private ResourceProto convertToProtoFormat(Resource t) {
return ProtoUtils.convertToProtoFormat(t);
}
@Override
public boolean getAreNodeLabelsAcceptedByRM() {
RegisterNodeManagerResponseProtoOrBuilder p =
this.viaProto ? this.proto : this.builder;
return p.getAreNodeLabelsAcceptedByRM();
}
@Override
public void setAreNodeLabelsAcceptedByRM(boolean areNodeLabelsAcceptedByRM) {
maybeInitBuilder();
this.builder.setAreNodeLabelsAcceptedByRM(areNodeLabelsAcceptedByRM);
}
@Override
public boolean getAreNodeAttributesAcceptedByRM() {
RegisterNodeManagerResponseProtoOrBuilder p =
this.viaProto ? this.proto : this.builder;
return p.getAreNodeAttributesAcceptedByRM();
}
@Override
public void setAreNodeAttributesAcceptedByRM(
boolean areNodeAttributesAcceptedByRM) {
maybeInitBuilder();
this.builder
.setAreNodeAttributesAcceptedByRM(areNodeAttributesAcceptedByRM);
}
}
| RegisterNodeManagerResponsePBImpl |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/StXMinFromWKBEvaluator.java | {
"start": 1238,
"end": 4697
} | class ____ extends AbstractConvertFunction.AbstractEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(StXMinFromWKBEvaluator.class);
private final EvalOperator.ExpressionEvaluator wkb;
public StXMinFromWKBEvaluator(Source source, EvalOperator.ExpressionEvaluator wkb,
DriverContext driverContext) {
super(driverContext, source);
this.wkb = wkb;
}
@Override
public EvalOperator.ExpressionEvaluator next() {
return wkb;
}
@Override
public Block evalVector(Vector v) {
BytesRefVector vector = (BytesRefVector) v;
int positionCount = v.getPositionCount();
BytesRef scratchPad = new BytesRef();
if (vector.isConstant()) {
try {
return driverContext.blockFactory().newConstantDoubleBlockWith(evalValue(vector, 0, scratchPad), positionCount);
} catch (IllegalArgumentException e) {
registerException(e);
return driverContext.blockFactory().newConstantNullBlock(positionCount);
}
}
try (DoubleBlock.Builder builder = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) {
for (int p = 0; p < positionCount; p++) {
try {
builder.appendDouble(evalValue(vector, p, scratchPad));
} catch (IllegalArgumentException e) {
registerException(e);
builder.appendNull();
}
}
return builder.build();
}
}
private double evalValue(BytesRefVector container, int index, BytesRef scratchPad) {
BytesRef value = container.getBytesRef(index, scratchPad);
return StXMin.fromWellKnownBinary(value);
}
@Override
public Block evalBlock(Block b) {
BytesRefBlock block = (BytesRefBlock) b;
int positionCount = block.getPositionCount();
try (DoubleBlock.Builder builder = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) {
BytesRef scratchPad = new BytesRef();
for (int p = 0; p < positionCount; p++) {
int valueCount = block.getValueCount(p);
int start = block.getFirstValueIndex(p);
int end = start + valueCount;
boolean positionOpened = false;
boolean valuesAppended = false;
for (int i = start; i < end; i++) {
try {
double value = evalValue(block, i, scratchPad);
if (positionOpened == false && valueCount > 1) {
builder.beginPositionEntry();
positionOpened = true;
}
builder.appendDouble(value);
valuesAppended = true;
} catch (IllegalArgumentException e) {
registerException(e);
}
}
if (valuesAppended == false) {
builder.appendNull();
} else if (positionOpened) {
builder.endPositionEntry();
}
}
return builder.build();
}
}
private double evalValue(BytesRefBlock container, int index, BytesRef scratchPad) {
BytesRef value = container.getBytesRef(index, scratchPad);
return StXMin.fromWellKnownBinary(value);
}
@Override
public String toString() {
return "StXMinFromWKBEvaluator[" + "wkb=" + wkb + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(wkb);
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += wkb.baseRamBytesUsed();
return baseRamBytesUsed;
}
public static | StXMinFromWKBEvaluator |
java | apache__camel | components/camel-google/camel-google-calendar/src/generated/java/org/apache/camel/component/google/calendar/GoogleCalendarEndpointConfigurer.java | {
"start": 742,
"end": 15068
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("ApiName", org.apache.camel.component.google.calendar.internal.GoogleCalendarApiName.class);
map.put("MethodName", java.lang.String.class);
map.put("ApplicationName", java.lang.String.class);
map.put("ClientId", java.lang.String.class);
map.put("Delegate", java.lang.String.class);
map.put("InBody", java.lang.String.class);
map.put("Scopes", java.lang.String.class);
map.put("SendEmptyMessageWhenIdle", boolean.class);
map.put("BridgeErrorHandler", boolean.class);
map.put("ExceptionHandler", org.apache.camel.spi.ExceptionHandler.class);
map.put("ExchangePattern", org.apache.camel.ExchangePattern.class);
map.put("PollStrategy", org.apache.camel.spi.PollingConsumerPollStrategy.class);
map.put("LazyStartProducer", boolean.class);
map.put("BackoffErrorThreshold", int.class);
map.put("BackoffIdleThreshold", int.class);
map.put("BackoffMultiplier", int.class);
map.put("Delay", long.class);
map.put("Greedy", boolean.class);
map.put("InitialDelay", long.class);
map.put("RepeatCount", long.class);
map.put("RunLoggingLevel", org.apache.camel.LoggingLevel.class);
map.put("ScheduledExecutorService", java.util.concurrent.ScheduledExecutorService.class);
map.put("Scheduler", java.lang.Object.class);
map.put("SchedulerProperties", java.util.Map.class);
map.put("StartScheduler", boolean.class);
map.put("TimeUnit", java.util.concurrent.TimeUnit.class);
map.put("UseFixedDelay", boolean.class);
map.put("AccessToken", java.lang.String.class);
map.put("ClientSecret", java.lang.String.class);
map.put("EmailAddress", java.lang.String.class);
map.put("P12FileName", java.lang.String.class);
map.put("RefreshToken", java.lang.String.class);
map.put("ServiceAccountKey", java.lang.String.class);
map.put("User", java.lang.String.class);
ALL_OPTIONS = map;
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
GoogleCalendarEndpoint target = (GoogleCalendarEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": target.getConfiguration().setAccessToken(property(camelContext, java.lang.String.class, value)); return true;
case "applicationname":
case "applicationName": target.getConfiguration().setApplicationName(property(camelContext, java.lang.String.class, value)); return true;
case "backofferrorthreshold":
case "backoffErrorThreshold": target.setBackoffErrorThreshold(property(camelContext, int.class, value)); return true;
case "backoffidlethreshold":
case "backoffIdleThreshold": target.setBackoffIdleThreshold(property(camelContext, int.class, value)); return true;
case "backoffmultiplier":
case "backoffMultiplier": target.setBackoffMultiplier(property(camelContext, int.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "clientid":
case "clientId": target.getConfiguration().setClientId(property(camelContext, java.lang.String.class, value)); return true;
case "clientsecret":
case "clientSecret": target.getConfiguration().setClientSecret(property(camelContext, java.lang.String.class, value)); return true;
case "delay": target.setDelay(property(camelContext, long.class, value)); return true;
case "delegate": target.getConfiguration().setDelegate(property(camelContext, java.lang.String.class, value)); return true;
case "emailaddress":
case "emailAddress": target.getConfiguration().setEmailAddress(property(camelContext, java.lang.String.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "greedy": target.setGreedy(property(camelContext, boolean.class, value)); return true;
case "inbody":
case "inBody": target.setInBody(property(camelContext, java.lang.String.class, value)); return true;
case "initialdelay":
case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "p12filename":
case "p12FileName": target.getConfiguration().setP12FileName(property(camelContext, java.lang.String.class, value)); return true;
case "pollstrategy":
case "pollStrategy": target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value)); return true;
case "refreshtoken":
case "refreshToken": target.getConfiguration().setRefreshToken(property(camelContext, java.lang.String.class, value)); return true;
case "repeatcount":
case "repeatCount": target.setRepeatCount(property(camelContext, long.class, value)); return true;
case "runlogginglevel":
case "runLoggingLevel": target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value)); return true;
case "scheduledexecutorservice":
case "scheduledExecutorService": target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value)); return true;
case "scheduler": target.setScheduler(property(camelContext, java.lang.Object.class, value)); return true;
case "schedulerproperties":
case "schedulerProperties": target.setSchedulerProperties(property(camelContext, java.util.Map.class, value)); return true;
case "scopes": target.getConfiguration().setScopes(property(camelContext, java.lang.String.class, value)); return true;
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value)); return true;
case "serviceaccountkey":
case "serviceAccountKey": target.getConfiguration().setServiceAccountKey(property(camelContext, java.lang.String.class, value)); return true;
case "startscheduler":
case "startScheduler": target.setStartScheduler(property(camelContext, boolean.class, value)); return true;
case "timeunit":
case "timeUnit": target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true;
case "usefixeddelay":
case "useFixedDelay": target.setUseFixedDelay(property(camelContext, boolean.class, value)); return true;
case "user": target.getConfiguration().setUser(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": return java.lang.String.class;
case "applicationname":
case "applicationName": return java.lang.String.class;
case "backofferrorthreshold":
case "backoffErrorThreshold": return int.class;
case "backoffidlethreshold":
case "backoffIdleThreshold": return int.class;
case "backoffmultiplier":
case "backoffMultiplier": return int.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "clientid":
case "clientId": return java.lang.String.class;
case "clientsecret":
case "clientSecret": return java.lang.String.class;
case "delay": return long.class;
case "delegate": return java.lang.String.class;
case "emailaddress":
case "emailAddress": return java.lang.String.class;
case "exceptionhandler":
case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class;
case "exchangepattern":
case "exchangePattern": return org.apache.camel.ExchangePattern.class;
case "greedy": return boolean.class;
case "inbody":
case "inBody": return java.lang.String.class;
case "initialdelay":
case "initialDelay": return long.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "p12filename":
case "p12FileName": return java.lang.String.class;
case "pollstrategy":
case "pollStrategy": return org.apache.camel.spi.PollingConsumerPollStrategy.class;
case "refreshtoken":
case "refreshToken": return java.lang.String.class;
case "repeatcount":
case "repeatCount": return long.class;
case "runlogginglevel":
case "runLoggingLevel": return org.apache.camel.LoggingLevel.class;
case "scheduledexecutorservice":
case "scheduledExecutorService": return java.util.concurrent.ScheduledExecutorService.class;
case "scheduler": return java.lang.Object.class;
case "schedulerproperties":
case "schedulerProperties": return java.util.Map.class;
case "scopes": return java.lang.String.class;
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": return boolean.class;
case "serviceaccountkey":
case "serviceAccountKey": return java.lang.String.class;
case "startscheduler":
case "startScheduler": return boolean.class;
case "timeunit":
case "timeUnit": return java.util.concurrent.TimeUnit.class;
case "usefixeddelay":
case "useFixedDelay": return boolean.class;
case "user": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
GoogleCalendarEndpoint target = (GoogleCalendarEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": return target.getConfiguration().getAccessToken();
case "applicationname":
case "applicationName": return target.getConfiguration().getApplicationName();
case "backofferrorthreshold":
case "backoffErrorThreshold": return target.getBackoffErrorThreshold();
case "backoffidlethreshold":
case "backoffIdleThreshold": return target.getBackoffIdleThreshold();
case "backoffmultiplier":
case "backoffMultiplier": return target.getBackoffMultiplier();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "clientid":
case "clientId": return target.getConfiguration().getClientId();
case "clientsecret":
case "clientSecret": return target.getConfiguration().getClientSecret();
case "delay": return target.getDelay();
case "delegate": return target.getConfiguration().getDelegate();
case "emailaddress":
case "emailAddress": return target.getConfiguration().getEmailAddress();
case "exceptionhandler":
case "exceptionHandler": return target.getExceptionHandler();
case "exchangepattern":
case "exchangePattern": return target.getExchangePattern();
case "greedy": return target.isGreedy();
case "inbody":
case "inBody": return target.getInBody();
case "initialdelay":
case "initialDelay": return target.getInitialDelay();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "p12filename":
case "p12FileName": return target.getConfiguration().getP12FileName();
case "pollstrategy":
case "pollStrategy": return target.getPollStrategy();
case "refreshtoken":
case "refreshToken": return target.getConfiguration().getRefreshToken();
case "repeatcount":
case "repeatCount": return target.getRepeatCount();
case "runlogginglevel":
case "runLoggingLevel": return target.getRunLoggingLevel();
case "scheduledexecutorservice":
case "scheduledExecutorService": return target.getScheduledExecutorService();
case "scheduler": return target.getScheduler();
case "schedulerproperties":
case "schedulerProperties": return target.getSchedulerProperties();
case "scopes": return target.getConfiguration().getScopes();
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": return target.isSendEmptyMessageWhenIdle();
case "serviceaccountkey":
case "serviceAccountKey": return target.getConfiguration().getServiceAccountKey();
case "startscheduler":
case "startScheduler": return target.isStartScheduler();
case "timeunit":
case "timeUnit": return target.getTimeUnit();
case "usefixeddelay":
case "useFixedDelay": return target.isUseFixedDelay();
case "user": return target.getConfiguration().getUser();
default: return null;
}
}
@Override
public Object getCollectionValueType(Object target, String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "schedulerproperties":
case "schedulerProperties": return java.lang.Object.class;
default: return null;
}
}
}
| GoogleCalendarEndpointConfigurer |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/matchers/VarargsTest.java | {
"start": 17128,
"end": 17417
} | class ____ implements BaseType {
@Override
public boolean equals(final Object obj) {
return obj != null && obj.getClass().equals(getClass());
}
@Override
public int hashCode() {
return super.hashCode();
}
}
}
| SubType |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/resolver/RouterGenericManager.java | {
"start": 952,
"end": 1236
} | interface ____ {
/**
* Refresh superuser proxy groups mappings (used in RBF).
* @return true if the operation was successful.
* @throws IOException if operation was not successful.
*/
boolean refreshSuperUserGroupsConfiguration() throws IOException;
}
| RouterGenericManager |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sort/MultiInputSortingDataInput.java | {
"start": 4232,
"end": 5757
} | class ____<IN, K> implements StreamTaskInput<IN> {
private final int idx;
private final StreamTaskInput<IN> wrappedInput;
private final PushSorter<Tuple2<byte[], StreamRecord<IN>>> sorter;
private final CommonContext commonContext;
private final SortingPhaseDataOutput sortingPhaseDataOutput = new SortingPhaseDataOutput();
private final KeySelector<IN, K> keySelector;
private final TypeSerializer<K> keySerializer;
private final DataOutputSerializer dataOutputSerializer;
private MutableObjectIterator<Tuple2<byte[], StreamRecord<IN>>> sortedInput;
private long seenWatermark = Long.MIN_VALUE;
private MultiInputSortingDataInput(
CommonContext commonContext,
StreamTaskInput<IN> wrappedInput,
int inputIdx,
PushSorter<Tuple2<byte[], StreamRecord<IN>>> sorter,
KeySelector<IN, K> keySelector,
TypeSerializer<K> keySerializer,
DataOutputSerializer dataOutputSerializer) {
this.wrappedInput = wrappedInput;
this.idx = inputIdx;
this.commonContext = commonContext;
this.sorter = sorter;
this.keySelector = keySelector;
this.keySerializer = keySerializer;
this.dataOutputSerializer = dataOutputSerializer;
}
/**
* A wrapper that combines sorting {@link StreamTaskInput inputs} with a {@link InputSelectable}
* that should be used to choose which input to consume next from.
*/
public static | MultiInputSortingDataInput |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/ioc/introspection/JavaxTransientTest.java | {
"start": 191,
"end": 487
} | class ____ {
@Test
void testIntrospectionWithJavaxTransient() {
BeanIntrospection<ObjectWithJavaxTransient> introspection = BeanIntrospection.getIntrospection(ObjectWithJavaxTransient.class);
assertTrue(introspection.getProperty("tmp").isPresent());
}
}
| JavaxTransientTest |
java | apache__flink | flink-connectors/flink-file-sink-common/src/main/java/org/apache/flink/streaming/api/functions/sink/filesystem/OutputStreamBasedPartFileWriter.java | {
"start": 3965,
"end": 8734
} | class ____<IN, BucketID>
implements BucketWriter<IN, BucketID> {
private final RecoverableWriter recoverableWriter;
OutputStreamBasedBucketWriter(final RecoverableWriter recoverableWriter) {
this.recoverableWriter = recoverableWriter;
}
@Override
public InProgressFileWriter<IN, BucketID> openNewInProgressFile(
final BucketID bucketID, final Path path, final long creationTime)
throws IOException {
return openNew(bucketID, recoverableWriter.open(path), path, creationTime);
}
@Override
public CompactingFileWriter openNewCompactingFile(
CompactingFileWriter.Type type, BucketID bucketID, Path path, long creationTime)
throws IOException {
// Both types are supported, overwrite to avoid UnsupportedOperationException.
return openNewInProgressFile(bucketID, path, creationTime);
}
@Override
public InProgressFileWriter<IN, BucketID> resumeInProgressFileFrom(
final BucketID bucketID,
final InProgressFileRecoverable inProgressFileRecoverable,
final long creationTime)
throws IOException {
final OutputStreamBasedInProgressFileRecoverable
outputStreamBasedInProgressRecoverable =
(OutputStreamBasedInProgressFileRecoverable) inProgressFileRecoverable;
return resumeFrom(
bucketID,
recoverableWriter.recover(
outputStreamBasedInProgressRecoverable.getResumeRecoverable()),
inProgressFileRecoverable.getPath(),
outputStreamBasedInProgressRecoverable.getResumeRecoverable(),
creationTime);
}
@Override
public PendingFile recoverPendingFile(final PendingFileRecoverable pendingFileRecoverable)
throws IOException {
final RecoverableWriter.CommitRecoverable commitRecoverable;
if (pendingFileRecoverable instanceof OutputStreamBasedPendingFileRecoverable) {
commitRecoverable =
((OutputStreamBasedPendingFileRecoverable) pendingFileRecoverable)
.getCommitRecoverable();
} else if (pendingFileRecoverable
instanceof OutputStreamBasedInProgressFileRecoverable) {
commitRecoverable =
((OutputStreamBasedInProgressFileRecoverable) pendingFileRecoverable)
.getResumeRecoverable();
} else {
throw new IllegalArgumentException(
"can not recover from the pendingFileRecoverable");
}
return new OutputStreamBasedPendingFile(
recoverableWriter.recoverForCommit(commitRecoverable));
}
@Override
public boolean cleanupInProgressFileRecoverable(
InProgressFileRecoverable inProgressFileRecoverable) throws IOException {
final RecoverableWriter.ResumeRecoverable resumeRecoverable =
((OutputStreamBasedInProgressFileRecoverable) inProgressFileRecoverable)
.getResumeRecoverable();
return recoverableWriter.cleanupRecoverableState(resumeRecoverable);
}
@Override
public WriterProperties getProperties() {
return new WriterProperties(
new OutputStreamBasedInProgressFileRecoverableSerializer(
recoverableWriter.getResumeRecoverableSerializer()),
new OutputStreamBasedPendingFileRecoverableSerializer(
recoverableWriter.getCommitRecoverableSerializer()),
recoverableWriter.supportsResume());
}
public abstract InProgressFileWriter<IN, BucketID> openNew(
final BucketID bucketId,
final RecoverableFsDataOutputStream stream,
final Path path,
final long creationTime)
throws IOException;
public abstract InProgressFileWriter<IN, BucketID> resumeFrom(
final BucketID bucketId,
final RecoverableFsDataOutputStream stream,
final Path path,
final RecoverableWriter.ResumeRecoverable resumable,
final long creationTime)
throws IOException;
}
/**
* The {@link PendingFileRecoverable} implementation for {@link OutputStreamBasedBucketWriter}.
*/
public static final | OutputStreamBasedBucketWriter |
java | apache__kafka | connect/runtime/src/main/java/org/apache/kafka/connect/util/TopicAdmin.java | {
"start": 5371,
"end": 38859
} | class ____ {
private final String name;
private int numPartitions = NO_PARTITIONS;
private short replicationFactor = NO_REPLICATION_FACTOR;
private final Map<String, String> configs = new HashMap<>();
NewTopicBuilder(String name) {
this.name = name;
}
/**
* Specify the desired number of partitions for the topic.
*
* @param numPartitions the desired number of partitions; must be positive, or -1 to
* signify using the broker's default
* @return this builder to allow methods to be chained; never null
*/
public NewTopicBuilder partitions(int numPartitions) {
this.numPartitions = numPartitions;
return this;
}
/**
* Specify the topic's number of partition should be the broker configuration for
* {@code num.partitions}.
*
* @return this builder to allow methods to be chained; never null
*/
public NewTopicBuilder defaultPartitions() {
this.numPartitions = NO_PARTITIONS;
return this;
}
/**
* Specify the desired replication factor for the topic.
*
* @param replicationFactor the desired replication factor; must be positive, or -1 to
* signify using the broker's default
* @return this builder to allow methods to be chained; never null
*/
public NewTopicBuilder replicationFactor(short replicationFactor) {
this.replicationFactor = replicationFactor;
return this;
}
/**
* Specify the replication factor for the topic should be the broker configurations for
* {@code default.replication.factor}.
*
* @return this builder to allow methods to be chained; never null
*/
public NewTopicBuilder defaultReplicationFactor() {
this.replicationFactor = NO_REPLICATION_FACTOR;
return this;
}
/**
* Specify that the topic should be compacted.
*
* @return this builder to allow methods to be chained; never null
*/
public NewTopicBuilder compacted() {
this.configs.put(CLEANUP_POLICY_CONFIG, CLEANUP_POLICY_COMPACT);
return this;
}
/**
* Specify the configuration properties for the topic, overwriting any previously-set properties.
*
* @param configs the desired topic configuration properties, or null if all existing properties should be cleared
* @return this builder to allow methods to be chained; never null
*/
public NewTopicBuilder config(Map<String, Object> configs) {
if (configs != null) {
for (Map.Entry<String, Object> entry : configs.entrySet()) {
Object value = entry.getValue();
this.configs.put(entry.getKey(), value != null ? value.toString() : null);
}
} else {
this.configs.clear();
}
return this;
}
/**
* Build the {@link NewTopic} representation.
*
* @return the topic description; never null
*/
public NewTopic build() {
return new NewTopic(
name,
Optional.of(numPartitions),
Optional.of(replicationFactor)
).configs(configs);
}
}
/**
* Obtain a {@link NewTopicBuilder builder} to define a {@link NewTopic}.
*
* @param topicName the name of the topic
* @return the {@link NewTopic} description of the topic; never null
*/
public static NewTopicBuilder defineTopic(String topicName) {
return new NewTopicBuilder(topicName);
}
private static final Logger log = LoggerFactory.getLogger(TopicAdmin.class);
private final String bootstrapServers;
private final Admin admin;
private final boolean logCreation;
/**
* Create a new topic admin component with the given configuration.
* <p>
* Note that this will create an underlying {@link Admin} instance which must be freed when this
* topic admin is no longer needed by calling {@link #close()} or {@link #close(Duration)}.
*
* @param adminConfig the configuration for the {@link Admin}
*/
public TopicAdmin(Map<String, Object> adminConfig) {
this(adminConfig, Admin.create(adminConfig));
}
public TopicAdmin(Map<String, Object> adminConfig, Admin adminClient) {
this(bootstrapServers(adminConfig), adminClient, true);
}
// visible for testing
TopicAdmin(Admin adminClient) {
this(null, adminClient, true);
}
// visible for testing
TopicAdmin(String bootstrapServers, Admin adminClient, boolean logCreation) {
this.admin = adminClient;
this.bootstrapServers = bootstrapServers != null ? bootstrapServers : "<unknown>";
this.logCreation = logCreation;
}
private static String bootstrapServers(Map<String, Object> adminConfig) {
Object result = adminConfig.get(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG);
return result != null ? result.toString() : null;
}
/**
* Attempt to create the topic described by the given definition, returning true if the topic was created or false
* if the topic already existed.
*
* @param topic the specification of the topic
* @return true if the topic was created or false if the topic already existed.
* @throws ConnectException if an error occurs, the operation takes too long, or the thread is interrupted while
* attempting to perform this operation
* @throws UnsupportedVersionException if the broker does not support the necessary APIs to perform this request
*/
public boolean createTopic(NewTopic topic) {
if (topic == null) return false;
Set<String> newTopicNames = createTopics(topic);
return newTopicNames.contains(topic.name());
}
/**
* Attempt to create the topics described by the given definitions, returning all of the names of those topics that
* were created by this request. Any existing topics with the same name are unchanged, and the names of such topics
* are excluded from the result.
* <p>
* If multiple topic definitions have the same topic name, the last one with that name will be used.
* <p>
* Apache Kafka added support for creating topics in 0.10.1.0, so this method works as expected with that and later versions.
* With brokers older than 0.10.1.0, this method is unable to create topics and always returns an empty set.
*
* @param topics the specifications of the topics
* @return the names of the topics that were created by this operation; never null but possibly empty
* @throws ConnectException if an error occurs, the operation takes too long, or the thread is interrupted while
* attempting to perform this operation
*/
public Set<String> createTopics(NewTopic... topics) {
return createOrFindTopics(topics).createdTopics();
}
/**
* Implements a retry logic around creating topic(s) in case it'd fail due to
* specific type of exceptions, see {@link TopicAdmin#retryableTopicCreationException(ConnectException)}
*
* @param topicDescription the specifications of the topic
* @param timeoutMs Timeout in milliseconds
* @param backOffMs Time for delay after initial failed attempt in milliseconds
* @param time {@link Time} instance
* @return the names of the topics that were created by this operation; never null but possibly empty,
* the same as {@link TopicAdmin#createTopics(NewTopic...)}
*/
public Set<String> createTopicsWithRetry(NewTopic topicDescription, long timeoutMs, long backOffMs, Time time) {
Timer timer = time.timer(timeoutMs);
do {
try {
return createTopics(topicDescription);
} catch (ConnectException e) {
if (timer.notExpired() && retryableTopicCreationException(e)) {
log.info("'{}' topic creation failed due to '{}', retrying, {}ms remaining",
topicDescription.name(), e.getMessage(), timer.remainingMs());
} else {
throw e;
}
}
timer.sleep(backOffMs);
} while (timer.notExpired());
throw new TimeoutException("Timeout expired while trying to create topic(s)");
}
private boolean retryableTopicCreationException(ConnectException e) {
// createTopics wraps the exception into ConnectException
// to retry the creation, it should be an ExecutionException from future get which was caused by InvalidReplicationFactorException
// or can be a TimeoutException
Throwable cause = e.getCause();
while (cause != null) {
final Throwable finalCause = cause;
if (CAUSES_TO_RETRY_TOPIC_CREATION.stream().anyMatch(exceptionClass -> exceptionClass.isInstance(finalCause))) {
return true;
}
cause = cause.getCause();
}
return false;
}
/**
* Attempt to find or create the topic described by the given definition, returning true if the topic was created or had
* already existed, or false if the topic did not exist and could not be created.
*
* @param topic the specification of the topic
* @return true if the topic was created or existed, or false if the topic could not already existed.
* @throws ConnectException if an error occurs, the operation takes too long, or the thread is interrupted while
* attempting to perform this operation
* @throws UnsupportedVersionException if the broker does not support the necessary APIs to perform this request
*/
public boolean createOrFindTopic(NewTopic topic) {
if (topic == null) return false;
return createOrFindTopics(topic).isCreatedOrExisting(topic.name());
}
/**
* Attempt to create the topics described by the given definitions, returning all of the names of those topics that
* were created by this request. Any existing topics with the same name are unchanged, and the names of such topics
* are excluded from the result.
* <p>
* If multiple topic definitions have the same topic name, the last one with that name will be used.
* <p>
* Apache Kafka added support for creating topics in 0.10.1.0, so this method works as expected with that and later versions.
* With brokers older than 0.10.1.0, this method is unable to create topics and always returns an empty set.
*
* @param topics the specifications of the topics
* @return the {@link TopicCreationResponse} with the names of the newly created and existing topics;
* never null but possibly empty
* @throws ConnectException if an error occurs, the operation takes too long, or the thread is interrupted while
* attempting to perform this operation
*/
public TopicCreationResponse createOrFindTopics(NewTopic... topics) {
Map<String, NewTopic> topicsByName = new HashMap<>();
if (topics != null) {
for (NewTopic topic : topics) {
if (topic != null) topicsByName.put(topic.name(), topic);
}
}
if (topicsByName.isEmpty()) return EMPTY_CREATION;
String topicNameList = String.join("', '", topicsByName.keySet());
// Attempt to create any missing topics
CreateTopicsOptions args = new CreateTopicsOptions().validateOnly(false);
Map<String, KafkaFuture<Void>> newResults = admin.createTopics(topicsByName.values(), args).values();
// Iterate over each future so that we can handle individual failures like when some topics already exist
Set<String> newlyCreatedTopicNames = new HashSet<>();
Set<String> existingTopicNames = new HashSet<>();
for (Map.Entry<String, KafkaFuture<Void>> entry : newResults.entrySet()) {
String topic = entry.getKey();
try {
entry.getValue().get();
if (logCreation) {
log.info("Created topic {} on brokers at {}", topicsByName.get(topic), bootstrapServers);
}
newlyCreatedTopicNames.add(topic);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof TopicExistsException) {
log.debug("Found existing topic '{}' on the brokers at {}", topic, bootstrapServers);
existingTopicNames.add(topic);
continue;
}
if (cause instanceof UnsupportedVersionException) {
log.debug("Unable to create topic(s) '{}' since the brokers at {} do not support the CreateTopics API." +
" Falling back to assume topic(s) exist or will be auto-created by the broker.",
topicNameList, bootstrapServers);
return EMPTY_CREATION;
}
if (cause instanceof ClusterAuthorizationException) {
log.debug("Not authorized to create topic(s) '{}' upon the brokers {}." +
" Falling back to assume topic(s) exist or will be auto-created by the broker.",
topicNameList, bootstrapServers);
return EMPTY_CREATION;
}
if (cause instanceof TopicAuthorizationException) {
log.debug("Not authorized to create topic(s) '{}' upon the brokers {}." +
" Falling back to assume topic(s) exist or will be auto-created by the broker.",
topicNameList, bootstrapServers);
return EMPTY_CREATION;
}
if (cause instanceof InvalidConfigurationException) {
throw new ConnectException("Unable to create topic(s) '" + topicNameList + "': " + cause.getMessage(),
cause);
}
if (cause instanceof TimeoutException) {
// Timed out waiting for the operation to complete
throw new ConnectException("Timed out while checking for or creating topic(s) '" + topicNameList + "'." +
" This could indicate a connectivity issue, unavailable topic partitions, or if" +
" this is your first use of the topic it may have taken too long to create.", cause);
}
throw new ConnectException("Error while attempting to create/find topic(s) '" + topicNameList + "'", e);
} catch (InterruptedException e) {
Thread.interrupted();
throw new ConnectException("Interrupted while attempting to create/find topic(s) '" + topicNameList + "'", e);
}
}
return new TopicCreationResponse(newlyCreatedTopicNames, existingTopicNames);
}
/**
* Attempt to fetch the descriptions of the given topics
* Apache Kafka added support for describing topics in 0.10.0.0, so this method works as expected with that and later versions.
* With brokers older than 0.10.0.0, this method is unable to describe topics and always returns an empty set.
*
* @param topics the topics to describe
* @return a map of topic names to topic descriptions of the topics that were requested; never null but possibly empty
* @throws RetriableException if a retriable error occurs, the operation takes too long, or the
* thread is interrupted while attempting to perform this operation
* @throws ConnectException if a non retriable error occurs
*/
public Map<String, TopicDescription> describeTopics(String... topics) {
if (topics == null) {
return Map.of();
}
String topicNameList = String.join(", ", topics);
Map<String, KafkaFuture<TopicDescription>> newResults =
admin.describeTopics(List.of(topics), new DescribeTopicsOptions()).topicNameValues();
// Iterate over each future so that we can handle individual failures like when some topics don't exist
Map<String, TopicDescription> existingTopics = new HashMap<>();
newResults.forEach((topic, desc) -> {
try {
existingTopics.put(topic, desc.get());
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof UnknownTopicOrPartitionException) {
log.debug("Topic '{}' does not exist on the brokers at {}", topic, bootstrapServers);
return;
}
if (cause instanceof ClusterAuthorizationException || cause instanceof TopicAuthorizationException) {
String msg = String.format("Not authorized to describe topic(s) '%s' on the brokers %s",
topicNameList, bootstrapServers);
throw new ConnectException(msg, cause);
}
if (cause instanceof UnsupportedVersionException) {
String msg = String.format("Unable to describe topic(s) '%s' since the brokers "
+ "at %s do not support the DescribeTopics API.",
topicNameList, bootstrapServers);
throw new ConnectException(msg, cause);
}
if (cause instanceof TimeoutException) {
// Timed out waiting for the operation to complete
throw new RetriableException("Timed out while describing topics '" + topicNameList + "'", cause);
}
throw new ConnectException("Error while attempting to describe topics '" + topicNameList + "'", e);
} catch (InterruptedException e) {
Thread.interrupted();
throw new RetriableException("Interrupted while attempting to describe topics '" + topicNameList + "'", e);
}
});
return existingTopics;
}
/**
* Verify the named topic uses only compaction for the cleanup policy.
*
* @param topic the name of the topic
* @param workerTopicConfig the name of the worker configuration that specifies the topic name
* @return true if the admin client could be used to verify the topic setting, or false if
* the verification could not be performed, likely because the admin client principal
* did not have the required permissions or because the broker was older than 0.11.0.0
* @throws ConfigException if the actual topic setting did not match the required setting
*/
public boolean verifyTopicCleanupPolicyOnlyCompact(String topic, String workerTopicConfig,
String topicPurpose) {
Set<String> cleanupPolicies = topicCleanupPolicy(topic);
if (cleanupPolicies.isEmpty()) {
log.info("Unable to use admin client to verify the cleanup policy of '{}' "
+ "topic is '{}', either because the broker is an older "
+ "version or because the Kafka principal used for Connect "
+ "internal topics does not have the required permission to "
+ "describe topic configurations.", topic, TopicConfig.CLEANUP_POLICY_COMPACT);
return false;
}
Set<String> expectedPolicies = Set.of(TopicConfig.CLEANUP_POLICY_COMPACT);
if (!cleanupPolicies.equals(expectedPolicies)) {
String expectedPolicyStr = String.join(",", expectedPolicies);
String cleanupPolicyStr = String.join(",", cleanupPolicies);
String msg = String.format("Topic '%s' supplied via the '%s' property is required "
+ "to have '%s=%s' to guarantee consistency and durability of "
+ "%s, but found the topic currently has '%s=%s'. Continuing would likely "
+ "result in eventually losing %s and problems restarting this Connect "
+ "cluster in the future. Change the '%s' property in the "
+ "Connect worker configurations to use a topic with '%s=%s'.",
topic, workerTopicConfig, TopicConfig.CLEANUP_POLICY_CONFIG, expectedPolicyStr,
topicPurpose, TopicConfig.CLEANUP_POLICY_CONFIG, cleanupPolicyStr, topicPurpose,
workerTopicConfig, TopicConfig.CLEANUP_POLICY_CONFIG, expectedPolicyStr);
throw new ConfigException(msg);
}
return true;
}
/**
* Get the cleanup policy for a topic.
*
* @param topic the name of the topic
* @return the set of cleanup policies set for the topic; may be empty if the topic does not
* exist or the topic's cleanup policy could not be retrieved
*/
public Set<String> topicCleanupPolicy(String topic) {
Config topicConfig = describeTopicConfig(topic);
if (topicConfig == null) {
// The topic must not exist
log.debug("Unable to find topic '{}' when getting cleanup policy", topic);
return Set.of();
}
ConfigEntry entry = topicConfig.get(CLEANUP_POLICY_CONFIG);
if (entry != null && entry.value() != null) {
String policyStr = entry.value();
log.debug("Found cleanup.policy={} for topic '{}'", policyStr, topic);
return Arrays.stream(policyStr.split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(String::toLowerCase)
.collect(Collectors.toSet());
}
// This is unexpected, as the topic config should include the cleanup.policy even if
// the topic settings don't override the broker's log.cleanup.policy. But just to be safe.
log.debug("Found no cleanup.policy for topic '{}'", topic);
return Set.of();
}
/**
* Attempt to fetch the topic configuration for the given topic.
* Apache Kafka added support for describing topic configurations in 0.11.0.0, so this method
* works as expected with that and later versions. With brokers older than 0.11.0.0, this method
* is unable get the topic configurations and always returns a null value.
*
* <p>If the topic does not exist, a null value is returned.
*
* @param topic the name of the topic for which the topic configuration should be obtained
* @return the topic configuration if the topic exists, or null if the topic did not exist
* @throws RetriableException if a retriable error occurs, the operation takes too long, or the
* thread is interrupted while attempting to perform this operation
* @throws ConnectException if a non retriable error occurs
*/
public Config describeTopicConfig(String topic) {
return describeTopicConfigs(topic).get(topic);
}
/**
* Attempt to fetch the topic configurations for the given topics.
* Apache Kafka added support for describing topic configurations in 0.11.0.0, so this method
* works as expected with that and later versions. With brokers older than 0.11.0.0, this method
* is unable get the topic configurations and always returns an empty set.
*
* <p>An entry with a null Config is placed into the resulting map for any topic that does
* not exist on the brokers.
*
* @param topicNames the topics to obtain configurations
* @return the map of topic configurations for each existing topic, or an empty map if none
* of the topics exist
* @throws RetriableException if a retriable error occurs, the operation takes too long, or the
* thread is interrupted while attempting to perform this operation
* @throws ConnectException if a non retriable error occurs
*/
public Map<String, Config> describeTopicConfigs(String... topicNames) {
if (topicNames == null) {
return Map.of();
}
Collection<String> topics = Arrays.stream(topicNames)
.filter(Objects::nonNull)
.map(String::trim)
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
if (topics.isEmpty()) {
return Map.of();
}
String topicNameList = String.join(", ", topics);
Collection<ConfigResource> resources = topics.stream()
.map(t -> new ConfigResource(ConfigResource.Type.TOPIC, t))
.collect(Collectors.toList());
Map<ConfigResource, KafkaFuture<Config>> newResults = admin.describeConfigs(resources, new DescribeConfigsOptions()).values();
// Iterate over each future so that we can handle individual failures like when some topics don't exist
Map<String, Config> result = new HashMap<>();
newResults.forEach((resource, configs) -> {
String topic = resource.name();
try {
result.put(topic, configs.get());
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof UnknownTopicOrPartitionException) {
log.debug("Topic '{}' does not exist on the brokers at {}", topic, bootstrapServers);
result.put(topic, null);
} else if (cause instanceof ClusterAuthorizationException || cause instanceof TopicAuthorizationException) {
log.debug("Not authorized to describe topic config for topic '{}' on brokers at {}", topic, bootstrapServers);
} else if (cause instanceof UnsupportedVersionException) {
log.debug("API to describe topic config for topic '{}' is unsupported on brokers at {}", topic, bootstrapServers);
} else if (cause instanceof TimeoutException) {
String msg = String.format("Timed out while waiting to describe topic config for topic '%s' on brokers at %s",
topic, bootstrapServers);
throw new RetriableException(msg, e);
} else {
String msg = String.format("Error while attempting to describe topic config for topic '%s' on brokers at %s",
topic, bootstrapServers);
throw new ConnectException(msg, e);
}
} catch (InterruptedException e) {
Thread.interrupted();
String msg = String.format("Interrupted while attempting to describe topic configs '%s'", topicNameList);
throw new RetriableException(msg, e);
}
});
return result;
}
/**
* Fetch the most recent offset for each of the supplied {@link TopicPartition} objects.
*
* @param partitions the topic partitions
* @return the map of offset for each topic partition, or an empty map if the supplied partitions
* are null or empty
* @throws UnsupportedVersionException if the admin client cannot read end offsets
* @throws TimeoutException if the offset metadata could not be fetched before the amount of time allocated
* by {@code request.timeout.ms} expires, and this call can be retried
* @throws LeaderNotAvailableException if the leader was not available and this call can be retried
* @throws RetriableException if a retriable error occurs, or the thread is interrupted while attempting
* to perform this operation
* @throws ConnectException if a non retriable error occurs
*/
public Map<TopicPartition, Long> endOffsets(Set<TopicPartition> partitions) {
if (partitions == null || partitions.isEmpty()) {
return Map.of();
}
Map<TopicPartition, OffsetSpec> offsetSpecMap = partitions.stream().collect(Collectors.toMap(Function.identity(), tp -> OffsetSpec.latest()));
ListOffsetsResult resultFuture = admin.listOffsets(offsetSpecMap, new ListOffsetsOptions(IsolationLevel.READ_UNCOMMITTED));
// Get the individual result for each topic partition so we have better error messages
Map<TopicPartition, Long> result = new HashMap<>();
for (TopicPartition partition : partitions) {
try {
ListOffsetsResultInfo info = resultFuture.partitionResult(partition).get();
result.put(partition, info.offset());
} catch (ExecutionException e) {
Throwable cause = e.getCause();
String topic = partition.topic();
if (cause instanceof AuthorizationException) {
String msg = String.format("Not authorized to get the end offsets for topic '%s' on brokers at %s", topic, bootstrapServers);
throw new ConnectException(msg, cause);
} else if (cause instanceof UnsupportedVersionException) {
// Should theoretically never happen, because this method is the same as what the consumer uses and therefore
// should exist in the broker since before the admin client was added
String msg = String.format("API to get the get the end offsets for topic '%s' is unsupported on brokers at %s", topic, bootstrapServers);
throw new UnsupportedVersionException(msg, cause);
} else if (cause instanceof TimeoutException) {
String msg = String.format("Timed out while waiting to get end offsets for topic '%s' on brokers at %s", topic, bootstrapServers);
throw new TimeoutException(msg, cause);
} else if (cause instanceof LeaderNotAvailableException) {
String msg = String.format("Unable to get end offsets during leader election for topic '%s' on brokers at %s", topic, bootstrapServers);
throw new LeaderNotAvailableException(msg, cause);
} else if (cause instanceof org.apache.kafka.common.errors.RetriableException) {
throw (org.apache.kafka.common.errors.RetriableException) cause;
} else {
String msg = String.format("Error while getting end offsets for topic '%s' on brokers at %s", topic, bootstrapServers);
throw new ConnectException(msg, cause);
}
} catch (InterruptedException e) {
Thread.interrupted();
String msg = String.format("Interrupted while attempting to read end offsets for topic '%s' on brokers at %s", partition.topic(), bootstrapServers);
throw new RetriableException(msg, e);
}
}
return result;
}
/**
* Fetch the most recent offset for each of the supplied {@link TopicPartition} objects, and performs retry when
* {@link org.apache.kafka.connect.errors.RetriableException} is thrown.
*
* @param partitions the topic partitions
* @param timeoutDuration timeout duration; may not be null
* @param retryBackoffMs the number of milliseconds to delay upon receiving a
* {@link org.apache.kafka.connect.errors.RetriableException} before retrying again;
* must be 0 or more
* @return the map of offset for each topic partition, or an empty map if the supplied partitions
* are null or empty
* @throws UnsupportedVersionException if the broker is too old to support the admin client API to read end offsets
* @throws ConnectException if {@code timeoutDuration} is exhausted
* @see TopicAdmin#endOffsets(Set)
*/
public Map<TopicPartition, Long> retryEndOffsets(Set<TopicPartition> partitions, Duration timeoutDuration, long retryBackoffMs) {
try {
return RetryUtil.retryUntilTimeout(
() -> endOffsets(partitions),
() -> "list offsets for topic partitions",
timeoutDuration,
retryBackoffMs);
} catch (UnsupportedVersionException e) {
// Older brokers don't support this admin method, so rethrow it without wrapping it
throw e;
} catch (Exception e) {
throw ConnectUtils.maybeWrap(e, "Failed to list offsets for topic partitions");
}
}
@Override
public void close() {
admin.close();
}
public void close(Duration timeout) {
admin.close(timeout);
}
}
| NewTopicBuilder |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-batch-jdbc/src/main/java/smoketest/batch/SampleBatchApplication.java | {
"start": 1337,
"end": 2055
} | class ____ {
@Bean
Tasklet tasklet() {
return (contribution, context) -> RepeatStatus.FINISHED;
}
@Bean
Job job(JobRepository jobRepository, Step step) {
return new JobBuilder("job", jobRepository).start(step).build();
}
@Bean
Step step1(JobRepository jobRepository, Tasklet tasklet, PlatformTransactionManager transactionManager) {
return new StepBuilder("step1", jobRepository).tasklet(tasklet, transactionManager).build();
}
public static void main(String[] args) {
// System.exit is common for Batch applications since the exit code can be used to
// drive a workflow
System.exit(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class, args)));
}
}
| SampleBatchApplication |
java | apache__camel | components/camel-geocoder/src/main/java/org/apache/camel/component/geocoder/GeoCoderConstants.java | {
"start": 901,
"end": 2756
} | class ____ {
@Metadata(description = "The formatted address", javaType = "String")
public static final String ADDRESS = "CamelGeoCoderAddress";
@Metadata(description = "The latitude and longitude of the location. Separated by comma.", javaType = "String")
public static final String LATLNG = "CamelGeoCoderLatlng";
@Metadata(description = "The latitude of the location.", javaType = "String")
public static final String LAT = "CamelGeoCoderLat";
@Metadata(description = "The longitude of the location.", javaType = "String")
public static final String LNG = "CamelGeoCoderLng";
@Metadata(description = "Status code from the geocoder library. If status is\n" +
"`GeocoderStatus.OK` then additional headers is enriched",
javaType = "org.apache.camel.component.geocoder.GeocoderStatus", required = true)
public static final String STATUS = "CamelGeoCoderStatus";
@Metadata(description = "The region code.", javaType = "String")
public static final String REGION_CODE = "CamelGeoCoderRegionCode";
@Metadata(description = "The region name.", javaType = "String")
public static final String REGION_NAME = "CamelGeoCoderRegionName";
@Metadata(description = "The city long name.", javaType = "String")
public static final String CITY = "CamelGeoCoderCity";
@Metadata(description = "The country long name.", javaType = "String")
public static final String COUNTRY_LONG = "CamelGeoCoderCountryLong";
@Metadata(description = "The country short name.", javaType = "String")
public static final String COUNTRY_SHORT = "CamelGeoCoderCountryShort";
@Metadata(description = "The postal code.", javaType = "String")
public static final String POSTAL_CODE = "CamelGeoCoderPostalCode";
private GeoCoderConstants() {
}
}
| GeoCoderConstants |
java | spring-projects__spring-boot | module/spring-boot-neo4j/src/dockerTest/java/org/springframework/boot/neo4j/autoconfigure/Neo4jAutoConfigurationIntegrationTests.java | {
"start": 1952,
"end": 2128
} | class ____ {
@Container
private static final Neo4jContainer neo4j = TestImage.container(Neo4jContainer.class);
@SpringBootTest
@Nested
| Neo4jAutoConfigurationIntegrationTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CheckReturnValueWellKnownLibrariesTest.java | {
"start": 17221,
"end": 18068
} | class ____ {",
" static void testAnimal() {",
" Animal a = new AutoValue_Animal(\"dog\", 4);",
" // BUG: Diagnostic contains: CheckReturnValue",
" a.numberOfLegs();",
"", // And test usages where the static type is the generated class, too:
" AutoValue_Animal b = new AutoValue_Animal(\"dog\", 4);",
" // BUG: Diagnostic contains: CheckReturnValue",
" b.numberOfLegs();",
" }",
"}")
.setArgs(ImmutableList.of("-processor", AutoValueProcessor.class.getName()))
.doTest();
}
@Test
public void autoBuilderSetterMethods() {
compilationHelper
.addSourceLines(
"Person.java",
"""
package com.google.frobber;
public final | AnimalCaller |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/spi/CompositeOwner.java | {
"start": 173,
"end": 435
} | interface ____ extends PrimeAmongSecondarySupertypes {
/**
* @param attributeName to be added to the dirty list
*/
void $$_hibernate_trackChange(String attributeName);
@Override
default CompositeOwner asCompositeOwner() {
return this;
}
}
| CompositeOwner |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/cluster/service/ClusterStateUpdateStatsWireSerializationTests.java | {
"start": 679,
"end": 28028
} | class ____ extends AbstractWireSerializingTestCase<ClusterStateUpdateStats> {
@Override
protected Writeable.Reader<ClusterStateUpdateStats> instanceReader() {
return ClusterStateUpdateStats::new;
}
@Override
protected ClusterStateUpdateStats createTestInstance() {
return new ClusterStateUpdateStats(
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong()
);
}
private static long not(long l) {
return randomValueOtherThan(l, ESTestCase::randomNonNegativeLong);
}
@Override
protected ClusterStateUpdateStats mutateInstance(ClusterStateUpdateStats instance) {
switch (between(1, 19)) {
case 1:
return new ClusterStateUpdateStats(
not(instance.getUnchangedTaskCount()),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 2:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
not(instance.getPublicationSuccessCount()),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 3:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
not(instance.getPublicationFailureCount()),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 4:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
not(instance.getUnchangedComputationElapsedMillis()),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 5:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
not(instance.getUnchangedNotificationElapsedMillis()),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 6:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
not(instance.getSuccessfulComputationElapsedMillis()),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 7:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
not(instance.getSuccessfulPublicationElapsedMillis()),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 8:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
not(instance.getSuccessfulContextConstructionElapsedMillis()),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 9:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
not(instance.getSuccessfulCommitElapsedMillis()),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 10:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
not(instance.getSuccessfulCompletionElapsedMillis()),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 11:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
not(instance.getSuccessfulMasterApplyElapsedMillis()),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 12:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
not(instance.getSuccessfulNotificationElapsedMillis()),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 13:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
not(instance.getFailedComputationElapsedMillis()),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 14:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
not(instance.getFailedPublicationElapsedMillis()),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 15:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
not(instance.getFailedContextConstructionElapsedMillis()),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 16:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
not(instance.getFailedCommitElapsedMillis()),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 17:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
not(instance.getFailedCompletionElapsedMillis()),
instance.getFailedMasterApplyElapsedMillis(),
instance.getFailedNotificationElapsedMillis()
);
case 18:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
not(instance.getFailedMasterApplyElapsedMillis()),
instance.getFailedNotificationElapsedMillis()
);
case 19:
return new ClusterStateUpdateStats(
instance.getUnchangedTaskCount(),
instance.getPublicationSuccessCount(),
instance.getPublicationFailureCount(),
instance.getUnchangedComputationElapsedMillis(),
instance.getUnchangedNotificationElapsedMillis(),
instance.getSuccessfulComputationElapsedMillis(),
instance.getSuccessfulPublicationElapsedMillis(),
instance.getSuccessfulContextConstructionElapsedMillis(),
instance.getSuccessfulCommitElapsedMillis(),
instance.getSuccessfulCompletionElapsedMillis(),
instance.getSuccessfulMasterApplyElapsedMillis(),
instance.getSuccessfulNotificationElapsedMillis(),
instance.getFailedComputationElapsedMillis(),
instance.getFailedPublicationElapsedMillis(),
instance.getFailedContextConstructionElapsedMillis(),
instance.getFailedCommitElapsedMillis(),
instance.getFailedCompletionElapsedMillis(),
instance.getFailedMasterApplyElapsedMillis(),
not(instance.getFailedNotificationElapsedMillis())
);
}
throw new AssertionError("impossible");
}
}
| ClusterStateUpdateStatsWireSerializationTests |
java | spring-projects__spring-boot | module/spring-boot-neo4j/src/main/java/org/springframework/boot/neo4j/autoconfigure/ConfigBuilderCustomizer.java | {
"start": 776,
"end": 1033
} | interface ____ can be implemented by beans wishing to customize the a
* {@link ConfigBuilder} to fine-tune its auto-configuration before it creates a
* {@link Config} instance.
*
* @author Stephane Nicoll
* @since 4.0.0
*/
@FunctionalInterface
public | that |
java | apache__logging-log4j2 | log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4AuthFailureIT.java | {
"start": 1514,
"end": 2118
} | class ____ {
@Test
void test(final LoggerContext ctx, final MongoClient mongoClient) {
final Logger logger = ctx.getLogger(MongoDb4AuthFailureIT.class);
logger.info("Hello log");
final MongoDatabase database = mongoClient.getDatabase(MongoDb4TestConstants.DATABASE_NAME);
assertNotNull(database);
final MongoCollection<Document> collection =
database.getCollection(getClass().getSimpleName());
assertNotNull(collection);
final Document first = collection.find().first();
assertNull(first);
}
}
| MongoDb4AuthFailureIT |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/profile/resolver/ClassNameActiveProfilesResolverTests.java | {
"start": 1181,
"end": 1373
} | class ____ {
@Test
void test(@Autowired Environment environment) {
assertThat(environment.getActiveProfiles()).contains(getClass().getSimpleName());
}
}
| ClassNameActiveProfilesResolverTests |
java | netty__netty | testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketObjectEchoTest.java | {
"start": 5303,
"end": 6692
} | class ____ extends ChannelInboundHandlerAdapter {
private final boolean autoRead;
volatile Channel channel;
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
volatile int counter;
EchoHandler(boolean autoRead) {
this.autoRead = autoRead;
}
@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception {
channel = ctx.channel();
if (!autoRead) {
ctx.read();
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
assertEquals(data[counter], msg);
if (channel.parent() != null) {
channel.write(msg);
}
counter ++;
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
try {
ctx.flush();
} finally {
if (!autoRead) {
ctx.read();
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
if (exception.compareAndSet(null, cause)) {
ctx.close();
}
}
}
}
| EchoHandler |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/builditem/ApplicationIndexBuildItem.java | {
"start": 189,
"end": 427
} | class ____ extends SimpleBuildItem {
private final Index index;
public ApplicationIndexBuildItem(Index index) {
this.index = index;
}
public Index getIndex() {
return index;
}
}
| ApplicationIndexBuildItem |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/TimelineDataManager.java | {
"start": 2096,
"end": 2328
} | class ____ over the timeline store and the ACLs manager. It does some non
* trivial manipulation of the timeline data before putting or after getting it
* from the timeline store, and checks the user's access to it.
*
*/
public | wrap |
java | elastic__elasticsearch | modules/lang-painless/src/test/java/org/elasticsearch/painless/ArrayLikeObjectTestCase.java | {
"start": 716,
"end": 6444
} | class ____ extends ScriptTestCase {
/**
* Build the string for declaring the variable holding the array-like-object to test. So {@code int[]} for arrays and {@code List} for
* lists.
*/
protected abstract String declType(String valueType);
/**
* Build the string for calling the constructor for the array-like-object to test. So {@code new int[5]} for arrays and
* {@code [0, 0, 0, 0, 0]} or {@code [null, null, null, null, null]} for lists.
*/
protected abstract String valueCtorCall(String valueType, int size);
/**
* Matcher for the message of the out of bounds exceptions thrown for too negative or too positive offsets.
*/
protected abstract Matcher<String> outOfBoundsExceptionMessageMatcher(int index, int size);
private void arrayLoadStoreTestCase(boolean declareAsDef, String valueType, Object val, @Nullable Number valPlusOne) {
String declType = declareAsDef ? "def" : declType(valueType);
String valueCtorCall = valueCtorCall(valueType, 5);
String decl = declType + " x = " + valueCtorCall;
assertEquals(5, exec(decl + "; return x.length", true));
assertEquals(val, exec(decl + "; x[ 0] = params.val; return x[ 0];", singletonMap("val", val), true));
assertEquals(val, exec(decl + "; x[ 0] = params.val; return x[-5];", singletonMap("val", val), true));
assertEquals(val, exec(decl + "; x[-5] = params.val; return x[-5];", singletonMap("val", val), true));
expectOutOfBounds(6, decl + "; return x[ 6]", val);
expectOutOfBounds(-1, decl + "; return x[-6]", val);
expectOutOfBounds(6, decl + "; x[ 6] = params.val; return 0", val);
expectOutOfBounds(-1, decl + "; x[-6] = params.val; return 0", val);
if (valPlusOne != null) {
assertEquals(val, exec(decl + "; x[0] = params.val; x[ 0] = x[ 0]++; return x[0];", singletonMap("val", val), true));
assertEquals(val, exec(decl + "; x[0] = params.val; x[ 0] = x[-5]++; return x[0];", singletonMap("val", val), true));
assertEquals(valPlusOne, exec(decl + "; x[0] = params.val; x[ 0] = ++x[ 0]; return x[0];", singletonMap("val", val), true));
assertEquals(valPlusOne, exec(decl + "; x[0] = params.val; x[ 0] = ++x[-5]; return x[0];", singletonMap("val", val), true));
assertEquals(valPlusOne, exec(decl + "; x[0] = params.val; x[ 0]++ ; return x[0];", singletonMap("val", val), true));
assertEquals(valPlusOne, exec(decl + "; x[0] = params.val; x[-5]++ ; return x[0];", singletonMap("val", val), true));
assertEquals(valPlusOne, exec(decl + "; x[0] = params.val; x[ 0] += 1 ; return x[0];", singletonMap("val", val), true));
assertEquals(valPlusOne, exec(decl + "; x[0] = params.val; x[-5] += 1 ; return x[0];", singletonMap("val", val), true));
expectOutOfBounds(6, decl + "; return x[ 6]++", val);
expectOutOfBounds(-1, decl + "; return x[-6]++", val);
expectOutOfBounds(6, decl + "; return ++x[ 6]", val);
expectOutOfBounds(-1, decl + "; return ++x[-6]", val);
expectOutOfBounds(6, decl + "; x[ 6] += 1; return 0", val);
expectOutOfBounds(-1, decl + "; x[-6] += 1; return 0", val);
}
}
private void expectOutOfBounds(int index, String script, Object val) {
IndexOutOfBoundsException e = expectScriptThrows(
IndexOutOfBoundsException.class,
() -> exec(script, singletonMap("val", val), true)
);
try {
/* If this fails you *might* be missing -XX:-OmitStackTraceInFastThrow in the test jvm
* In Eclipse you can add this by default by going to Preference->Java->Installed JREs,
* clicking on the default JRE, clicking edit, and adding the flag to the
* "Default VM Arguments".
*/
assertThat(e.getMessage(), outOfBoundsExceptionMessageMatcher(index, 5));
} catch (AssertionError ae) {
// Mark the exception we are testing as suppressed so we get its stack trace.
ae.addSuppressed(e);
throw ae;
}
}
public void testInts() {
arrayLoadStoreTestCase(false, "int", 5, 6);
}
public void testIntsInDef() {
arrayLoadStoreTestCase(true, "int", 5, 6);
}
public void testLongs() {
arrayLoadStoreTestCase(false, "long", 5L, 6L);
}
public void testLongsInDef() {
arrayLoadStoreTestCase(true, "long", 5L, 6L);
}
public void testShorts() {
arrayLoadStoreTestCase(false, "short", (short) 5, (short) 6);
}
public void testShortsInDef() {
arrayLoadStoreTestCase(true, "short", (short) 5, (short) 6);
}
public void testBytes() {
arrayLoadStoreTestCase(false, "byte", (byte) 5, (byte) 6);
}
public void testBytesInDef() {
arrayLoadStoreTestCase(true, "byte", (byte) 5, (byte) 6);
}
public void testFloats() {
arrayLoadStoreTestCase(false, "float", 5.0f, 6.0f);
}
public void testFloatsInDef() {
arrayLoadStoreTestCase(true, "float", 5.0f, 6.0f);
}
public void testDoubles() {
arrayLoadStoreTestCase(false, "double", 5.0d, 6.0d);
}
public void testDoublesInDef() {
arrayLoadStoreTestCase(true, "double", 5.0d, 6.0d);
}
public void testStrings() {
arrayLoadStoreTestCase(false, "String", "cat", null);
}
public void testStringsInDef() {
arrayLoadStoreTestCase(true, "String", "cat", null);
}
public void testDef() {
arrayLoadStoreTestCase(true, "def", 5, null);
}
}
| ArrayLikeObjectTestCase |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/records/OutOfTheBoxRecordAsEmbeddableTest.java | {
"start": 786,
"end": 1408
} | class ____ {
@Test
public void testRecordPersistLoadAndMerge(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.persist( new MyEntity( 1L, new MyRecord( "test", "abc" ) ) );
}
);
scope.inTransaction(
session -> {
MyEntity myEntity = session.get( MyEntity.class, 1L );
assertNotNull( myEntity );
assertEquals( "test", myEntity.getRecord().name() );
assertEquals( "abc", myEntity.getRecord().description() );
myEntity.setRecord( new MyRecord( "test2", "def" ) );
}
);
}
@Entity(name = "MyEntity")
public static | OutOfTheBoxRecordAsEmbeddableTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/SelfEqualsTest.java | {
"start": 934,
"end": 1656
} | class ____ {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(SelfEquals.class, getClass());
@Test
public void positiveCase() {
compilationHelper
.addSourceLines(
"SelfEqualsPositiveCase.java",
"""
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Assert;
/**
* Positive test cases for {@link SelfEquals} check.
*
* @author eaftan@google.com (Eddie Aftandilian)
* @author bhagwani@google.com (Sumit Bhagwani)
*/
public | SelfEqualsTest |
java | quarkusio__quarkus | integration-tests/spring-web/src/test/java/io/quarkus/it/spring/web/testprofile/Profiles.java | {
"start": 572,
"end": 661
} | class ____ implements QuarkusTestProfile {
}
public static | QuarkusTestProfileNoTags |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/CascadeManagedAndTransientTest.java | {
"start": 11524,
"end": 13614
} | class ____ {
@Id
@GeneratedValue
private Long nodeID;
@Version
private long version;
@Basic(optional = false)
private String name;
@OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, mappedBy = "deliveryNode")
private Set<Transport> deliveryTransports = new HashSet<>();
@OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, mappedBy = "pickupNode")
private Set<Transport> pickupTransports = new HashSet<>();
@ManyToOne(
optional = false,
cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH},
fetch = FetchType.EAGER
)
private Route route = null;
@ManyToOne(
optional = false,
cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH},
fetch = FetchType.EAGER
)
private Tour tour;
@Transient
private String transientField = "node original value";
public Set<Transport> getDeliveryTransports() {
return deliveryTransports;
}
public void setDeliveryTransports(Set<Transport> deliveryTransports) {
this.deliveryTransports = deliveryTransports;
}
public Set<Transport> getPickupTransports() {
return pickupTransports;
}
public void setPickupTransports(Set<Transport> pickupTransports) {
this.pickupTransports = pickupTransports;
}
public Long getNodeID() {
return nodeID;
}
public long getVersion() {
return version;
}
protected void setVersion(long version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Route getRoute() {
return route;
}
public void setRoute(Route route) {
this.route = route;
}
public Tour getTour() {
return tour;
}
public void setTour(Tour tour) {
this.tour = tour;
}
public String getTransientField() {
return transientField;
}
public void setTransientField(String transientField) {
this.transientField = transientField;
}
protected void setNodeID(Long nodeID) {
this.nodeID = nodeID;
}
}
}
| Node |
java | google__truth | core/src/main/java/com/google/common/truth/ExpectFailure.java | {
"start": 5038,
"end": 5174
} | interface ____ we check for so that we can automatically disable "value of" lines during
* {@link ExpectFailure} assertions.
*/
| that |
java | junit-team__junit5 | junit-jupiter-params/src/main/java/org/junit/jupiter/params/ParameterizedDeclarationContext.java | {
"start": 510,
"end": 1122
} | interface ____<C> {
Class<?> getTestClass();
Annotation getAnnotation();
AnnotatedElement getAnnotatedElement();
String getDisplayNamePattern();
boolean quoteTextArguments();
boolean isAutoClosingArguments();
boolean isAllowingZeroInvocations();
ArgumentCountValidationMode getArgumentCountValidationMode();
default String getAnnotationName() {
return getAnnotation().annotationType().getSimpleName();
}
ResolverFacade getResolverFacade();
C createInvocationContext(ParameterizedInvocationNameFormatter formatter, Arguments arguments, int invocationIndex);
}
| ParameterizedDeclarationContext |
java | spring-projects__spring-boot | module/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/NativeImageResourceProviderCustomizer.java | {
"start": 1030,
"end": 1671
} | class ____ extends ResourceProviderCustomizer {
@Override
public void customize(FluentConfiguration configuration) {
if (configuration.getResourceProvider() == null) {
Scanner<JavaMigration> scanner = new Scanner<>(JavaMigration.class, configuration,
configuration.getLocations());
NativeImageResourceProvider resourceProvider = new NativeImageResourceProvider(scanner,
configuration.getClassLoader(), Arrays.asList(configuration.getLocations()),
configuration.getEncoding(), configuration.isFailOnMissingLocations());
configuration.resourceProvider(resourceProvider);
}
}
}
| NativeImageResourceProviderCustomizer |
java | apache__camel | components/camel-http/src/test/java/org/apache/camel/component/http/HttpsSslContextParametersGetTest.java | {
"start": 1180,
"end": 2335
} | class ____ extends HttpsGetTest {
private HttpServer localServer;
@Override
public final void doPreSetup() throws Exception {
localServer = ServerBootstrap.bootstrap()
.setCanonicalHostName("localhost").setHttpProcessor(getBasicHttpProcessor())
.setConnectionReuseStrategy(getConnectionReuseStrategy()).setResponseFactory(getHttpResponseFactory())
.setSslContext(getSSLContext())
.register("/mail/", new BasicValidationHandler(GET.name(), null, null, getExpectedContent())).create();
localServer.start();
}
@Override
public void cleanupResources() {
if (localServer != null) {
localServer.stop();
}
}
@Override
@Test
public void httpsGet() {
Exchange exchange = template.request("https://localhost:" + localServer.getLocalPort()
+ "/mail/?x509HostnameVerifier=x509HostnameVerifier&sslContextParameters=#sslContextParameters",
exchange1 -> {
});
assertExchange(exchange);
}
}
| HttpsSslContextParametersGetTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_192_ibatis.java | {
"start": 303,
"end": 981
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "select * from ${table_name} \n" +
"where ${column_name} in ( #{valueList} )";
// System.out.println(sql);
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0);
assertEquals(1, statementList.size());
assertEquals("SELECT *\n" +
"FROM ${table_name}\n" +
"WHERE ${column_name} IN (#{valueList})", stmt.toString());
}
}
| MySqlSelectTest_192_ibatis |
java | google__guava | android/guava/src/com/google/common/graph/StandardNetwork.java | {
"start": 2061,
"end": 7057
} | class ____<N, E> extends AbstractNetwork<N, E> {
private final boolean isDirected;
private final boolean allowsParallelEdges;
private final boolean allowsSelfLoops;
private final ElementOrder<N> nodeOrder;
private final ElementOrder<E> edgeOrder;
final MapIteratorCache<N, NetworkConnections<N, E>> nodeConnections;
// We could make this a Map<E, EndpointPair<N>>. It would make incidentNodes(edge) slightly
// faster, but also make Networks consume 5 to 20+% (increasing with average degree) more memory.
final MapIteratorCache<E, N> edgeToReferenceNode; // referenceNode == source if directed
/** Constructs a graph with the properties specified in {@code builder}. */
StandardNetwork(NetworkBuilder<? super N, ? super E> builder) {
this(
builder,
builder.nodeOrder.<N, NetworkConnections<N, E>>createMap(
builder.expectedNodeCount.or(DEFAULT_NODE_COUNT)),
builder.edgeOrder.<E, N>createMap(builder.expectedEdgeCount.or(DEFAULT_EDGE_COUNT)));
}
/**
* Constructs a graph with the properties specified in {@code builder}, initialized with the given
* node and edge maps.
*/
StandardNetwork(
NetworkBuilder<? super N, ? super E> builder,
Map<N, NetworkConnections<N, E>> nodeConnections,
Map<E, N> edgeToReferenceNode) {
this.isDirected = builder.directed;
this.allowsParallelEdges = builder.allowsParallelEdges;
this.allowsSelfLoops = builder.allowsSelfLoops;
this.nodeOrder = builder.nodeOrder.cast();
this.edgeOrder = builder.edgeOrder.cast();
// Prefer the heavier "MapRetrievalCache" for nodes if lookup is expensive. This optimizes
// methods that access the same node(s) repeatedly, such as Graphs.removeEdgesConnecting().
this.nodeConnections =
(nodeConnections instanceof TreeMap)
? new MapRetrievalCache<N, NetworkConnections<N, E>>(nodeConnections)
: new MapIteratorCache<N, NetworkConnections<N, E>>(nodeConnections);
this.edgeToReferenceNode = new MapIteratorCache<>(edgeToReferenceNode);
}
@Override
public Set<N> nodes() {
return nodeConnections.unmodifiableKeySet();
}
@Override
public Set<E> edges() {
return edgeToReferenceNode.unmodifiableKeySet();
}
@Override
public boolean isDirected() {
return isDirected;
}
@Override
public boolean allowsParallelEdges() {
return allowsParallelEdges;
}
@Override
public boolean allowsSelfLoops() {
return allowsSelfLoops;
}
@Override
public ElementOrder<N> nodeOrder() {
return nodeOrder;
}
@Override
public ElementOrder<E> edgeOrder() {
return edgeOrder;
}
@Override
public Set<E> incidentEdges(N node) {
return nodeInvalidatableSet(checkedConnections(node).incidentEdges(), node);
}
@Override
public EndpointPair<N> incidentNodes(E edge) {
N nodeU = checkedReferenceNode(edge);
// requireNonNull is safe because checkedReferenceNode made sure the edge is in the network.
N nodeV = requireNonNull(nodeConnections.get(nodeU)).adjacentNode(edge);
return EndpointPair.of(this, nodeU, nodeV);
}
@Override
public Set<N> adjacentNodes(N node) {
return nodeInvalidatableSet(checkedConnections(node).adjacentNodes(), node);
}
@Override
public Set<E> edgesConnecting(N nodeU, N nodeV) {
NetworkConnections<N, E> connectionsU = checkedConnections(nodeU);
if (!allowsSelfLoops && nodeU == nodeV) { // just an optimization, only check reference equality
return ImmutableSet.of();
}
checkArgument(containsNode(nodeV), NODE_NOT_IN_GRAPH, nodeV);
return nodePairInvalidatableSet(connectionsU.edgesConnecting(nodeV), nodeU, nodeV);
}
@Override
public Set<E> inEdges(N node) {
return nodeInvalidatableSet(checkedConnections(node).inEdges(), node);
}
@Override
public Set<E> outEdges(N node) {
return nodeInvalidatableSet(checkedConnections(node).outEdges(), node);
}
@Override
public Set<N> predecessors(N node) {
return nodeInvalidatableSet(checkedConnections(node).predecessors(), node);
}
@Override
public Set<N> successors(N node) {
return nodeInvalidatableSet(checkedConnections(node).successors(), node);
}
final NetworkConnections<N, E> checkedConnections(N node) {
NetworkConnections<N, E> connections = nodeConnections.get(node);
if (connections == null) {
checkNotNull(node);
throw new IllegalArgumentException(String.format(NODE_NOT_IN_GRAPH, node));
}
return connections;
}
final N checkedReferenceNode(E edge) {
N referenceNode = edgeToReferenceNode.get(edge);
if (referenceNode == null) {
checkNotNull(edge);
throw new IllegalArgumentException(String.format(EDGE_NOT_IN_GRAPH, edge));
}
return referenceNode;
}
final boolean containsNode(N node) {
return nodeConnections.containsKey(node);
}
final boolean containsEdge(E edge) {
return edgeToReferenceNode.containsKey(edge);
}
}
| StandardNetwork |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/operators/SimpleQueue.java | {
"start": 1076,
"end": 2717
} | interface ____<@NonNull T> {
/**
* Atomically enqueue a single value.
* @param value the value to enqueue, not null
* @return true if successful, false if the value was not enqueued
* likely due to reaching the queue capacity)
*/
boolean offer(@NonNull T value);
/**
* Atomically enqueue two values.
* @param v1 the first value to enqueue, not null
* @param v2 the second value to enqueue, not null
* @return true if successful, false if the value was not enqueued
* likely due to reaching the queue capacity)
*/
boolean offer(@NonNull T v1, @NonNull T v2);
/**
* Tries to dequeue a value (non-null) or returns null if
* the queue is empty.
* <p>
* If the producer uses {@link #offer(Object, Object)} and
* when polling in pairs, if the first poll() returns a non-null
* item, the second poll() is guaranteed to return a non-null item
* as well.
* @return the item or null to indicate an empty queue
* @throws Throwable if some pre-processing of the dequeued
* item (usually through fused functions) throws.
*/
@Nullable
T poll() throws Throwable;
/**
* Returns true if the queue is empty.
* <p>
* Note however that due to potential fused functions in {@link #poll()}
* it is possible this method returns false but then poll() returns null
* because the fused function swallowed the available item(s).
* @return true if the queue is empty
*/
boolean isEmpty();
/**
* Removes all enqueued items from this queue.
*/
void clear();
}
| SimpleQueue |
java | google__guava | guava/src/com/google/common/collect/ImmutableMapEntry.java | {
"start": 4101,
"end": 4687
} | class ____<K, V>
extends NonTerminalImmutableMapEntry<K, V> {
private final transient @Nullable ImmutableMapEntry<K, V> nextInValueBucket;
NonTerminalImmutableBiMapEntry(
K key,
V value,
@Nullable ImmutableMapEntry<K, V> nextInKeyBucket,
@Nullable ImmutableMapEntry<K, V> nextInValueBucket) {
super(key, value, nextInKeyBucket);
this.nextInValueBucket = nextInValueBucket;
}
@Override
@Nullable ImmutableMapEntry<K, V> getNextInValueBucket() {
return nextInValueBucket;
}
}
}
| NonTerminalImmutableBiMapEntry |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/event/EventListenerFactory.java | {
"start": 936,
"end": 1625
} | interface ____ {
/**
* Specify if this factory supports the specified {@link Method}.
* @param method an {@link EventListener} annotated method
* @return {@code true} if this factory supports the specified method
*/
boolean supportsMethod(Method method);
/**
* Create an {@link ApplicationListener} for the specified method.
* @param beanName the name of the bean
* @param type the target type of the instance
* @param method the {@link EventListener} annotated method
* @return an application listener, suitable to invoke the specified method
*/
ApplicationListener<?> createApplicationListener(String beanName, Class<?> type, Method method);
}
| EventListenerFactory |
java | google__dagger | dagger-producers/main/java/dagger/producers/monitoring/TimingRecorders.java | {
"start": 8536,
"end": 12575
} | class ____ extends ProducerTimingRecorder {
private final ImmutableList<ProducerTimingRecorder> delegates;
DelegatingProducerTimingRecorder(ImmutableList<ProducerTimingRecorder> delegates) {
this.delegates = delegates;
}
@Override
public void recordMethod(long startedNanos, long durationNanos) {
for (ProducerTimingRecorder delegate : delegates) {
try {
delegate.recordMethod(startedNanos, durationNanos);
} catch (RuntimeException e) {
logProducerTimingRecorderMethodException(e, delegate, "recordMethod");
}
}
}
@Override
public void recordSuccess(long latencyNanos) {
for (ProducerTimingRecorder delegate : delegates) {
try {
delegate.recordSuccess(latencyNanos);
} catch (RuntimeException e) {
logProducerTimingRecorderMethodException(e, delegate, "recordSuccess");
}
}
}
@Override
public void recordFailure(Throwable exception, long latencyNanos) {
for (ProducerTimingRecorder delegate : delegates) {
try {
delegate.recordFailure(exception, latencyNanos);
} catch (RuntimeException e) {
logProducerTimingRecorderMethodException(e, delegate, "recordFailure");
}
}
}
@Override
public void recordSkip(Throwable exception) {
for (ProducerTimingRecorder delegate : delegates) {
try {
delegate.recordSkip(exception);
} catch (RuntimeException e) {
logProducerTimingRecorderMethodException(e, delegate, "recordSkip");
}
}
}
}
/** Returns a recorder factory that returns no-op component recorders. */
public static ProductionComponentTimingRecorder.Factory
noOpProductionComponentTimingRecorderFactory() {
return NO_OP_PRODUCTION_COMPONENT_TIMING_RECORDER_FACTORY;
}
/** Returns a component recorder that returns no-op producer recorders. */
public static ProductionComponentTimingRecorder noOpProductionComponentTimingRecorder() {
return NO_OP_PRODUCTION_COMPONENT_TIMING_RECORDER;
}
private static final ProductionComponentTimingRecorder.Factory
NO_OP_PRODUCTION_COMPONENT_TIMING_RECORDER_FACTORY =
new ProductionComponentTimingRecorder.Factory() {
@Override
public ProductionComponentTimingRecorder create(Object component) {
return noOpProductionComponentTimingRecorder();
}
};
private static final ProductionComponentTimingRecorder
NO_OP_PRODUCTION_COMPONENT_TIMING_RECORDER =
new ProductionComponentTimingRecorder() {
@Override
public ProducerTimingRecorder producerTimingRecorderFor(ProducerToken token) {
return ProducerTimingRecorder.noOp();
}
};
private static void logCreateException(
RuntimeException e, ProductionComponentTimingRecorder.Factory factory, Object component) {
logger.log(
Level.SEVERE,
"RuntimeException while calling ProductionComponentTimingRecorder.Factory.create on"
+ " factory "
+ factory
+ " with component "
+ component,
e);
}
private static void logProducerTimingRecorderForException(
RuntimeException e, ProductionComponentTimingRecorder recorder, ProducerToken token) {
logger.log(
Level.SEVERE,
"RuntimeException while calling ProductionComponentTimingRecorder.producerTimingRecorderFor"
+ "on recorder "
+ recorder
+ " with token "
+ token,
e);
}
private static void logProducerTimingRecorderMethodException(
RuntimeException e, ProducerTimingRecorder recorder, String method) {
logger.log(
Level.SEVERE,
"RuntimeException while calling ProducerTimingRecorder."
+ method
+ " on recorder "
+ recorder,
e);
}
private TimingRecorders() {}
}
| DelegatingProducerTimingRecorder |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/util/Executables.java | {
"start": 640,
"end": 2955
} | class ____ {
private static final Method DEFAULT_METHOD;
static {
Method method;
try {
method = ExecutableElement.class.getMethod( "isDefault" );
}
catch ( NoSuchMethodException e ) {
method = null;
}
DEFAULT_METHOD = method;
}
private Executables() {
}
static boolean isPublicNotStatic(ExecutableElement method) {
return isPublic( method ) && isNotStatic( method );
}
static boolean isPublic(ExecutableElement method) {
return method.getModifiers().contains( Modifier.PUBLIC );
}
private static boolean isNotStatic(ExecutableElement method) {
return !method.getModifiers().contains( Modifier.STATIC );
}
public static boolean isFinal(Accessor accessor) {
return accessor != null && accessor.getModifiers().contains( Modifier.FINAL );
}
public static boolean isDefaultMethod(ExecutableElement method) {
try {
return DEFAULT_METHOD != null && Boolean.TRUE.equals( DEFAULT_METHOD.invoke( method ) );
}
catch ( IllegalAccessException | InvocationTargetException e ) {
return false;
}
}
/**
* @param executableElement the element to check
* @return {@code true}, if the executable element is a method annotated with {@code @BeforeMapping} or
* {@code @AfterMapping}
*/
public static boolean isLifecycleCallbackMethod(ExecutableElement executableElement) {
return isBeforeMappingMethod( executableElement ) || isAfterMappingMethod( executableElement );
}
/**
* @param executableElement the element to check
* @return {@code true}, if the executable element is a method annotated with {@code @AfterMapping}
*/
public static boolean isAfterMappingMethod(ExecutableElement executableElement) {
return AfterMappingGem.instanceOn( executableElement ) != null;
}
/**
* @param executableElement the element to check
* @return {@code true}, if the executable element is a method annotated with {@code @BeforeMapping}
*/
public static boolean isBeforeMappingMethod(ExecutableElement executableElement) {
return BeforeMappingGem.instanceOn( executableElement ) != null;
}
}
| Executables |
java | google__dagger | javatests/dagger/hilt/android/ViewModelSavedStateOwnerTest.java | {
"start": 9320,
"end": 9716
} | class ____
extends Hilt_ViewModelSavedStateOwnerTest_ErrorTestActivity {
@Inject @ActivityRetainedSavedState Provider<SavedStateHandle> provider;
@SuppressWarnings("unused")
@Override
protected void onDestroy() {
super.onDestroy();
SavedStateHandle savedStateHandle = provider.get();
}
}
@AndroidEntryPoint(Fragment.class)
public static | ErrorTestActivity |
java | apache__thrift | lib/java/src/main/java/org/apache/thrift/transport/AutoExpandingBufferWriteTransport.java | {
"start": 954,
"end": 2994
} | class ____ extends TEndpointTransport {
private final AutoExpandingBuffer buf;
private int pos;
private int res;
/**
* Constructor.
*
* @param config the configuration to use. Currently used for defining the maximum message size.
* @param initialCapacity the initial capacity of the buffer
* @param frontReserve space, if any, to reserve at the beginning such that the first write is
* after this reserve. This allows framed transport to reserve space for the frame buffer
* length.
* @throws IllegalArgumentException if initialCapacity is less than one
* @throws IllegalArgumentException if frontReserve is less than zero
* @throws IllegalArgumentException if frontReserve is greater than initialCapacity
*/
public AutoExpandingBufferWriteTransport(
TConfiguration config, int initialCapacity, int frontReserve) throws TTransportException {
super(config);
if (initialCapacity < 1) {
throw new IllegalArgumentException("initialCapacity");
}
if (frontReserve < 0 || initialCapacity < frontReserve) {
throw new IllegalArgumentException("frontReserve");
}
this.buf = new AutoExpandingBuffer(initialCapacity);
this.pos = frontReserve;
this.res = frontReserve;
}
@Override
public void close() {}
@Override
public boolean isOpen() {
return true;
}
@Override
public void open() throws TTransportException {}
@Override
public int read(byte[] buf, int off, int len) throws TTransportException {
throw new UnsupportedOperationException();
}
@Override
public void write(byte[] toWrite, int off, int len) throws TTransportException {
buf.resizeIfNecessary(pos + len);
System.arraycopy(toWrite, off, buf.array(), pos, len);
pos += len;
}
public AutoExpandingBuffer getBuf() {
return buf;
}
/**
* @return length of the buffer, including any front reserve
*/
public int getLength() {
return pos;
}
public void reset() {
pos = res;
}
}
| AutoExpandingBufferWriteTransport |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/OAIPMHEndpointBuilderFactory.java | {
"start": 38674,
"end": 41243
} | interface ____ extends EndpointProducerBuilder {
default OAIPMHEndpointProducerBuilder basic() {
return (OAIPMHEndpointProducerBuilder) this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedOAIPMHEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedOAIPMHEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
}
/**
* Builder for endpoint for the OAI-PMH component.
*/
public | AdvancedOAIPMHEndpointProducerBuilder |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/provider/ContextProvidersPriorityTest.java | {
"start": 1523,
"end": 2601
} | class ____ {
private static final String HEADER_NAME = "my-header";
private static final String HEADER_VALUE_FROM_LOW_PRIORITY = "low-priority";
private static final String HEADER_VALUE_FROM_HIGH_PRIORITY = "high-priority";
@TestHTTPResource
URI baseUri;
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar.addClasses(Client.class, TestJacksonBasicMessageBodyReader.class));
@Test
void shouldUseTheHighestPriorityContextProvider() {
// @formatter:off
var response =
given()
.body(baseUri.toString())
.when()
.post("/call-client")
.thenReturn();
// @formatter:on
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.jsonPath().getString(HEADER_NAME)).isEqualTo(format("[%s]", HEADER_VALUE_FROM_HIGH_PRIORITY));
}
@Path("/")
@ApplicationScoped
public static | ContextProvidersPriorityTest |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/cglib/transform/FieldVisitorTee.java | {
"start": 899,
"end": 1962
} | class ____ extends FieldVisitor {
private FieldVisitor fv1, fv2;
public FieldVisitorTee(FieldVisitor fv1, FieldVisitor fv2) {
super(Constants.ASM_API);
this.fv1 = fv1;
this.fv2 = fv2;
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
return AnnotationVisitorTee.getInstance(fv1.visitAnnotation(desc, visible),
fv2.visitAnnotation(desc, visible));
}
@Override
public void visitAttribute(Attribute attr) {
fv1.visitAttribute(attr);
fv2.visitAttribute(attr);
}
@Override
public void visitEnd() {
fv1.visitEnd();
fv2.visitEnd();
}
@Override
public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
return AnnotationVisitorTee.getInstance(fv1.visitTypeAnnotation(typeRef, typePath, desc, visible),
fv2.visitTypeAnnotation(typeRef, typePath, desc, visible));
}
}
| FieldVisitorTee |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/DeregisterSubClusterResponse.java | {
"start": 1154,
"end": 1741
} | class ____ {
@Private
@Unstable
public static DeregisterSubClusterResponse newInstance(
List<DeregisterSubClusters> deregisterSubClusters) {
DeregisterSubClusterResponse response = Records.newRecord(DeregisterSubClusterResponse.class);
response.setDeregisterSubClusters(deregisterSubClusters);
return response;
}
@Private
@Unstable
public abstract void setDeregisterSubClusters(List<DeregisterSubClusters> deregisterSubClusters);
@Public
@Unstable
public abstract List<DeregisterSubClusters> getDeregisterSubClusters();
}
| DeregisterSubClusterResponse |
java | spring-projects__spring-framework | spring-webflux/src/test/java/org/springframework/web/reactive/result/SimpleUrlHandlerMappingIntegrationTests.java | {
"start": 2292,
"end": 4989
} | class ____ extends AbstractHttpHandlerIntegrationTests {
@Override
protected HttpHandler createHttpHandler() {
AnnotationConfigApplicationContext wac = new AnnotationConfigApplicationContext(WebConfig.class);
return WebHttpHandlerBuilder.webHandler(new DispatcherHandler(wac))
.exceptionHandler(new ResponseStatusExceptionHandler())
.build();
}
@ParameterizedHttpServerTest
void requestToFooHandler(HttpServer httpServer) throws Exception {
startServer(httpServer);
URI url = URI.create("http://localhost:" + this.port + "/foo");
RequestEntity<Void> request = RequestEntity.get(url).build();
@SuppressWarnings("resource")
ResponseEntity<byte[]> response = new RestTemplate().exchange(request, byte[].class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isEqualTo("foo".getBytes(StandardCharsets.UTF_8));
}
@ParameterizedHttpServerTest
public void requestToBarHandler(HttpServer httpServer) throws Exception {
startServer(httpServer);
URI url = URI.create("http://localhost:" + this.port + "/bar");
RequestEntity<Void> request = RequestEntity.get(url).build();
@SuppressWarnings("resource")
ResponseEntity<byte[]> response = new RestTemplate().exchange(request, byte[].class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isEqualTo("bar".getBytes(StandardCharsets.UTF_8));
}
@ParameterizedHttpServerTest
void requestToHeaderSettingHandler(HttpServer httpServer) throws Exception {
startServer(httpServer);
URI url = URI.create("http://localhost:" + this.port + "/header");
RequestEntity<Void> request = RequestEntity.get(url).build();
@SuppressWarnings("resource")
ResponseEntity<byte[]> response = new RestTemplate().exchange(request, byte[].class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getHeaders().getFirst("foo")).isEqualTo("bar");
}
@ParameterizedHttpServerTest
@SuppressWarnings("resource")
void handlerNotFound(HttpServer httpServer) throws Exception {
startServer(httpServer);
URI url = URI.create("http://localhost:" + this.port + "/oops");
RequestEntity<Void> request = RequestEntity.get(url).build();
try {
new RestTemplate().exchange(request, byte[].class);
}
catch (HttpClientErrorException ex) {
assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
}
private static DataBuffer asDataBuffer(String text) {
DefaultDataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(256);
return buffer.write(text.getBytes(StandardCharsets.UTF_8));
}
@Configuration
static | SimpleUrlHandlerMappingIntegrationTests |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/publisher/FluxDistinctTest.java | {
"start": 25635,
"end": 25960
} | class ____ {
private final int i;
public DistinctDefaultError(int i) {
this.i = i;
}
@Override
public int hashCode() {
return i % 3;
}
@Override
public boolean equals(Object obj) {
return obj instanceof DistinctDefaultError && ((DistinctDefaultError) obj).i == i;
}
}
static | DistinctDefaultError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.