language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/authentication/event/AuthenticationFailureServiceExceptionEvent.java
{ "start": 1017, "end": 1354 }
class ____ extends AbstractAuthenticationFailureEvent { @Serial private static final long serialVersionUID = 5580062757249390756L; public AuthenticationFailureServiceExceptionEvent(Authentication authentication, AuthenticationException exception) { super(authentication, exception); } }
AuthenticationFailureServiceExceptionEvent
java
elastic__elasticsearch
modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/DerivativePipelineAggregationBuilder.java
{ "start": 1560, "end": 10303 }
class ____ extends AbstractPipelineAggregationBuilder<DerivativePipelineAggregationBuilder> { public static final String NAME = "derivative"; private static final ParseField FORMAT_FIELD = new ParseField("format"); private static final ParseField GAP_POLICY_FIELD = new ParseField("gap_policy"); private static final ParseField UNIT_FIELD = new ParseField("unit"); private String format; private GapPolicy gapPolicy = GapPolicy.SKIP; private String units; public DerivativePipelineAggregationBuilder(String name, String bucketsPath) { this(name, new String[] { bucketsPath }); } private DerivativePipelineAggregationBuilder(String name, String[] bucketsPaths) { super(name, NAME, bucketsPaths); } /** * Read from a stream. */ public DerivativePipelineAggregationBuilder(StreamInput in) throws IOException { super(in, NAME); format = in.readOptionalString(); if (in.readBoolean()) { gapPolicy = GapPolicy.readFrom(in); } units = in.readOptionalString(); } @Override protected void doWriteTo(StreamOutput out) throws IOException { out.writeOptionalString(format); boolean hasGapPolicy = gapPolicy != null; out.writeBoolean(hasGapPolicy); if (hasGapPolicy) { gapPolicy.writeTo(out); } out.writeOptionalString(units); } public DerivativePipelineAggregationBuilder format(String format) { if (format == null) { throw new IllegalArgumentException("[format] must not be null: [" + name + "]"); } this.format = format; return this; } public String format() { return format; } public DerivativePipelineAggregationBuilder gapPolicy(GapPolicy gapPolicy) { if (gapPolicy == null) { throw new IllegalArgumentException("[gapPolicy] must not be null: [" + name + "]"); } this.gapPolicy = gapPolicy; return this; } public GapPolicy gapPolicy() { return gapPolicy; } public DerivativePipelineAggregationBuilder unit(String units) { if (units == null) { throw new IllegalArgumentException("[units] must not be null: [" + name + "]"); } this.units = units; return this; } public DerivativePipelineAggregationBuilder unit(DateHistogramInterval units) { if (units == null) { throw new IllegalArgumentException("[units] must not be null: [" + name + "]"); } this.units = units.toString(); return this; } public String unit() { return units; } @Override protected PipelineAggregator createInternal(Map<String, Object> metadata) { DocValueFormat formatter; if (format != null) { formatter = new DocValueFormat.Decimal(format); } else { formatter = DocValueFormat.RAW; } Long xAxisUnits = null; if (units != null) { Rounding.DateTimeUnit dateTimeUnit = DateHistogramAggregationBuilder.DATE_FIELD_UNITS.get(units); if (dateTimeUnit != null) { xAxisUnits = dateTimeUnit.getField().getBaseUnit().getDuration().toMillis(); } else { TimeValue timeValue = TimeValue.parseTimeValue(units, null, getClass().getSimpleName() + ".unit"); if (timeValue != null) { xAxisUnits = timeValue.getMillis(); } } } return new DerivativePipelineAggregator(name, bucketsPaths, formatter, gapPolicy, xAxisUnits, metadata); } @Override protected void validate(ValidationContext context) { if (bucketsPaths.length != 1) { context.addValidationError( PipelineAggregator.Parser.BUCKETS_PATH.getPreferredName() + " must contain a single entry for aggregation [" + name + "]" ); } context.validateParentAggSequentiallyOrderedWithoutSkips(NAME, name); } @Override protected XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException { if (format != null) { builder.field(FORMAT_FIELD.getPreferredName(), format); } if (gapPolicy != null) { builder.field(GAP_POLICY_FIELD.getPreferredName(), gapPolicy.getName()); } if (units != null) { builder.field(UNIT_FIELD.getPreferredName(), units); } return builder; } public static DerivativePipelineAggregationBuilder parse(String pipelineAggregatorName, XContentParser parser) throws IOException { XContentParser.Token token; String currentFieldName = null; String[] bucketsPaths = null; String format = null; String units = null; GapPolicy gapPolicy = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_STRING) { if (FORMAT_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { format = parser.text(); } else if (BUCKETS_PATH_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { bucketsPaths = new String[] { parser.text() }; } else if (GAP_POLICY_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { gapPolicy = GapPolicy.parse(parser.text(), parser.getTokenLocation()); } else if (UNIT_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { units = parser.text(); } else { throw new ParsingException( parser.getTokenLocation(), "Unknown key for a " + token + " in [" + pipelineAggregatorName + "]: [" + currentFieldName + "]." ); } } else if (token == XContentParser.Token.START_ARRAY) { if (BUCKETS_PATH_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { List<String> paths = new ArrayList<>(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { String path = parser.text(); paths.add(path); } bucketsPaths = paths.toArray(new String[paths.size()]); } else { throw new ParsingException( parser.getTokenLocation(), "Unknown key for a " + token + " in [" + pipelineAggregatorName + "]: [" + currentFieldName + "]." ); } } else { throw new ParsingException( parser.getTokenLocation(), "Unexpected token " + token + " in [" + pipelineAggregatorName + "]." ); } } if (bucketsPaths == null) { throw new ParsingException( parser.getTokenLocation(), "Missing required field [" + BUCKETS_PATH_FIELD.getPreferredName() + "] for derivative aggregation [" + pipelineAggregatorName + "]" ); } DerivativePipelineAggregationBuilder factory = new DerivativePipelineAggregationBuilder(pipelineAggregatorName, bucketsPaths[0]); if (format != null) { factory.format(format); } if (gapPolicy != null) { factory.gapPolicy(gapPolicy); } if (units != null) { factory.unit(units); } return factory; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; if (super.equals(obj) == false) return false; DerivativePipelineAggregationBuilder other = (DerivativePipelineAggregationBuilder) obj; return Objects.equals(format, other.format) && gapPolicy == other.gapPolicy && Objects.equals(units, other.units); } @Override public int hashCode() { return Objects.hash(super.hashCode(), format, gapPolicy, units); } @Override public String getWriteableName() { return NAME; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.zero(); } }
DerivativePipelineAggregationBuilder
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/NativeQuery.java
{ "start": 1822, "end": 3843 }
interface ____ { /** * Defines the native query to be executed when the annotated method is called. Alias for {@link Query#value()}. */ @AliasFor(annotation = Query.class) String value() default ""; /** * Defines a special count query that shall be used for pagination queries to look up the total number of elements for * a page. If none is configured we will derive the count query from the original query or {@link #countProjection()} * query if any. Alias for {@link Query#countQuery()}. */ @AliasFor(annotation = Query.class) String countQuery() default ""; /** * Defines the projection part of the count query that is generated for pagination. If neither {@link #countQuery()} * nor {@code countProjection()} is configured we will derive the count query from the original query. Alias for * {@link Query#countProjection()}. */ @AliasFor(annotation = Query.class) String countProjection() default ""; /** * The named query to be used. If not defined, a {@link jakarta.persistence.NamedQuery} with name of * {@code ${domainClass}.${queryMethodName}} will be used. Alias for {@link Query#name()}. */ @AliasFor(annotation = Query.class) String name() default ""; /** * Returns the name of the {@link jakarta.persistence.NamedQuery} to be used to execute count queries when pagination * is used. Will default to the named query name configured suffixed by {@code .count}. Alias for * {@link Query#countName()}. */ @AliasFor(annotation = Query.class) String countName() default ""; /** * Define a {@link QueryRewriter} that should be applied to the query string after the query is fully assembled. Alias * for {@link Query#queryRewriter()}. */ @AliasFor(annotation = Query.class) Class<? extends QueryRewriter> queryRewriter() default QueryRewriter.IdentityQueryRewriter.class; /** * Name of the {@link jakarta.persistence.SqlResultSetMapping @SqlResultSetMapping(name)} to apply for this query. */ String sqlResultSetMapping() default ""; }
NativeQuery
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/targetclass/mixed/AroundInvokeOnTargetClassAndOutsideAndManySuperclassesWithOverridesTest.java
{ "start": 779, "end": 1259 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(MyBean.class, MyInterceptorBinding.class, MyInterceptor.class); @Test public void test() { ArcContainer arc = Arc.container(); MyBean bean = arc.instance(MyBean.class).get(); assertEquals("super-outside: outside: super-target: target: foobar", bean.doSomething()); } static
AroundInvokeOnTargetClassAndOutsideAndManySuperclassesWithOverridesTest
java
elastic__elasticsearch
x-pack/plugin/searchable-snapshots/src/main/java/org/elasticsearch/xpack/searchablesnapshots/allocation/SearchableSnapshotIndexFoldersDeletionListener.java
{ "start": 1565, "end": 5253 }
class ____ implements IndexStorePlugin.IndexFoldersDeletionListener { private static final Logger logger = LogManager.getLogger(SearchableSnapshotIndexEventListener.class); private final Supplier<CacheService> cacheServiceSupplier; private final Supplier<SharedBlobCacheService<CacheKey>> frozenCacheServiceSupplier; public SearchableSnapshotIndexFoldersDeletionListener( Supplier<CacheService> cacheServiceSupplier, Supplier<SharedBlobCacheService<CacheKey>> frozenCacheServiceSupplier ) { this.cacheServiceSupplier = Objects.requireNonNull(cacheServiceSupplier); this.frozenCacheServiceSupplier = Objects.requireNonNull(frozenCacheServiceSupplier); } @Override public void beforeIndexFoldersDeleted( Index index, IndexSettings indexSettings, Path[] indexPaths, IndexRemovalReason indexRemovalReason ) { if (indexSettings.getIndexMetadata().isSearchableSnapshot()) { for (int shard = 0; shard < indexSettings.getNumberOfShards(); shard++) { markShardAsEvictedInCache(new ShardId(index, shard), indexSettings, indexRemovalReason); } } } @Override public void beforeShardFoldersDeleted( ShardId shardId, IndexSettings indexSettings, Path[] shardPaths, IndexRemovalReason indexRemovalReason ) { if (indexSettings.getIndexMetadata().isSearchableSnapshot()) { markShardAsEvictedInCache(shardId, indexSettings, indexRemovalReason); } } private void markShardAsEvictedInCache(ShardId shardId, IndexSettings indexSettings, IndexRemovalReason indexRemovalReason) { final CacheService cacheService = this.cacheServiceSupplier.get(); assert cacheService != null : "cache service not initialized"; logger.debug("{} marking shard as evicted in searchable snapshots cache (reason: cache files deleted from disk)", shardId); cacheService.markShardAsEvictedInCache( SNAPSHOT_SNAPSHOT_ID_SETTING.get(indexSettings.getSettings()), SNAPSHOT_INDEX_NAME_SETTING.get(indexSettings.getSettings()), shardId ); // Only partial searchable snapshots use the shared blob cache. if (indexSettings.getIndexMetadata().isPartialSearchableSnapshot()) { switch (indexRemovalReason) { // The index was deleted, it's not coming back - we can evict asynchronously case DELETED -> { final SharedBlobCacheService<CacheKey> sharedBlobCacheService = SearchableSnapshotIndexFoldersDeletionListener.this.frozenCacheServiceSupplier.get(); assert sharedBlobCacheService != null : "frozen cache service not initialized"; sharedBlobCacheService.forceEvictAsync(SearchableSnapshots.forceEvictPredicate(shardId, indexSettings.getSettings())); } // An error occurred - we should eagerly clear the state case FAILURE -> { final SharedBlobCacheService<CacheKey> sharedBlobCacheService = SearchableSnapshotIndexFoldersDeletionListener.this.frozenCacheServiceSupplier.get(); assert sharedBlobCacheService != null : "frozen cache service not initialized"; sharedBlobCacheService.forceEvict(SearchableSnapshots.forceEvictPredicate(shardId, indexSettings.getSettings())); } // Any other reason - we let the cache entries expire naturally } } } }
SearchableSnapshotIndexFoldersDeletionListener
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/fielddata/AbstractGeoFieldDataTestCase.java
{ "start": 1084, "end": 3157 }
class ____ extends AbstractFieldDataImplTestCase { @Override protected abstract String getFieldDataType(); protected Field randomGeoPointField(String fieldName, Field.Store store) { Point point = GeometryTestUtils.randomPoint(); return new LatLonDocValuesField(fieldName, point.getLat(), point.getLon()); } @Override protected boolean hasDocValues() { return true; } @Override protected long minRamBytesUsed() { return 0; } @Override protected void fillAllMissing() throws Exception { Document d = new Document(); d.add(new StringField("_id", "1", Field.Store.NO)); writer.addDocument(d); d = new Document(); d.add(new StringField("_id", "2", Field.Store.NO)); writer.addDocument(d); d = new Document(); d.add(new StringField("_id", "3", Field.Store.NO)); writer.addDocument(d); } @Override public void testSortMultiValuesFields() { assumeFalse("Only test on non geo_point fields", getFieldDataType().equals("geo_point")); } protected void assertValues(MultiGeoPointValues values, int docId) throws IOException { assertValues(values, docId, false); } protected void assertMissing(MultiGeoPointValues values, int docId) throws IOException { assertValues(values, docId, true); } private void assertValues(MultiGeoPointValues values, int docId, boolean missing) throws IOException { assertEquals(missing == false, values.advanceExact(docId)); if (missing == false) { final int docCount = values.docValueCount(); for (int i = 0; i < docCount; ++i) { final GeoPoint point = values.nextValue(); assertThat(point.lat(), allOf(greaterThanOrEqualTo(GeoUtils.MIN_LAT), lessThanOrEqualTo(GeoUtils.MAX_LAT))); assertThat(point.lon(), allOf(greaterThanOrEqualTo(GeoUtils.MIN_LON), lessThanOrEqualTo(GeoUtils.MAX_LON))); } } } }
AbstractGeoFieldDataTestCase
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/heap/AbstractHeapAppendingState.java
{ "start": 1392, "end": 2552 }
class ____<K, N, IN, SV, OUT> extends AbstractHeapState<K, N, SV> implements InternalAppendingState<K, N, IN, SV, OUT> { /** * Creates a new key/value state for the given hash map of key/value pairs. * * @param stateTable The state table for which this state is associated to. * @param keySerializer The serializer for the keys. * @param valueSerializer The serializer for the state. * @param namespaceSerializer The serializer for the namespace. * @param defaultValue The default value for the state. */ AbstractHeapAppendingState( StateTable<K, N, SV> stateTable, TypeSerializer<K> keySerializer, TypeSerializer<SV> valueSerializer, TypeSerializer<N> namespaceSerializer, SV defaultValue) { super(stateTable, keySerializer, valueSerializer, namespaceSerializer, defaultValue); } @Override public SV getInternal() { return stateTable.get(currentNamespace); } @Override public void updateInternal(SV valueToStore) { stateTable.put(currentNamespace, valueToStore); } }
AbstractHeapAppendingState
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyUtils.java
{ "start": 947, "end": 2257 }
class ____ { private RoleHierarchyUtils() { } /** * Converts the supplied {@link Map} of role name to implied role name(s) to a string * representation understood by {@link RoleHierarchyImpl#setHierarchy(String)}. The * map key is the role name and the map value is a {@link List} of implied role * name(s). * @param roleHierarchyMap the mapping(s) of role name to implied role name(s) * @return a string representation of a role hierarchy * @throws IllegalArgumentException if roleHierarchyMap is null or empty or if a role * name is null or empty or if an implied role name(s) is null or empty * @deprecated please see {@link RoleHierarchyImpl#setHierarchy} deprecation notice */ @Deprecated public static String roleHierarchyFromMap(Map<String, List<String>> roleHierarchyMap) { Assert.notEmpty(roleHierarchyMap, "roleHierarchyMap cannot be empty"); StringWriter result = new StringWriter(); PrintWriter writer = new PrintWriter(result); roleHierarchyMap.forEach((role, impliedRoles) -> { Assert.hasLength(role, "role name must be supplied"); Assert.notEmpty(impliedRoles, "implied role name(s) cannot be empty"); for (String impliedRole : impliedRoles) { writer.println(role + " > " + impliedRole); } }); return result.toString(); } }
RoleHierarchyUtils
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/genericsinheritance/Child.java
{ "start": 307, "end": 575 }
class ____<P extends Parent> { @Id Long id; @ManyToOne P parent; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public P getParent() { return parent; } public void setParent(P parent) { this.parent = parent; } }
Child
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/google/SetGenerators.java
{ "start": 4706, "end": 5015 }
class ____ extends TestStringSetGenerator { @SuppressWarnings("DistinctVarargsChecker") // deliberately testing deduplication @Override protected Set<String> create(String[] elements) { return ImmutableSet.of(elements[0], elements[0]); } } public static
DegeneratedImmutableSetGenerator
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/BeanCreationNotAllowedException.java
{ "start": 927, "end": 1244 }
class ____ extends BeanCreationException { /** * Create a new BeanCreationNotAllowedException. * @param beanName the name of the bean requested * @param msg the detail message */ public BeanCreationNotAllowedException(String beanName, String msg) { super(beanName, msg); } }
BeanCreationNotAllowedException
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/binding/MissingNamespaceMapper.java
{ "start": 693, "end": 746 }
interface ____ { void get(); }
MissingNamespaceMapper
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeReference.java
{ "start": 24706, "end": 31759 }
class ____ extends INodeReference { /** * Record the latest snapshot of the dst subtree before the rename, * i.e. this reference is NOT in that snapshot. For * later operations on the moved/renamed files/directories, if the latest * snapshot is after this dstSnapshot, changes will be recorded to the * latest snapshot. Otherwise changes will be recorded to the snapshot * belonging to the src of the rename. * * {@link Snapshot#NO_SNAPSHOT_ID} means no dstSnapshot (e.g., src of the * first-time rename). */ private final int dstSnapshotId; @Override public final int getDstSnapshotId() { return dstSnapshotId; } public DstReference(INodeDirectory parent, WithCount referred, final int dstSnapshotId) { super(parent, referred); this.dstSnapshotId = dstSnapshotId; referred.addReference(this); INodeReferenceValidation.add(this, DstReference.class); } String getDstDetails() { return getClass().getSimpleName() + "[" + getLocalName() + ", dstSnapshot=" + dstSnapshotId + "]"; } @Override void assertReferences() { final INode ref = getReferredINode(); final String err; if (ref instanceof WithCount) { if (ref.getParentReference() == this) { return; } else { err = "OBJECT MISMATCH, ref.getParentReference() != this"; } } else { err = "UNEXPECTED CLASS, expecting WithCount"; } throw new IllegalStateException(err + ":" + "\n ref: " + (ref == null? null : ref.toDetailString()) + "\n this: " + this.toDetailString()); } @Override public void cleanSubtree(ReclaimContext reclaimContext, int snapshot, int prior) { if (snapshot == Snapshot.CURRENT_STATE_ID && prior == Snapshot.NO_SNAPSHOT_ID) { destroyAndCollectBlocks(reclaimContext); } else { // if prior is NO_SNAPSHOT_ID, we need to check snapshot belonging to // the previous WithName instance if (prior == Snapshot.NO_SNAPSHOT_ID) { prior = getPriorSnapshot(this); } // if prior is not NO_SNAPSHOT_ID, and prior is not before the // to-be-deleted snapshot, we can quit here and leave the snapshot // deletion work to the src tree of rename if (snapshot != Snapshot.CURRENT_STATE_ID && prior != Snapshot.NO_SNAPSHOT_ID && Snapshot.ID_INTEGER_COMPARATOR.compare(snapshot, prior) <= 0) { return; } getReferredINode().cleanSubtree(reclaimContext, snapshot, prior); } } /** * When dstSnapshotId >= snapshotToBeDeleted, * this reference is not in snapshotToBeDeleted. * This reference should not be destroyed. * * @param context to {@link ReclaimContext#getSnapshotIdToBeDeleted()} */ private void shouldDestroy(ReclaimContext context) { final int snapshotToBeDeleted = context.getSnapshotIdToBeDeleted(); if (snapshotToBeDeleted == Snapshot.CURRENT_STATE_ID || snapshotToBeDeleted > dstSnapshotId) { return; } LOG.warn("Try to destroy a DstReference with dstSnapshotId = {}" + " >= snapshotToBeDeleted = {}", dstSnapshotId, snapshotToBeDeleted); LOG.warn(" dstRef: {}", toDetailString()); final INode r = getReferredINode().asReference().getReferredINode(); LOG.warn(" referred: {}", r.toDetailString()); } /** * {@inheritDoc} * <br> * To destroy a DstReference node, we first remove its link with the * referred node. If the reference number of the referred node is &lt;= 0, * we destroy the subtree of the referred node. Otherwise, we clean the * referred node's subtree and delete everything created after the last * rename operation, i.e., everything outside of the scope of the prior * WithName nodes. * @param reclaimContext */ @Override public void destroyAndCollectBlocks(ReclaimContext reclaimContext) { shouldDestroy(reclaimContext); // since we count everything of the subtree for the quota usage of a // dst reference node, here we should just simply do a quota computation. // then to avoid double counting, we pass a different QuotaDelta to other // calls reclaimContext.quotaDelta().add(computeQuotaUsage(reclaimContext.bsps)); ReclaimContext newCtx = reclaimContext.getCopy(); if (removeReference(this) <= 0) { getReferredINode().destroyAndCollectBlocks(newCtx); } else { // we will clean everything, including files, directories, and // snapshots, that were created after this prior snapshot int prior = getPriorSnapshot(this); // prior must be non-null, otherwise we do not have any previous // WithName nodes, and the reference number will be 0. Preconditions.checkState(prior != Snapshot.NO_SNAPSHOT_ID); // identify the snapshot created after prior int snapshot = getSelfSnapshot(prior); INode referred = getReferredINode().asReference().getReferredINode(); if (referred.isFile()) { // if referred is a file, it must be a file with snapshot since we did // recordModification before the rename INodeFile file = referred.asFile(); Preconditions.checkState(file.isWithSnapshot()); // make sure we mark the file as deleted file.getFileWithSnapshotFeature().deleteCurrentFile(); // when calling cleanSubtree of the referred node, since we // compute quota usage updates before calling this destroy // function, we use true for countDiffChange referred.cleanSubtree(newCtx, snapshot, prior); } else if (referred.isDirectory()) { // similarly, if referred is a directory, it must be an // INodeDirectory with snapshot INodeDirectory dir = referred.asDirectory(); Preconditions.checkState(dir.isWithSnapshot()); DirectoryWithSnapshotFeature.destroyDstSubtree(newCtx, dir, snapshot, prior); } } } private int getSelfSnapshot(final int prior) { WithCount wc = (WithCount) getReferredINode().asReference(); INode referred = wc.getReferredINode(); int lastSnapshot = Snapshot.CURRENT_STATE_ID; if (referred.isFile() && referred.asFile().isWithSnapshot()) { lastSnapshot = referred.asFile().getDiffs().getLastSnapshotId(); } else if (referred.isDirectory()) { DirectoryWithSnapshotFeature sf = referred.asDirectory() .getDirectoryWithSnapshotFeature(); if (sf != null) { lastSnapshot = sf.getLastSnapshotId(); } } if (lastSnapshot != Snapshot.CURRENT_STATE_ID && lastSnapshot != prior) { return lastSnapshot; } else { return Snapshot.CURRENT_STATE_ID; } } } }
DstReference
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RBucket.java
{ "start": 858, "end": 7351 }
interface ____<V> extends RExpirable, RBucketAsync<V> { /** * Returns size of object in bytes. * * @return object size */ long size(); /** * Retrieves element stored in the holder. * * @return element */ V get(); /** * Retrieves element in the holder and removes it. * * @return element */ V getAndDelete(); /** * Use {@link #setIfAbsent(Object)} instead * * @param value - value to set * @return {@code true} if successful, or {@code false} if * element was already set */ @Deprecated boolean trySet(V value); /** * Use {@link #setIfAbsent(Object, Duration)} instead * * @param value - value to set * @param timeToLive - time to live interval * @param timeUnit - unit of time to live interval * @return {@code true} if successful, or {@code false} if * element was already set */ @Deprecated boolean trySet(V value, long timeToLive, TimeUnit timeUnit); /** * Sets value only if object holder doesn't exist. * * @param value - value to set * @return {@code true} if successful, or {@code false} if * element was already set */ boolean setIfAbsent(V value); /** * Sets value with defined duration only if object holder doesn't exist. * * @param value value to set * @param duration expiration duration * @return {@code true} if successful, or {@code false} if * element was already set */ boolean setIfAbsent(V value, Duration duration); /** * Sets value only if object holder already exists. * * @param value - value to set * @return {@code true} if successful, or {@code false} if * element wasn't set */ boolean setIfExists(V value); /** * Use {@link #setIfExists(Object, Duration)} instead * * @param value - value to set * @param timeToLive - time to live interval * @param timeUnit - unit of time to live interval * @return {@code true} if successful, or {@code false} if * element wasn't set */ @Deprecated boolean setIfExists(V value, long timeToLive, TimeUnit timeUnit); /** * Sets <code>value</code> with expiration <code>duration</code> only if object holder already exists. * * @param value value to set * @param duration expiration duration * @return {@code true} if successful, or {@code false} if * element wasn't set */ boolean setIfExists(V value, Duration duration); /** * Atomically sets the value to the given updated value * only if serialized state of the current value equals * to serialized state of the expected value. * * @param expect the expected value * @param update the new value * @return {@code true} if successful; or {@code false} if the actual value * was not equal to the expected value. */ boolean compareAndSet(V expect, V update); /** * Retrieves current element in the holder and replaces it with <code>newValue</code>. * * @param newValue - value to set * @return previous value */ V getAndSet(V newValue); /** * Use {@link #getAndSet(Object, Duration)} instead * * @param value - value to set * @param timeToLive - time to live interval * @param timeUnit - unit of time to live interval * @return previous value */ @Deprecated V getAndSet(V value, long timeToLive, TimeUnit timeUnit); /** * Retrieves current element in the holder and replaces it * with <code>value</code> with defined expiration <code>duration</code>. * * @param value value to set * @param duration expiration duration * @return previous value */ V getAndSet(V value, Duration duration); /** * Retrieves current element in the holder and sets an expiration duration for it. * <p> * Requires <b>Redis 6.2.0 and higher.</b> * * @param duration of object time to live interval * @return element */ V getAndExpire(Duration duration); /** * Retrieves current element in the holder and sets an expiration date for it. * <p> * Requires <b>Redis 6.2.0 and higher.</b> * * @param time of exact object expiration moment * @return element */ V getAndExpire(Instant time); /** * Retrieves current element in the holder and clears expiration date set before. * <p> * Requires <b>Redis 6.2.0 and higher.</b> * * @return element */ V getAndClearExpire(); /** * Stores element into the holder. * * @param value - value to set */ void set(V value); /** * Use {@link #set(Object, Duration)} instead * * @param value - value to set * @param timeToLive - time to live interval * @param timeUnit - unit of time to live interval */ @Deprecated void set(V value, long timeToLive, TimeUnit timeUnit); /** * Stores <code>value</code> into the holder with defined expiration <code>duration</code>. * * @param value value to set * @param duration expiration duration */ void set(V value, Duration duration); /** * Set value and keep existing TTL. * <p> * Requires <b>Redis 6.0.0 and higher.</b> * * @param value - value to set */ void setAndKeepTTL(V value); /** * Adds object event listener * * @see org.redisson.api.listener.TrackingListener * @see org.redisson.api.ExpiredObjectListener * @see org.redisson.api.DeletedObjectListener * @see org.redisson.api.listener.SetObjectListener * * @param listener - object event listener * @return listener id */ int addListener(ObjectListener listener); /** * Returns the common part of the data stored in this bucket * and a bucket defined by the <code>name</code> * * @param name second bucket * @return common part of the data */ V findCommon(String name); /** * Returns the length of the common part of the data stored in this bucket * and a bucket defined by the <code>name</code> * * @param name second bucket * @return common part of the data */ long findCommonLength(String name); }
RBucket
java
netty__netty
codec-socks/src/main/java/io/netty/handler/codec/socks/SocksCmdResponseDecoder.java
{ "start": 1183, "end": 3996 }
class ____ extends ReplayingDecoder<State> { private SocksCmdStatus cmdStatus; private SocksAddressType addressType; public SocksCmdResponseDecoder() { super(State.CHECK_PROTOCOL_VERSION); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception { switch (state()) { case CHECK_PROTOCOL_VERSION: { if (byteBuf.readByte() != SocksProtocolVersion.SOCKS5.byteValue()) { out.add(SocksCommonUtils.UNKNOWN_SOCKS_RESPONSE); break; } checkpoint(State.READ_CMD_HEADER); } case READ_CMD_HEADER: { cmdStatus = SocksCmdStatus.valueOf(byteBuf.readByte()); byteBuf.skipBytes(1); // reserved addressType = SocksAddressType.valueOf(byteBuf.readByte()); checkpoint(State.READ_CMD_ADDRESS); } case READ_CMD_ADDRESS: { switch (addressType) { case IPv4: { String host = NetUtil.intToIpAddress(ByteBufUtil.readIntBE(byteBuf)); int port = ByteBufUtil.readUnsignedShortBE(byteBuf); out.add(new SocksCmdResponse(cmdStatus, addressType, host, port)); break; } case DOMAIN: { int fieldLength = byteBuf.readByte(); String host = byteBuf.readString(fieldLength, CharsetUtil.US_ASCII); int port = ByteBufUtil.readUnsignedShortBE(byteBuf); out.add(new SocksCmdResponse(cmdStatus, addressType, host, port)); break; } case IPv6: { byte[] bytes = new byte[16]; byteBuf.readBytes(bytes); String host = SocksCommonUtils.ipv6toStr(bytes); int port = ByteBufUtil.readUnsignedShortBE(byteBuf); out.add(new SocksCmdResponse(cmdStatus, addressType, host, port)); break; } case UNKNOWN: { out.add(SocksCommonUtils.UNKNOWN_SOCKS_RESPONSE); break; } default: { throw new Error("Unexpected address type: " + addressType); } } break; } default: { throw new Error("Unexpected response decoder type: " + state()); } } ctx.pipeline().remove(this); } @UnstableApi public
SocksCmdResponseDecoder
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/AbstractAbfsIntegrationTest.java
{ "start": 4236, "end": 31423 }
class ____ extends AbstractAbfsTestWithTimeout { private static final Logger LOG = LoggerFactory.getLogger(AbstractAbfsIntegrationTest.class); private boolean isIPAddress; private NativeAzureFileSystem wasb; private AzureBlobFileSystem abfs; private String abfsScheme; private Configuration rawConfig; private AbfsConfiguration abfsConfig; private String fileSystemName; private String accountName; private String testUrl; private AuthType authType; private boolean useConfiguredFileSystem = false; private boolean usingFilesystemForSASTests = false; public static final int SHORTENED_GUID_LEN = 12; protected AbstractAbfsIntegrationTest() throws Exception { fileSystemName = TEST_CONTAINER_PREFIX + UUID.randomUUID().toString(); rawConfig = new Configuration(); rawConfig.addResource(TEST_CONFIGURATION_FILE_NAME); this.accountName = rawConfig.get(FS_AZURE_ACCOUNT_NAME); if (accountName == null) { // check if accountName is set using different config key accountName = rawConfig.get(FS_AZURE_ABFS_ACCOUNT_NAME); } assumeThat(accountName) .as("Not set: " + FS_AZURE_ABFS_ACCOUNT_NAME) .isNotBlank(); final String abfsUrl = this.getFileSystemName() + "@" + this.getAccountName(); URI defaultUri = null; abfsConfig = new AbfsConfiguration(rawConfig, accountName, identifyAbfsServiceTypeFromUrl(abfsUrl)); authType = abfsConfig.getEnum(FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME, AuthType.SharedKey); assumeValidAuthConfigsPresent(); abfsScheme = authType == AuthType.SharedKey ? FileSystemUriSchemes.ABFS_SCHEME : FileSystemUriSchemes.ABFS_SECURE_SCHEME; try { defaultUri = new URI(abfsScheme, abfsUrl, null, null, null); } catch (Exception ex) { throw new AssertionError(ex); } this.testUrl = defaultUri.toString(); abfsConfig.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, defaultUri.toString()); abfsConfig.setBoolean(AZURE_CREATE_REMOTE_FILESYSTEM_DURING_INITIALIZATION, true); if (isAppendBlobEnabled()) { String appendblobDirs = this.testUrl + "," + abfsConfig.get(FS_AZURE_CONTRACT_TEST_URI); rawConfig.set(FS_AZURE_APPEND_BLOB_KEY, appendblobDirs); } // For testing purposes, an IP address and port may be provided to override // the host specified in the FileSystem URI. Also note that the format of // the Azure Storage Service URI changes from // http[s]://[account][domain-suffix]/[filesystem] to // http[s]://[ip]:[port]/[account]/[filesystem]. String endPoint = abfsConfig.get(AZURE_ABFS_ENDPOINT); if (endPoint != null && endPoint.contains(":") && endPoint.split(":").length == 2) { this.isIPAddress = true; } else { this.isIPAddress = false; } // For tests, we want to enforce checksum validation so that any regressions can be caught. abfsConfig.setIsChecksumValidationEnabled(true); } protected boolean getIsNamespaceEnabled(AzureBlobFileSystem fs) throws IOException { return fs.getIsNamespaceEnabled(getTestTracingContext(fs, false)); } public static TracingContext getSampleTracingContext(AzureBlobFileSystem fs, boolean needsPrimaryReqId) { String correlationId, fsId; TracingHeaderFormat format; correlationId = "test-corr-id"; fsId = "test-filesystem-id"; format = TracingHeaderFormat.ALL_ID_FORMAT; return new TracingContext(correlationId, fsId, FSOperationType.TEST_OP, needsPrimaryReqId, format, null); } public TracingContext getTestTracingContext(AzureBlobFileSystem fs, boolean needsPrimaryReqId) { String correlationId, fsId; TracingHeaderFormat format; if (fs == null) { correlationId = "test-corr-id"; fsId = "test-filesystem-id"; format = TracingHeaderFormat.ALL_ID_FORMAT; } else { AbfsConfiguration abfsConf = fs.getAbfsStore().getAbfsConfiguration(); correlationId = abfsConf.getClientCorrelationId(); fsId = fs.getFileSystemId(); format = abfsConf.getTracingHeaderFormat(); } return new TracingContext(correlationId, fsId, FSOperationType.TEST_OP, needsPrimaryReqId, format, null); } @BeforeEach public void setup() throws Exception { //Create filesystem first to make sure getWasbFileSystem() can return an existing filesystem. createFileSystem(); // Only live account without namespace support can run ABFS&WASB // compatibility tests if (!isIPAddress && (abfsConfig.getAuthType(accountName) != AuthType.SAS) && (abfsConfig.getAuthType(accountName) != AuthType.UserboundSASWithOAuth) && !abfs.getIsNamespaceEnabled(getTestTracingContext( getFileSystem(), false))) { final URI wasbUri = new URI( abfsUrlToWasbUrl(getTestUrl(), abfsConfig.isHttpsAlwaysUsed())); final AzureNativeFileSystemStore azureNativeFileSystemStore = new AzureNativeFileSystemStore(); // update configuration with wasb credentials String accountNameWithoutDomain = accountName.split("\\.")[0]; String wasbAccountName = accountNameWithoutDomain + WASB_ACCOUNT_NAME_DOMAIN_SUFFIX; String keyProperty = FS_AZURE_ACCOUNT_KEY + "." + wasbAccountName; if (rawConfig.get(keyProperty) == null) { rawConfig.set(keyProperty, getAccountKey()); } rawConfig.set(APPEND_SUPPORT_ENABLE_PROPERTY_NAME, TRUE); azureNativeFileSystemStore.initialize( wasbUri, rawConfig, new AzureFileSystemInstrumentation(rawConfig)); wasb = new NativeAzureFileSystem(azureNativeFileSystemStore); wasb.initialize(wasbUri, rawConfig); } } @AfterEach public void teardown() throws Exception { try { IOUtils.closeStream(wasb); wasb = null; if (abfs == null) { return; } TracingContext tracingContext = getTestTracingContext(getFileSystem(), false); if (usingFilesystemForSASTests) { abfsConfig.set(FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME, AuthType.SharedKey.name()); AzureBlobFileSystem tempFs = (AzureBlobFileSystem) FileSystem.newInstance(rawConfig); tempFs.getAbfsStore().deleteFilesystem(tracingContext); } else if (!useConfiguredFileSystem) { // Delete all uniquely created filesystem from the account final AzureBlobFileSystemStore abfsStore = abfs.getAbfsStore(); abfsStore.deleteFilesystem(tracingContext); AbfsRestOperationException ex = intercept(AbfsRestOperationException.class, new Callable<Hashtable<String, String>>() { @Override public Hashtable<String, String> call() throws Exception { return abfsStore.getFilesystemProperties(tracingContext); } }); if (FILE_SYSTEM_NOT_FOUND.getStatusCode() != ex.getStatusCode()) { LOG.warn("Deleted test filesystem may still exist: {}", abfs, ex); } } } catch (Exception e) { LOG.warn("During cleanup: {}", e, e); } finally { IOUtils.closeStream(abfs); abfs = null; } } public AccessTokenProvider getAccessTokenProvider(final AzureBlobFileSystem fs) { return ITestAbfsClient.getAccessTokenProvider(fs.getAbfsStore().getClient()); } public void loadConfiguredFileSystem() throws Exception { // disable auto-creation of filesystem abfsConfig.setBoolean(AZURE_CREATE_REMOTE_FILESYSTEM_DURING_INITIALIZATION, false); // AbstractAbfsIntegrationTest always uses a new instance of FileSystem, // need to disable that and force filesystem provided in test configs. assumeValidTestConfigPresent(this.getRawConfiguration(), FS_AZURE_CONTRACT_TEST_URI); String[] authorityParts = (new URI(rawConfig.get(FS_AZURE_CONTRACT_TEST_URI))).getRawAuthority().split( AbfsHttpConstants.AZURE_DISTRIBUTED_FILE_SYSTEM_AUTHORITY_DELIMITER, 2); this.fileSystemName = authorityParts[0]; // Reset URL with configured filesystem final String abfsUrl = this.getFileSystemName() + "@" + this.getAccountName(); URI defaultUri = null; defaultUri = new URI(abfsScheme, abfsUrl, null, null, null); this.testUrl = defaultUri.toString(); abfsConfig.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, defaultUri.toString()); useConfiguredFileSystem = true; } /** * Create a filesystem for SAS tests using the SharedKey authentication. * We do not allow filesystem creation with SAS because certain type of SAS do not have * required permissions, and it is not known what type of SAS is configured by user. * @throws Exception */ protected void createFilesystemForSASTests() throws Exception { createFilesystemWithTestFileForSASTests(null); } /** * Create a filesystem for SAS tests along with a test file using SharedKey authentication. * We do not allow filesystem creation with SAS because certain type of SAS do not have * required permissions, and it is not known what type of SAS is configured by user. * @param testPath path of the test file. * @throws Exception */ protected void createFilesystemWithTestFileForSASTests(Path testPath) throws Exception { try (AzureBlobFileSystem tempFs = (AzureBlobFileSystem) FileSystem.newInstance(rawConfig)){ ContractTestUtils.assertPathExists(tempFs, "This path should exist", new Path("/")); if (testPath != null) { tempFs.create(testPath).close(); } abfsConfig.set(FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME, AuthType.SAS.name()); usingFilesystemForSASTests = true; } } /** * Create a filesystem for user bound SAS tests using the SharedKey authentication. * * @throws Exception */ protected void createFilesystemForUserBoundSASTests() throws Exception{ try (AzureBlobFileSystem tempFs = (AzureBlobFileSystem) FileSystem.newInstance(rawConfig)){ ContractTestUtils.assertPathExists(tempFs, "This path should exist", new Path("/")); abfsConfig.set(FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME, AuthType.UserboundSASWithOAuth.name()); usingFilesystemForSASTests = true; } } public AzureBlobFileSystem getFileSystem() throws IOException { return abfs; } public AzureBlobFileSystem getFileSystem(Configuration configuration) throws Exception{ final AzureBlobFileSystem fs = (AzureBlobFileSystem) FileSystem.get(configuration); return fs; } public AzureBlobFileSystem getFileSystem(String abfsUri) throws Exception { abfsConfig.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, abfsUri); final AzureBlobFileSystem fs = (AzureBlobFileSystem) FileSystem.get(rawConfig); return fs; } /** * Creates the filesystem; updates the {@link #abfs} field. * @return the created filesystem. * @throws IOException failure during create/init. */ public AzureBlobFileSystem createFileSystem() throws IOException { if (abfs == null) { abfs = (AzureBlobFileSystem) FileSystem.newInstance(rawConfig); } return abfs; } protected NativeAzureFileSystem getWasbFileSystem() { return wasb; } protected String getHostName() { // READ FROM ENDPOINT, THIS IS CALLED ONLY WHEN TESTING AGAINST DEV-FABRIC String endPoint = abfsConfig.get(AZURE_ABFS_ENDPOINT); return endPoint.split(":")[0]; } protected void setTestUrl(String testUrl) { this.testUrl = testUrl; } protected String getTestUrl() { return testUrl; } protected void setFileSystemName(String fileSystemName) { this.fileSystemName = fileSystemName; } protected String getMethodName() { return methodName.getMethodName(); } protected String getFileSystemName() { return fileSystemName; } protected String getAccountName() { return this.accountName; } protected String getAccountKey() { return abfsConfig.get(FS_AZURE_ACCOUNT_KEY); } public AbfsConfiguration getConfiguration() { return abfsConfig; } public AbfsConfiguration getConfiguration(AzureBlobFileSystem fs) { return fs.getAbfsStore().getAbfsConfiguration(); } public Map<String, Long> getInstrumentationMap(AzureBlobFileSystem fs) { return fs.getInstrumentationMap(); } public Configuration getRawConfiguration() { return abfsConfig.getRawConfiguration(); } public AuthType getAuthType() { return this.authType; } public String getAbfsScheme() { return this.abfsScheme; } protected boolean isIPAddress() { return isIPAddress; } /** * Write a buffer to a file. * @param path path * @param buffer buffer * @throws IOException failure */ protected void write(Path path, byte[] buffer) throws IOException { ContractTestUtils.writeDataset(getFileSystem(), path, buffer, buffer.length, CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_DEFAULT, false); } /** * Touch a file in the test store. Will overwrite any existing file. * @param path path * @throws IOException failure. */ protected void touch(Path path) throws IOException { ContractTestUtils.touch(getFileSystem(), path); } protected static String wasbUrlToAbfsUrl(final String wasbUrl) { return convertTestUrls( wasbUrl, FileSystemUriSchemes.WASB_SCHEME, FileSystemUriSchemes.WASB_SECURE_SCHEME, FileSystemUriSchemes.WASB_DNS_PREFIX, FileSystemUriSchemes.ABFS_SCHEME, FileSystemUriSchemes.ABFS_SECURE_SCHEME, FileSystemUriSchemes.ABFS_DNS_PREFIX, false); } protected static String abfsUrlToWasbUrl(final String abfsUrl, final boolean isAlwaysHttpsUsed) { return convertTestUrls( abfsUrl, FileSystemUriSchemes.ABFS_SCHEME, FileSystemUriSchemes.ABFS_SECURE_SCHEME, FileSystemUriSchemes.ABFS_DNS_PREFIX, FileSystemUriSchemes.WASB_SCHEME, FileSystemUriSchemes.WASB_SECURE_SCHEME, FileSystemUriSchemes.WASB_DNS_PREFIX, isAlwaysHttpsUsed); } private AbfsServiceType identifyAbfsServiceTypeFromUrl(String defaultUri) { if (defaultUri.contains(ABFS_BLOB_DOMAIN_NAME)) { return AbfsServiceType.BLOB; } return AbfsServiceType.DFS; } private static String convertTestUrls( final String url, final String fromNonSecureScheme, final String fromSecureScheme, final String fromDnsPrefix, final String toNonSecureScheme, final String toSecureScheme, final String toDnsPrefix, final boolean isAlwaysHttpsUsed) { String data = null; if (url.startsWith(fromNonSecureScheme + "://") && isAlwaysHttpsUsed) { data = url.replace(fromNonSecureScheme + "://", toSecureScheme + "://"); } else if (url.startsWith(fromNonSecureScheme + "://")) { data = url.replace(fromNonSecureScheme + "://", toNonSecureScheme + "://"); } else if (url.startsWith(fromSecureScheme + "://")) { data = url.replace(fromSecureScheme + "://", toSecureScheme + "://"); } if (data != null) { data = data.replace("." + fromDnsPrefix + ".", "." + toDnsPrefix + "."); } return data; } public Path getTestPath() { Path path = new Path(UriUtils.generateUniqueTestPath()); return path; } public AzureBlobFileSystemStore getAbfsStore(final AzureBlobFileSystem fs) { return fs.getAbfsStore(); } public AbfsClient getAbfsClient(final AzureBlobFileSystemStore abfsStore) { return abfsStore.getClient(); } public void setAbfsClient(AzureBlobFileSystemStore abfsStore, AbfsClient client) { abfsStore.setClient(client); } public Path makeQualified(Path path) throws java.io.IOException { return getFileSystem().makeQualified(path); } /** * Create a path under the test path provided by * {@link #getTestPath()}. * @param filepath path string in * @return a path qualified by the test filesystem * @throws IOException IO problems */ protected Path path(String filepath) throws IOException { return getFileSystem().makeQualified( new Path(getTestPath(), getUniquePath(filepath))); } /** * Generate a unique path using the given filepath. * @param filepath path string * @return unique path created from filepath and a GUID */ protected Path getUniquePath(String filepath) { if (filepath.equals("/")) { return new Path(filepath); } return new Path(filepath + StringUtils .right(UUID.randomUUID().toString(), SHORTENED_GUID_LEN)); } /** * Get any Delegation Token manager created by the filesystem. * @return the DT manager or null. * @throws IOException failure */ protected AbfsDelegationTokenManager getDelegationTokenManager() throws IOException { return getFileSystem().getDelegationTokenManager(); } /** * Generic create File and enabling AbfsOutputStream Flush. * * @param fs AzureBlobFileSystem that is initialised in the test. * @param path Path of the file to be created. * @return AbfsOutputStream for writing. * @throws AzureBlobFileSystemException */ protected AbfsOutputStream createAbfsOutputStreamWithFlushEnabled( AzureBlobFileSystem fs, Path path) throws IOException { AzureBlobFileSystemStore abfss = fs.getAbfsStore(); abfss.getAbfsConfiguration().setDisableOutputStreamFlush(false); return (AbfsOutputStream) abfss.createFile(path, fs.getFsStatistics(), true, FsPermission.getDefault(), FsPermission.getUMask(fs.getConf()), getTestTracingContext(fs, false)); } /** * Custom assertion for AbfsStatistics which have statistics, expected * value and map of statistics and value as its parameters. * @param statistic the AbfsStatistics which needs to be asserted. * @param expectedValue the expected value of the statistics. * @param metricMap map of (String, Long) with statistics name as key and * statistics value as map value. */ protected long assertAbfsStatistics(AbfsStatistic statistic, long expectedValue, Map<String, Long> metricMap) { assertEquals(expectedValue, (long) metricMap.get(statistic.getStatName()), "Mismatch in " + statistic.getStatName()); return expectedValue; } protected void assumeValidTestConfigPresent(final Configuration conf, final String key) { String configuredValue = conf.get(accountProperty(key, accountName), conf.get(key, "")); assumeThat(configuredValue) .as(String.format("Missing Required Test Config: %s.", key)) .isNotEmpty(); } protected void assumeValidAuthConfigsPresent() { final AuthType currentAuthType = getAuthType(); assumeThat(currentAuthType). as("SAS Based Authentication Not Allowed For Integration Tests"). isNotEqualTo(AuthType.SAS); assumeThat(currentAuthType). as("User-bound SAS Based Authentication Not Allowed For Integration Tests"). isNotEqualTo(AuthType.UserboundSASWithOAuth); if (currentAuthType == AuthType.SharedKey) { assumeValidTestConfigPresent(getRawConfiguration(), FS_AZURE_ACCOUNT_KEY); } else { assumeValidTestConfigPresent(getRawConfiguration(), FS_AZURE_ACCOUNT_TOKEN_PROVIDER_TYPE_PROPERTY_NAME); } } protected boolean isAppendBlobEnabled() { return getRawConfiguration().getBoolean(FS_AZURE_TEST_APPENDBLOB_ENABLED, false); } protected AbfsServiceType getAbfsServiceType() { return abfsConfig.getFsConfiguredServiceType(); } /** * Returns the service type to be used for Ingress Operations irrespective of account type. * Default value is the same as the service type configured for the file system. * @return the service type. */ public AbfsServiceType getIngressServiceType() { return abfsConfig.getIngressServiceType(); } /** * Create directory with implicit parent directory. * @param path path to create. Can be relative or absolute. */ protected void createAzCopyFolder(Path path) throws Exception { assumeBlobServiceType(); assumeValidTestConfigPresent(getRawConfiguration(), FS_AZURE_TEST_FIXED_SAS_TOKEN); String sasToken = getRawConfiguration().get(FS_AZURE_TEST_FIXED_SAS_TOKEN); AzcopyToolHelper azcopyHelper = AzcopyToolHelper.getInstance(sasToken); azcopyHelper.createFolderUsingAzcopy(getAzcopyAbsolutePath(path)); } /** * Create file with implicit parent directory. * @param path path to create. Can be relative or absolute. */ protected void createAzCopyFile(Path path) throws Exception { assumeBlobServiceType(); assumeValidTestConfigPresent(getRawConfiguration(), FS_AZURE_TEST_FIXED_SAS_TOKEN); String sasToken = getRawConfiguration().get(FS_AZURE_TEST_FIXED_SAS_TOKEN); AzcopyToolHelper azcopyHelper = AzcopyToolHelper.getInstance(sasToken); azcopyHelper.createFileUsingAzcopy(getAzcopyAbsolutePath(path)); } private String getAzcopyAbsolutePath(Path path) throws IOException { String pathFromContainerRoot = getFileSystem().makeQualified(path).toUri().getPath(); return HTTPS_SCHEME + COLON + FORWARD_SLASH + FORWARD_SLASH + accountName + FORWARD_SLASH + fileSystemName + pathFromContainerRoot; } /** * Utility method to assume that the test is running against a Blob service. * Otherwise, the test will be skipped. */ protected void assumeBlobServiceType() { assumeThat(getAbfsServiceType()). as("Blob service type is required for this test"). isEqualTo(AbfsServiceType.BLOB); } /** * Utility method to assume that the test is running against a DFS service. * Otherwise, the test will be skipped. */ protected void assumeDfsServiceType() { assumeThat(getAbfsServiceType()) .as("DFS service type is required for this test") .isEqualTo(AbfsServiceType.DFS); } /** * Utility method to assume that the test is running against a HNS Enabled account. * Otherwise, the test will be skipped. * @throws IOException if an error occurs while checking the account type. */ protected void assumeHnsEnabled() throws IOException { assumeHnsEnabled("HNS-Enabled account must be used for this test"); } /** * Utility method to assume that the test is running against a HNS Enabled account. * @param errorMessage error message to be displayed if the test is skipped. * @throws IOException if an error occurs while checking the account type. */ protected void assumeHnsEnabled(String errorMessage) throws IOException { assumeThat(getIsNamespaceEnabled(getFileSystem())).as(errorMessage).isTrue(); } /** * Utility method to assume that the test is running against a HNS Disabled account. * Otherwise, the test will be skipped. * @throws IOException if an error occurs while checking the account type. */ protected void assumeHnsDisabled() throws IOException { assumeHnsDisabled("HNS-Enabled account must not be used for this test"); } /** * Utility method to assume that the test is running against a HNS Disabled account. * @param message error message to be displayed if the test is skipped. * @throws IOException if an error occurs while checking the account type. */ protected void assumeHnsDisabled(String message) throws IOException { assumeThat(getIsNamespaceEnabled(getFileSystem())).as(message).isFalse(); } /** * Assert that the path contains the expected DNS suffix. * If service type is blob, then path should have blob domain name. * @param path to be asserted. */ protected void assertPathDns(Path path) { String expectedDns = getAbfsServiceType() == AbfsServiceType.BLOB ? ABFS_BLOB_DOMAIN_NAME : ABFS_DFS_DOMAIN_NAME; Assertions.assertThat(path.toString()) .describedAs("Path does not contain expected DNS") .contains(expectedDns); } /** * Return array of random bytes of the given length. * * @param length length of the byte array * @return byte array */ protected byte[] getRandomBytesArray(int length) { final byte[] b = new byte[length]; new Random().nextBytes(b); return b; } /** * Create a file on the file system with the given file name and content. * * @param fs fileSystem that stores the file * @param fileName name of the file * @param fileContent content of the file * * @return path of the file created * @throws IOException exception in writing file on fileSystem */ protected Path createFileWithContent(FileSystem fs, String fileName, byte[] fileContent) throws IOException { Path testFilePath = path(fileName); try (FSDataOutputStream oStream = fs.create(testFilePath)) { oStream.write(fileContent); oStream.flush(); } return testFilePath; } /** * Checks a list of futures for exceptions. * * This method iterates over a list of futures, waits for each task to complete, * and handles any exceptions thrown by the lambda expressions. If a * RuntimeException is caught, it increments the exceptionCaught counter. * If an unexpected exception is caught, it prints the exception to the standard error. * Finally, it asserts that no RuntimeExceptions were caught. * * @param futures The list of futures to check for exceptions. */ protected void checkFuturesForExceptions(List<Future<?>> futures, int exceptionVal) { int exceptionCaught = 0; for (Future<?> future : futures) { try { future.get(); // wait for the task to complete and handle any exceptions thrown by the lambda expression } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { exceptionCaught++; } else { System.err.println("Unexpected exception caught: " + cause); } } catch (InterruptedException e) { // handle interruption } } assertEquals(exceptionCaught, exceptionVal); } /** * Assumes that recovery through client transaction ID is enabled. * Namespace is enabled for the given AzureBlobFileSystem. * Service type is DFS. * Assumes that the client transaction ID is enabled in the configuration. * * @throws IOException in case of an error */ protected void assumeRecoveryThroughClientTransactionID(boolean isCreate) throws IOException { // Assumes that recovery through client transaction ID is enabled. assumeThat(getConfiguration().getIsClientTransactionIdEnabled()) .as("Recovery through client transaction ID is not enabled") .isTrue(); // Assumes that service type is DFS. assumeDfsServiceType(); // Assumes that namespace is enabled for the given AzureBlobFileSystem. assumeHnsEnabled(); if (isCreate) { // Assume that create client is DFS client. assumeThat(AbfsServiceType.DFS.equals(getIngressServiceType())) .as("Ingress service type is not DFS") .isTrue(); // Assume that append blob is not enabled in DFS client. assumeThat(isAppendBlobEnabled()).as("Append blob is enabled in DFS client").isFalse(); } } }
AbstractAbfsIntegrationTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/fetch/FetchProfiler.java
{ "start": 1217, "end": 5295 }
class ____ implements FetchPhase.Profiler { private final FetchProfileBreakdown current; /** * Start profiling at the current time. */ public FetchProfiler() { this(System.nanoTime()); } /** * Build the profiler starting at a fixed time. */ public FetchProfiler(long nanoTime) { current = new FetchProfileBreakdown(nanoTime); } /** * Finish profiling at the current time. */ @Override public ProfileResult finish() { return finish(System.nanoTime()); } /** * Finish profiling at a fixed time. */ public ProfileResult finish(long nanoTime) { return current.result(nanoTime); } @Override public StoredFieldLoader storedFields(StoredFieldLoader storedFieldLoader) { current.debug.put("stored_fields", storedFieldLoader.fieldsToLoad()); return new StoredFieldLoader() { @Override public LeafStoredFieldLoader getLoader(LeafReaderContext ctx, int[] docs) throws IOException { LeafStoredFieldLoader in = storedFieldLoader.getLoader(ctx, docs); return new LeafStoredFieldLoader() { @Override public void advanceTo(int doc) throws IOException { final Timer timer = current.getNewTimer(FetchPhaseTiming.LOAD_STORED_FIELDS); timer.start(); try { in.advanceTo(doc); } finally { timer.stop(); } } @Override public BytesReference source() { return in.source(); } @Override public String id() { return in.id(); } @Override public String routing() { return in.routing(); } @Override public Map<String, List<Object>> storedFields() { return in.storedFields(); } }; } @Override public List<String> fieldsToLoad() { return storedFieldLoader.fieldsToLoad(); } }; } @Override public FetchSubPhaseProcessor profile(String type, String description, FetchSubPhaseProcessor delegate) { FetchSubPhaseProfileBreakdown breakdown = new FetchSubPhaseProfileBreakdown(type, description, delegate); current.subPhases.add(breakdown); return new FetchSubPhaseProcessor() { @Override public void setNextReader(LeafReaderContext readerContext) throws IOException { Timer timer = breakdown.getNewTimer(FetchSubPhaseTiming.NEXT_READER); timer.start(); try { delegate.setNextReader(readerContext); } finally { timer.stop(); } } @Override public StoredFieldsSpec storedFieldsSpec() { return delegate.storedFieldsSpec(); } @Override public void process(HitContext hitContext) throws IOException { Timer timer = breakdown.getNewTimer(FetchSubPhaseTiming.PROCESS); timer.start(); try { delegate.process(hitContext); } finally { timer.stop(); } } }; } @Override public Timer startLoadingSource() { Timer timer = current.getNewTimer(FetchPhaseTiming.LOAD_SOURCE); timer.start(); return timer; } @Override public Timer startNextReader() { Timer timer = current.getNewTimer(FetchPhaseTiming.NEXT_READER); timer.start(); return timer; } static
FetchProfiler
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/compare/ComparableUtilsTest.java
{ "start": 2444, "end": 3290 }
class ____ { BigDecimal c = BigDecimal.ONE; @Test void between_returns_true() { assertTrue(ComparableUtils.is(a).between(b, c)); } @Test void betweenExclusive_returns_false() { assertFalse(ComparableUtils.is(a).betweenExclusive(b, c)); } @Test void static_between_returns_true() { assertTrue(ComparableUtils.between(b, c).test(a)); } @Test void static_betweenExclusive_returns_false() { assertFalse(ComparableUtils.betweenExclusive(b, c).test(a)); } } @DisplayName("C is 10 (B < A < C)") @Nested final
C_is_1
java
apache__kafka
storage/src/test/java/org/apache/kafka/tiered/storage/actions/UpdateBrokerConfigAction.java
{ "start": 1160, "end": 2198 }
class ____ implements TieredStorageTestAction { private final int brokerId; private final Map<String, String> configsToBeAdded; private final List<String> configsToBeDeleted; public UpdateBrokerConfigAction(int brokerId, Map<String, String> configsToBeAdded, List<String> configsToBeDeleted) { this.brokerId = brokerId; this.configsToBeAdded = configsToBeAdded; this.configsToBeDeleted = configsToBeDeleted; } @Override public void doExecute(TieredStorageTestContext context) throws ExecutionException, InterruptedException, TimeoutException { context.updateBrokerConfig(brokerId, configsToBeAdded, configsToBeDeleted); } @Override public void describe(PrintStream output) { output.printf("Update broker config: %d, configs-to-be-added: %s, configs-to-be-deleted: %s%n", brokerId, configsToBeAdded, configsToBeDeleted); } }
UpdateBrokerConfigAction
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging-pulsar/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/pulsar/deployment/DefaultSchemaConfigTest.java
{ "start": 75793, "end": 76548 }
class ____ { @Channel("tx") PulsarTransactions<String> pulsarTransactions; } @Test void repeatableIncomings() { Tuple[] expectations = { tuple("mp.messaging.incoming.channel1.schema", "STRING"), tuple("mp.messaging.incoming.channel2.schema", "STRING"), tuple("mp.messaging.incoming.channel3.schema", "JsonObjectJSON_OBJECTSchema"), tuple("mp.messaging.incoming.channel4.schema", "JsonObjectJSON_OBJECTSchema"), }; var generatedSchemas = Map.of("io.vertx.core.json.JsonObject", "JsonObjectJSON_OBJECTSchema"); doTest(expectations, generatedSchemas, RepeatableIncomingsChannels.class); } private static
TransactionalProducer
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/MemoryNavigableLRUCache.java
{ "start": 1417, "end": 5817 }
class ____ extends MemoryLRUCache { private static final Logger LOG = LoggerFactory.getLogger(MemoryNavigableLRUCache.class); public MemoryNavigableLRUCache(final String name, final int maxCacheSize) { super(name, maxCacheSize); } @Override public KeyValueIterator<Bytes, byte[]> range(final Bytes from, final Bytes to) { if (Objects.nonNull(from) && Objects.nonNull(to) && from.compareTo(to) > 0) { LOG.warn("Returning empty iterator for fetch with invalid key range: from > to. " + "This may be due to range arguments set in the wrong order, " + "or serdes that don't preserve ordering when lexicographically comparing the serialized bytes. " + "Note that the built-in numerical serdes do not follow this for negative numbers"); return KeyValueIterators.emptyIterator(); } else { final TreeMap<Bytes, byte[]> treeMap = toTreeMap(); final Iterator<Bytes> keys = getIterator(treeMap, from, to, true); return new DelegatingPeekingKeyValueIterator<>(name(), new MemoryNavigableLRUCache.CacheIterator(keys, treeMap)); } } @Override public KeyValueIterator<Bytes, byte[]> reverseRange(final Bytes from, final Bytes to) { if (Objects.nonNull(from) && Objects.nonNull(to) && from.compareTo(to) > 0) { LOG.warn("Returning empty iterator for fetch with invalid key range: from > to. " + "This may be due to range arguments set in the wrong order, " + "or serdes that don't preserve ordering when lexicographically comparing the serialized bytes. " + "Note that the built-in numerical serdes do not follow this for negative numbers"); return KeyValueIterators.emptyIterator(); } else { final TreeMap<Bytes, byte[]> treeMap = toTreeMap(); final Iterator<Bytes> keys = getIterator(treeMap, from, to, false); return new DelegatingPeekingKeyValueIterator<>(name(), new MemoryNavigableLRUCache.CacheIterator(keys, treeMap)); } } private Iterator<Bytes> getIterator(final TreeMap<Bytes, byte[]> treeMap, final Bytes from, final Bytes to, final boolean forward) { if (from == null && to == null) { return forward ? treeMap.navigableKeySet().iterator() : treeMap.navigableKeySet().descendingIterator(); } else if (from == null) { return forward ? treeMap.navigableKeySet().headSet(to, true).iterator() : treeMap.navigableKeySet().headSet(to, true).descendingIterator(); } else if (to == null) { return forward ? treeMap.navigableKeySet().tailSet(from, true).iterator() : treeMap.navigableKeySet().tailSet(from, true).descendingIterator(); } else { return forward ? treeMap.navigableKeySet().subSet(from, true, to, true).iterator() : treeMap.navigableKeySet().subSet(from, true, to, true).descendingIterator(); } } @Override public <PS extends Serializer<P>, P> KeyValueIterator<Bytes, byte[]> prefixScan(final P prefix, final PS prefixKeySerializer) { final Bytes from = Bytes.wrap(prefixKeySerializer.serialize(null, prefix)); final Bytes to = Bytes.increment(from); final TreeMap<Bytes, byte[]> treeMap = toTreeMap(); return new DelegatingPeekingKeyValueIterator<>( name(), new MemoryNavigableLRUCache.CacheIterator(treeMap.subMap(from, true, to, false).keySet().iterator(), treeMap) ); } @Override public KeyValueIterator<Bytes, byte[]> all() { return range(null, null); } @Override public KeyValueIterator<Bytes, byte[]> reverseAll() { return reverseRange(null, null); } private synchronized TreeMap<Bytes, byte[]> toTreeMap() { return new TreeMap<>(this.map); } @Override @SuppressWarnings("unchecked") public <R> QueryResult<R> query( final Query<R> query, final PositionBound positionBound, final QueryConfig config) { return StoreQueryUtils.handleBasicQueries( query, positionBound, config, this, getPosition(), context ); } private static
MemoryNavigableLRUCache
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/gateway/GatewayMetaStateTests.java
{ "start": 14470, "end": 15132 }
class ____ extends IndexMetadataVerifier { private final boolean upgrade; MockIndexMetadataVerifier(boolean upgrade) { super(Settings.EMPTY, null, null, null, null, null, MapperMetrics.NOOP); this.upgrade = upgrade; } @Override public IndexMetadata verifyIndexMetadata( IndexMetadata indexMetadata, IndexVersion minimumIndexCompatibilityVersion, IndexVersion minimumReadOnlyIndexCompatibilityVersion ) { return upgrade ? IndexMetadata.builder(indexMetadata).build() : indexMetadata; } } private static
MockIndexMetadataVerifier
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/CustomTypeIdResolverTest.java
{ "start": 1783, "end": 1943 }
class ____ extends ExtBean { public int y; public ExtBeanImpl() { } public ExtBeanImpl(int y) { this.y = y; } } static
ExtBeanImpl
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FutureTransformAsyncTest.java
{ "start": 12247, "end": 13112 }
class ____ { private Executor executor; ListenableFuture<String> foo(String s) { return immediateFuture(s); } ListenableFuture<String> test() { ListenableFuture<String> future = transformAsync(foo("x"), value -> immediateFuture("value: " + value), executor); return future; } } """) .addOutputLines( "out/Test.java", """ import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.Futures.transform; import static com.google.common.util.concurrent.Futures.transformAsync; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.util.concurrent.Executor;
Test
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/vectors/es818/ES818HnswBinaryQuantizedVectorsFormat.java
{ "start": 1563, "end": 3833 }
class ____ extends AbstractHnswVectorsFormat { public static final String NAME = "ES818HnswBinaryQuantizedVectorsFormat"; /** The format for storing, reading, merging vectors on disk */ private static final FlatVectorsFormat flatVectorsFormat = new ES818BinaryQuantizedVectorsFormat(); /** Constructs a format using default graph construction parameters */ public ES818HnswBinaryQuantizedVectorsFormat() { super(NAME); } /** * Constructs a format using the given graph construction parameters. * * @param maxConn the maximum number of connections to a node in the HNSW graph * @param beamWidth the size of the queue maintained during graph construction. */ public ES818HnswBinaryQuantizedVectorsFormat(int maxConn, int beamWidth) { super(NAME, maxConn, beamWidth); } /** * Constructs a format using the given graph construction parameters and scalar quantization. * * @param maxConn the maximum number of connections to a node in the HNSW graph * @param beamWidth the size of the queue maintained during graph construction. * @param numMergeWorkers number of workers (threads) that will be used when doing merge. If * larger than 1, a non-null {@link ExecutorService} must be passed as mergeExec * @param mergeExec the {@link ExecutorService} that will be used by ALL vector writers that are * generated by this format to do the merge */ public ES818HnswBinaryQuantizedVectorsFormat(int maxConn, int beamWidth, int numMergeWorkers, ExecutorService mergeExec) { super(NAME, maxConn, beamWidth, numMergeWorkers, mergeExec); } @Override protected FlatVectorsFormat flatVectorsFormat() { return flatVectorsFormat; } @Override public KnnVectorsWriter fieldsWriter(SegmentWriteState state) throws IOException { return new Lucene99HnswVectorsWriter(state, maxConn, beamWidth, flatVectorsFormat.fieldsWriter(state), numMergeWorkers, mergeExec); } @Override public KnnVectorsReader fieldsReader(SegmentReadState state) throws IOException { return new Lucene99HnswVectorsReader(state, flatVectorsFormat.fieldsReader(state)); } }
ES818HnswBinaryQuantizedVectorsFormat
java
spring-projects__spring-framework
framework-docs/src/main/java/org/springframework/docs/integration/mailusagesimple/Customer.java
{ "start": 696, "end": 870 }
class ____ { public String getEmailAddress() { return null; } public String getFirstName() { return null; } public String getLastName() { return null; } }
Customer
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/VerticleBase.java
{ "start": 1182, "end": 3182 }
class ____ implements Deployable { /** * Reference to the Vert.x instance that deployed this verticle */ protected Vertx vertx; /** * Reference to the context of the verticle */ protected Context context; /** * Initialise the verticle.<p> * This is called by Vert.x when the verticle instance is deployed. Don't call it yourself. * @param vertx the deploying Vert.x instance * @param context the context of the verticle */ public void init(Vertx vertx, Context context) { this.vertx = vertx; this.context = context; } /** * Get the deployment ID of the verticle deployment * @return the deployment ID */ public String deploymentID() { return context.deploymentID(); } /** * Get the configuration of the verticle. * <p> * This can be specified when the verticle is deployed. * @return the configuration */ public JsonObject config() { return context.config(); } @Override public final Future<?> deploy(Context context) throws Exception { init(context.owner(), context); return start(); } @Override public final Future<?> undeploy(Context context) throws Exception { return stop(); } /** * Start the verticle.<p> * This is called by Vert.x when the verticle instance is deployed. Don't call it yourself.<p> * If your verticle does things in its startup which take some time then you can override this method * and call the startFuture some time later when start up is complete. * @return a future signalling the start-up completion */ public Future<?> start() throws Exception { return ((ContextInternal)context).succeededFuture(); } /** * Stop the verticle.<p> * This is called by Vert.x when the verticle instance is un-deployed. Don't call it yourself.<p> * @return a future signalling the clean-up completion */ public Future<?> stop() throws Exception { return ((ContextInternal)context).succeededFuture(); } }
VerticleBase
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/antlr/PainlessParser.java
{ "start": 17272, "end": 20641 }
class ____ extends ParserRuleContext { public RstatementContext rstatement() { return getRuleContext(RstatementContext.class, 0); } public DstatementContext dstatement() { return getRuleContext(DstatementContext.class, 0); } public TerminalNode SEMICOLON() { return getToken(PainlessParser.SEMICOLON, 0); } public TerminalNode EOF() { return getToken(PainlessParser.EOF, 0); } public StatementContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_statement; } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof PainlessParserVisitor) return ((PainlessParserVisitor<? extends T>) visitor).visitStatement(this); else return visitor.visitChildren(this); } } public final StatementContext statement() throws RecognitionException { StatementContext _localctx = new StatementContext(_ctx, getState()); enterRule(_localctx, 6, RULE_statement); int _la; try { setState(117); _errHandler.sync(this); switch (_input.LA(1)) { case IF: case WHILE: case FOR: case TRY: enterOuterAlt(_localctx, 1); { setState(113); rstatement(); } break; case LBRACE: case LP: case DOLLAR: case DO: case CONTINUE: case BREAK: case RETURN: case NEW: case THROW: case BOOLNOT: case BWNOT: case ADD: case SUB: case INCR: case DECR: case OCTAL: case HEX: case INTEGER: case DECIMAL: case STRING: case REGEX: case TRUE: case FALSE: case NULL: case PRIMITIVE: case DEF: case ID: enterOuterAlt(_localctx, 2); { setState(114); dstatement(); setState(115); _la = _input.LA(1); if (!(_la == EOF || _la == SEMICOLON)) { _errHandler.recoverInline(this); } else { if (_input.LA(1) == Token.EOF) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } @SuppressWarnings("CheckReturnValue") public static
StatementContext
java
apache__camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/marshall/simple/BindySimpleFixedLengthMarshallTest.java
{ "start": 1805, "end": 3420 }
class ____ { private static final String URI_MOCK_RESULT = "mock:result"; private static final String URI_MOCK_ERROR = "mock:error"; private static final String URI_DIRECT_START = "direct:start"; private List<Map<String, Object>> models = new ArrayList<>(); private String expected; @Produce(URI_DIRECT_START) private ProducerTemplate template; @EndpointInject(URI_MOCK_RESULT) private MockEndpoint result; @Test @DirtiesContext public void testMarshallMessage() throws Exception { expected = "10A9 PaulineM ISINXD12345678BUYShare000002500.45USD01-08-2009\r\n"; result.expectedBodiesReceived(expected); template.sendBody(generateModel()); result.assertIsSatisfied(); } public List<Map<String, Object>> generateModel() { Map<String, Object> modelObjects = new HashMap<>(); Order order = new Order(); order.setOrderNr(10); order.setOrderType("BUY"); order.setClientNr("A9"); order.setFirstName("Pauline"); order.setLastName("M"); order.setAmount(new BigDecimal("2500.45")); order.setInstrumentCode("ISIN"); order.setInstrumentNumber("XD12345678"); order.setInstrumentType("Share"); order.setCurrency("USD"); Calendar calendar = new GregorianCalendar(); calendar.set(2009, 7, 1); order.setOrderDate(calendar.getTime()); modelObjects.put(order.getClass().getName(), order); models.add(modelObjects); return models; } public static
BindySimpleFixedLengthMarshallTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/ConcurrentQueriesByIdsTest.java
{ "start": 2247, "end": 2549 }
class ____ { @Id private Integer id; @Basic private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
SimpleEntity
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/support/management/MBeanInfoAssembler.java
{ "start": 9789, "end": 15390 }
class ____ (cacheInfo.method.getDeclaringClass() != managedClass) { continue; } LOG.trace("Extracting attributes and operations from method: {}", cacheInfo.method); ManagedAttribute ma = cacheInfo.method.getAnnotation(ManagedAttribute.class); if (ma != null) { String key; String desc = ma.description(); Method getter = null; Method setter = null; boolean mask = ma.mask(); if (cacheInfo.isGetter) { key = cacheInfo.getterOrSetterShorthandName; getter = cacheInfo.method; } else if (cacheInfo.isSetter) { key = cacheInfo.getterOrSetterShorthandName; setter = cacheInfo.method; } else { throw new IllegalArgumentException( "@ManagedAttribute can only be used on Java bean methods, was: " + cacheInfo.method + " on bean: " + managedClass); } // they key must be capitalized key = StringHelper.capitalize(key); // lookup first ManagedAttributeInfo info = attributes.get(key); if (info == null) { info = new ManagedAttributeInfo(key, desc); } if (getter != null) { info.setGetter(getter); } if (setter != null) { info.setSetter(setter); } info.setMask(mask); attributes.put(key, info); } // operations ManagedOperation mo = cacheInfo.method.getAnnotation(ManagedOperation.class); if (mo != null) { String desc = mo.description(); Method operation = cacheInfo.method; boolean mask = mo.mask(); operations.add(new ManagedOperationInfo(desc, operation, mask)); } } } private void extractMbeanAttributes( Map<String, ManagedAttributeInfo> attributes, Set<ModelMBeanAttributeInfo> mBeanAttributes, Set<ModelMBeanOperationInfo> mBeanOperations) throws IntrospectionException { for (ManagedAttributeInfo info : attributes.values()) { ModelMBeanAttributeInfo mbeanAttribute = new ModelMBeanAttributeInfo(info.getKey(), info.getDescription(), info.getGetter(), info.getSetter()); // add missing attribute descriptors, this is needed to have attributes accessible Descriptor desc = mbeanAttribute.getDescriptor(); desc.setField("mask", info.isMask() ? "true" : "false"); if (info.getGetter() != null) { desc.setField("getMethod", info.getGetter().getName()); // attribute must also be added as mbean operation ModelMBeanOperationInfo mbeanOperation = new ModelMBeanOperationInfo(info.getKey(), info.getGetter()); Descriptor opDesc = mbeanOperation.getDescriptor(); opDesc.setField("mask", info.isMask() ? "true" : "false"); mbeanOperation.setDescriptor(opDesc); mBeanOperations.add(mbeanOperation); } if (info.getSetter() != null) { desc.setField("setMethod", info.getSetter().getName()); // attribute must also be added as mbean operation ModelMBeanOperationInfo mbeanOperation = new ModelMBeanOperationInfo(info.getKey(), info.getSetter()); mBeanOperations.add(mbeanOperation); } mbeanAttribute.setDescriptor(desc); mBeanAttributes.add(mbeanAttribute); LOG.trace("Assembled attribute: {}", mbeanAttribute); } } private void extractMbeanOperations( Set<ManagedOperationInfo> operations, Set<ModelMBeanOperationInfo> mBeanOperations) { for (ManagedOperationInfo info : operations) { ModelMBeanOperationInfo mbean = new ModelMBeanOperationInfo(info.description(), info.operation()); Descriptor opDesc = mbean.getDescriptor(); opDesc.setField("mask", info.mask() ? "true" : "false"); mbean.setDescriptor(opDesc); mBeanOperations.add(mbean); LOG.trace("Assembled operation: {}", mbean); } } private void extractMbeanNotifications(Object managedBean, Set<ModelMBeanNotificationInfo> mBeanNotifications) { ManagedNotifications notifications = managedBean.getClass().getAnnotation(ManagedNotifications.class); if (notifications != null) { for (ManagedNotification notification : notifications.value()) { ModelMBeanNotificationInfo info = new ModelMBeanNotificationInfo( notification.notificationTypes(), notification.name(), notification.description()); mBeanNotifications.add(info); LOG.trace("Assembled notification: {}", info); } } } private String getDescription(Object managedBean, String objectName) { ManagedResource mr = ObjectHelper.getAnnotation(managedBean, ManagedResource.class); return mr != null ? mr.description() : ""; } private String getName(Object managedBean) { return managedBean.getClass().getName(); } private static final
if
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/search/aggregations/BaseAggregationTestCase.java
{ "start": 1582, "end": 11048 }
class ____<AB extends AbstractAggregationBuilder<AB>> extends AbstractBuilderTestCase { protected static final String IP_FIELD_NAME = "mapped_ip"; protected abstract AB createTestAggregatorBuilder(); /** * Generic test that creates new AggregatorFactory from the test * AggregatorFactory and checks both for equality and asserts equality on * the two queries. */ public void testFromXContent() throws IOException { AB testAgg = createTestAggregatorBuilder(); AggregatorFactories.Builder factoriesBuilder = AggregatorFactories.builder().addAggregator(testAgg); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { builder.prettyPrint(); } factoriesBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentBuilder shuffled = shuffleXContent(builder); try (XContentParser parser = createParser(shuffled)) { AggregationBuilder newAgg = parse(parser); assertNotSame(newAgg, testAgg); assertEquals(testAgg, newAgg); assertEquals(testAgg.hashCode(), newAgg.hashCode()); } } public void testSupportsConcurrentExecution() { int cardinality = randomIntBetween(-1, 100); AB builder = createTestAggregatorBuilder(); boolean supportsConcurrency = builder.supportsParallelCollection(field -> cardinality); AggregationBuilder bucketBuilder = new HistogramAggregationBuilder("test"); assertTrue(bucketBuilder.supportsParallelCollection(field -> cardinality)); bucketBuilder.subAggregation(builder); assertThat(bucketBuilder.supportsParallelCollection(field -> cardinality), equalTo(supportsConcurrency)); } /** * Create at least 2 aggregations and test equality and hash */ public void testFromXContentMulti() throws IOException { AggregatorFactories.Builder factoriesBuilder = AggregatorFactories.builder(); List<AB> testAggs = createTestAggregatorBuilders(); for (AB testAgg : testAggs) { factoriesBuilder.addAggregator(testAgg); } XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { builder.prettyPrint(); } factoriesBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentBuilder shuffled = shuffleXContent(builder); AggregatorFactories.Builder parsed; try (XContentParser parser = createParser(shuffled)) { assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); parsed = AggregatorFactories.parseAggregators(parser); } assertThat(parsed.getAggregatorFactories(), hasSize(testAggs.size())); assertThat(parsed.getPipelineAggregatorFactories(), hasSize(0)); assertEquals(factoriesBuilder, parsed); assertEquals(factoriesBuilder.hashCode(), parsed.hashCode()); } /** * Create at least 2 aggregations and test equality and hash */ public void testSerializationMulti() throws IOException { AggregatorFactories.Builder builder = AggregatorFactories.builder(); List<AB> testAggs = createTestAggregatorBuilders(); for (AB testAgg : testAggs) { builder.addAggregator(testAgg); } try (BytesStreamOutput output = new BytesStreamOutput()) { builder.writeTo(output); try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry())) { AggregatorFactories.Builder newBuilder = new AggregatorFactories.Builder(in); assertEquals(builder, newBuilder); assertEquals(builder.hashCode(), newBuilder.hashCode()); assertNotSame(builder, newBuilder); } } } /** * Generic test that checks that the toString method renders the XContent * correctly. */ public void testToString() throws IOException { AB testAgg = createTestAggregatorBuilder(); String toString = randomBoolean() ? Strings.toString(testAgg) : testAgg.toString(); AggregationBuilder newAgg; try (XContentParser parser = createParser(XContentType.JSON.xContent(), toString)) { newAgg = parse(parser); } assertNotSame(newAgg, testAgg); assertEquals(testAgg, newAgg); assertEquals(testAgg.hashCode(), newAgg.hashCode()); } protected AggregationBuilder parse(XContentParser parser) throws IOException { assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); AggregatorFactories.Builder parsed = AggregatorFactories.parseAggregators(parser); assertThat(parsed.getAggregatorFactories(), hasSize(1)); assertThat(parsed.getPipelineAggregatorFactories(), hasSize(0)); AggregationBuilder newAgg = parsed.getAggregatorFactories().iterator().next(); assertNull(parser.nextToken()); assertNotNull(newAgg); return newAgg; } /** * Test serialization and deserialization of the test AggregatorFactory. */ public void testSerialization() throws IOException { AB testAgg = createTestAggregatorBuilder(); try (BytesStreamOutput output = new BytesStreamOutput()) { output.writeNamedWriteable(testAgg); try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry())) { AggregationBuilder deserialized = in.readNamedWriteable(AggregationBuilder.class); assertEquals(testAgg, deserialized); assertEquals(testAgg.hashCode(), deserialized.hashCode()); assertNotSame(testAgg, deserialized); @SuppressWarnings("unchecked") // They are .equal so its safe AB castDeserialized = (AB) deserialized; assertToXContentAfterSerialization(testAgg, castDeserialized); } } } /** * Make sure serialization preserves toXContent. */ protected void assertToXContentAfterSerialization(AB original, AB deserialized) throws IOException { assertEquals(Strings.toString(original), Strings.toString(deserialized)); } public void testEqualsAndHashcode() throws IOException { // TODO we only change name and boost, we should extend by any sub-test supplying a "mutate" method that randomly changes one // aspect of the object under test checkEqualsAndHashCode(createTestAggregatorBuilder(), this::copyAggregation); } public void testShallowCopy() { AB original = createTestAggregatorBuilder(); AggregationBuilder clone = original.shallowCopy(original.factoriesBuilder, original.metadata); assertNotSame(original, clone); assertEquals(original, clone); } public void testPlainDeepCopyEquivalentToStreamCopy() throws IOException { AB original = createTestAggregatorBuilder(); AggregationBuilder deepClone = AggregationBuilder.deepCopy(original, Function.identity()); assertNotSame(deepClone, original); AggregationBuilder streamClone = copyAggregation(original); assertNotSame(streamClone, original); assertEquals(streamClone, deepClone); } // we use the streaming infra to create a copy of the query provided as // argument protected AB copyAggregation(AB agg) throws IOException { try (BytesStreamOutput output = new BytesStreamOutput()) { agg.writeTo(output); try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry())) { @SuppressWarnings("unchecked") AB secondAgg = (AB) namedWriteableRegistry().getReader(AggregationBuilder.class, agg.getWriteableName()).read(in); return secondAgg; } } } public String randomNumericField() { int randomInt = randomInt(3); return switch (randomInt) { case 0 -> DATE_FIELD_NAME; case 1 -> DOUBLE_FIELD_NAME; case 2 -> INT_FIELD_NAME; default -> INT_FIELD_NAME; }; } protected void randomFieldOrScript(ValuesSourceAggregationBuilder<?> factory, String field) { int choice = randomInt(2); switch (choice) { case 0 -> factory.field(field); case 1 -> { factory.field(field); factory.script(mockScript("_value + 1")); } case 2 -> factory.script(mockScript("doc[" + field + "] + 1")); default -> throw new AssertionError("Unknown random operation [" + choice + "]"); } } private List<AB> createTestAggregatorBuilders() { int numberOfAggregatorBuilders = randomIntBetween(2, 10); // ensure that we do not create 2 aggregations with the same name Set<String> names = new HashSet<>(); List<AB> aggBuilders = new ArrayList<>(); while (names.size() < numberOfAggregatorBuilders) { AB aggBuilder = createTestAggregatorBuilder(); if (names.add(aggBuilder.getName())) { aggBuilders.add(aggBuilder); } } return aggBuilders; } }
BaseAggregationTestCase
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/sql/ast/MySQLSqlAstTranslator.java
{ "start": 2081, "end": 16163 }
class ____<T extends JdbcOperation> extends SqlAstTranslatorWithOnDuplicateKeyUpdate<T> { /** * On MySQL, 1GB or {@code 2^30 - 1} is the maximum size that a char value can be casted. */ private static final int MAX_CHAR_SIZE = (1 << 30) - 1; private final MySQLDialect dialect; public MySQLSqlAstTranslator(SessionFactoryImplementor sessionFactory, Statement statement, MySQLDialect dialect) { super( sessionFactory, statement ); this.dialect = dialect; } public static String getSqlType(CastTarget castTarget, SessionFactoryImplementor factory) { final String sqlType = getCastTypeName( castTarget, factory.getTypeConfiguration() ); return getSqlType( castTarget, sqlType, factory.getJdbcServices().getDialect() ); } //TODO: this is really, really bad since it circumvents the whole machinery we have in DdlType // and in the Dialect for doing this in a unified way! These mappings should be held in // the DdlTypes themselves and should be set up in registerColumnTypes(). Doing it here // means we have problems distinguishing, say, the 'as Character' special case private static String getSqlType(CastTarget castTarget, String sqlType, Dialect dialect) { if ( sqlType != null ) { int parenthesesIndex = sqlType.indexOf( '(' ); final String baseName = parenthesesIndex == -1 ? sqlType : sqlType.substring( 0, parenthesesIndex ).trim(); switch ( baseName.toLowerCase( Locale.ROOT ) ) { case "bit": return "unsigned"; case "tinyint": case "smallint": case "integer": case "bigint": return "signed"; case "float": case "real": case "double precision": if ( ((MySQLDialect) dialect).getMySQLVersion().isSameOrAfter( 8, 0, 17 ) ) { return sqlType; } final int precision = castTarget.getPrecision() == null ? dialect.getDefaultDecimalPrecision() : castTarget.getPrecision(); final int scale = castTarget.getScale() == null ? Size.DEFAULT_SCALE : castTarget.getScale(); return "decimal(" + precision + "," + scale + ")"; case "char": case "varchar": case "nchar": case "nvarchar": case "text": case "mediumtext": case "longtext": case "enum": if ( castTarget.getLength() == null ) { // TODO: this is ugly and fragile, but could easily be handled in a DdlType if ( castTarget.getJdbcMapping().getJdbcJavaType().getJavaType() == Character.class ) { return "char(1)"; } else { return "char"; } } return castTarget.getLength() > MAX_CHAR_SIZE ? "char" : "char(" + castTarget.getLength() + ")"; case "binary": case "varbinary": case "mediumblob": case "longblob": return castTarget.getLength() == null ? "binary" : "binary(" + castTarget.getLength() + ")"; } } return sqlType; } @Override public void visitBinaryArithmeticExpression(BinaryArithmeticExpression arithmeticExpression) { if ( isIntegerDivisionEmulationRequired( arithmeticExpression ) ) { appendSql( OPEN_PARENTHESIS ); visitArithmeticOperand( arithmeticExpression.getLeftHandOperand() ); appendSql( " div " ); visitArithmeticOperand( arithmeticExpression.getRightHandOperand() ); appendSql( CLOSE_PARENTHESIS ); } else { super.visitBinaryArithmeticExpression(arithmeticExpression); } } @Override protected void visitInsertSource(InsertSelectStatement statement) { if ( statement.getSourceSelectStatement() != null ) { if ( statement.getConflictClause() != null ) { final List<ColumnReference> targetColumnReferences = statement.getTargetColumns(); final List<String> columnNames = new ArrayList<>( targetColumnReferences.size() ); for ( ColumnReference targetColumnReference : targetColumnReferences ) { columnNames.add( targetColumnReference.getColumnExpression() ); } appendSql( "select * from " ); emulateQueryPartTableReferenceColumnAliasing( new QueryPartTableReference( new SelectStatement( statement.getSourceSelectStatement() ), "excluded", columnNames, false, getSessionFactory() ) ); } else { statement.getSourceSelectStatement().accept( this ); } } else { visitValuesList( statement.getValuesList() ); if ( statement.getConflictClause() != null && getDialect().getMySQLVersion().isSameOrAfter( 8, 0, 19 ) ) { appendSql( " as excluded" ); char separator = '('; for ( ColumnReference targetColumn : statement.getTargetColumns() ) { appendSql( separator ); appendSql( targetColumn.getColumnExpression() ); separator = ','; } appendSql( ')' ); } } } @Override public void visitColumnReference(ColumnReference columnReference) { if ( getDialect().getMySQLVersion().isBefore( 8, 0, 19 ) && "excluded".equals( columnReference.getQualifier() ) && getStatementStack().getCurrent() instanceof InsertSelectStatement insertSelectStatement && insertSelectStatement.getSourceSelectStatement() == null ) { // Accessing the excluded row for an insert-values statement in the conflict clause requires the values qualifier appendSql( "values(" ); columnReference.appendReadExpression( this, null ); append( ')' ); } else { super.visitColumnReference( columnReference ); } } @Override protected void renderDeleteClause(DeleteStatement statement) { appendSql( "delete" ); final Stack<Clause> clauseStack = getClauseStack(); try { clauseStack.push( Clause.DELETE ); renderTableReferenceIdentificationVariable( statement.getTargetTable() ); if ( statement.getFromClause().getRoots().isEmpty() ) { appendSql( " from " ); renderDmlTargetTableExpression( statement.getTargetTable() ); } else { visitFromClause( statement.getFromClause() ); } } finally { clauseStack.pop(); } } @Override protected void renderUpdateClause(UpdateStatement updateStatement) { if ( updateStatement.getFromClause().getRoots().isEmpty() ) { super.renderUpdateClause( updateStatement ); } else { appendSql( "update " ); renderFromClauseSpaces( updateStatement.getFromClause() ); } } @Override protected void renderDmlTargetTableExpression(NamedTableReference tableReference) { super.renderDmlTargetTableExpression( tableReference ); if ( getClauseStack().getCurrent() != Clause.INSERT ) { renderTableReferenceIdentificationVariable( tableReference ); } } @Override protected void visitConflictClause(ConflictClause conflictClause) { visitOnDuplicateKeyConflictClause( conflictClause ); } @Override protected String determineColumnReferenceQualifier(ColumnReference columnReference) { final DmlTargetColumnQualifierSupport qualifierSupport = getDialect().getDmlTargetColumnQualifierSupport(); final String dmlAlias; // Since MySQL does not support aliasing the insert target table, // we must detect column reference that are used in the conflict clause // and use the table expression as qualifier instead if ( getClauseStack().getCurrent() != Clause.SET || !( getCurrentDmlStatement() instanceof InsertSelectStatement insertSelectStatement ) || ( dmlAlias = insertSelectStatement.getTargetTable().getIdentificationVariable() ) == null || !dmlAlias.equals( columnReference.getQualifier() ) ) { return columnReference.getQualifier(); } // Qualify the column reference with the table expression also when in subqueries else if ( qualifierSupport != DmlTargetColumnQualifierSupport.NONE || !getQueryPartStack().isEmpty() ) { return getCurrentDmlStatement().getTargetTable().getTableExpression(); } else { return null; } } @Override protected void renderExpressionAsClauseItem(Expression expression) { expression.accept( this ); } @Override protected void visitRecursivePath(Expression recursivePath, int sizeEstimate) { // MySQL determines the type and size of a column in a recursive CTE based on the expression of the non-recursive part // Due to that, we have to cast the path in the non-recursive path to a varchar of appropriate size to avoid data truncation errors if ( sizeEstimate == -1 ) { super.visitRecursivePath( recursivePath, sizeEstimate ); } else { appendSql( "cast(" ); recursivePath.accept( this ); appendSql( " as char(" ); appendSql( sizeEstimate ); appendSql( "))" ); } } @Override public void visitBooleanExpressionPredicate(BooleanExpressionPredicate booleanExpressionPredicate) { final boolean isNegated = booleanExpressionPredicate.isNegated(); if ( isNegated ) { appendSql( "not(" ); } booleanExpressionPredicate.getExpression().accept( this ); if ( isNegated ) { appendSql( CLOSE_PARENTHESIS ); } } protected boolean shouldEmulateFetchClause(QueryPart queryPart) { // Check if current query part is already row numbering to avoid infinite recursion return useOffsetFetchClause( queryPart ) && getQueryPartForRowNumbering() != queryPart && getDialect().supportsWindowFunctions() && !isRowsOnlyFetchClauseType( queryPart ); } @Override public void visitQueryGroup(QueryGroup queryGroup) { if ( shouldEmulateFetchClause( queryGroup ) ) { emulateFetchOffsetWithWindowFunctions( queryGroup, true ); } else { super.visitQueryGroup( queryGroup ); } } @Override public void visitQuerySpec(QuerySpec querySpec) { if ( shouldEmulateFetchClause( querySpec ) ) { emulateFetchOffsetWithWindowFunctions( querySpec, true ); } else { super.visitQuerySpec( querySpec ); } } @Override public void visitValuesTableReference(ValuesTableReference tableReference) { emulateValuesTableReferenceColumnAliasing( tableReference ); } @Override protected void renderDerivedTableReference(DerivedTableReference tableReference) { if ( tableReference instanceof FunctionTableReference && tableReference.isLateral() ) { // No need for a lateral keyword for functions tableReference.accept( this ); } else { super.renderDerivedTableReference( tableReference ); } } @Override public void visitOffsetFetchClause(QueryPart queryPart) { if ( !isRowNumberingCurrentQueryPart() ) { renderCombinedLimitClause( queryPart ); } } @Override protected void renderComparison(Expression lhs, ComparisonOperator operator, Expression rhs) { renderComparisonDistinctOperator( lhs, operator, rhs ); } @Override protected void renderPartitionItem(Expression expression) { if ( expression instanceof Literal ) { appendSql( "'0'" ); } else if ( expression instanceof Summarization summarization ) { renderCommaSeparated( summarization.getGroupings() ); appendSql( " with " ); appendSql( summarization.getKind().sqlText() ); } else { expression.accept( this ); } } @Override public void visitLikePredicate(LikePredicate likePredicate) { // Custom implementation because MySQL uses backslash as the default escape character if ( getDialect().getVersion().isSameOrAfter( 8, 0, 24 ) ) { // From version 8.0.24 we can override this by specifying an empty escape character // See https://dev.mysql.com/doc/refman/8.0/en/string-comparison-functions.html#operator_like super.visitLikePredicate( likePredicate ); if ( !getDialect().isNoBackslashEscapesEnabled() && likePredicate.getEscapeCharacter() == null ) { appendSql( " escape ''" ); } } else { if ( likePredicate.isCaseSensitive() ) { likePredicate.getMatchExpression().accept( this ); if ( likePredicate.isNegated() ) { appendSql( " not" ); } appendSql( " like " ); renderBackslashEscapedLikePattern( likePredicate.getPattern(), likePredicate.getEscapeCharacter(), getDialect().isNoBackslashEscapesEnabled() ); } else { appendSql( getDialect().getLowercaseFunction() ); appendSql( OPEN_PARENTHESIS ); likePredicate.getMatchExpression().accept( this ); appendSql( CLOSE_PARENTHESIS ); if ( likePredicate.isNegated() ) { appendSql( " not" ); } appendSql( " like " ); appendSql( getDialect().getLowercaseFunction() ); appendSql( OPEN_PARENTHESIS ); renderBackslashEscapedLikePattern( likePredicate.getPattern(), likePredicate.getEscapeCharacter(), getDialect().isNoBackslashEscapesEnabled() ); appendSql( CLOSE_PARENTHESIS ); } if ( likePredicate.getEscapeCharacter() != null ) { appendSql( " escape " ); likePredicate.getEscapeCharacter().accept( this ); } } } @Override public MySQLDialect getDialect() { return dialect; } @Override public void visitCastTarget(CastTarget castTarget) { String sqlType = getSqlType( castTarget, getSessionFactory() ); if ( sqlType != null ) { appendSql( sqlType ); } else { super.visitCastTarget( castTarget ); } } @Override protected void renderStringContainsExactlyPredicate(Expression haystack, Expression needle) { // MySQL can't cope with NUL characters in the position function, so we use a like predicate instead haystack.accept( this ); appendSql( " like concat('%',replace(replace(replace(" ); needle.accept( this ); appendSql( ",'~','~~'),'?','~?'),'%','~%'),'%') escape '~'" ); } /* Upsert Template: (for an entity WITHOUT @Version) INSERT INTO employees (id, name, salary, version) VALUES (?, ?, ?, ?) AS tr ON DUPLICATE KEY UPDATE name = tr.name, salary = tr.salary */ @Override protected void renderNewRowAlias() { appendSql( "as " ); renderAlias(); appendSql( " " ); } @Override protected void renderUpdatevalue(ColumnValueBinding columnValueBinding) { renderAlias(); appendSql( "." ); appendSql( columnValueBinding.getColumnReference().getColumnExpression() ); } private void renderAlias() { appendSql( "tr" ); } @Override protected void appendAssignmentColumn(ColumnReference column) { column.appendColumnForWrite( this, getAffectedTableNames().size() > 1 && !(getStatement() instanceof InsertSelectStatement) ? determineColumnReferenceQualifier( column ) : null ); } }
MySQLSqlAstTranslator
java
playframework__playframework
core/play-java/src/main/java/play/routing/RoutingDsl.java
{ "start": 9716, "end": 10210 }
class ____ { final String method; final Pattern pathPattern; final List<RouteParam> params; final Object action; final Method actionMethod; Route( String method, Pattern pathPattern, List<RouteParam> params, Object action, Method actionMethod) { this.method = method; this.pathPattern = pathPattern; this.params = params; this.action = action; this.actionMethod = actionMethod; } } static
Route
java
apache__camel
components/camel-smb/src/test/java/org/apache/camel/component/smb/SmbRecursiveMinDepthIT.java
{ "start": 1020, "end": 2314 }
class ____ extends SmbServerTestSupport { @Override public void doPostSetup() throws Exception { prepareSmbServer(); } protected String getSmbUrl() { return String.format( "smb:%s/%s/uploadmin?username=%s&password=%s&recursive=true&mindepth=3&initialDelay=3000", service.address(), service.shareName(), service.userName(), service.password()); } @Test public void testDirectoryTraversalDepth() throws Exception { MockEndpoint mock = getMockEndpoint("mock:received_send"); mock.expectedBodiesReceivedInAnyOrder("Hello", "Goodday"); mock.assertIsSatisfied(); } private void prepareSmbServer() { template.sendBodyAndHeader(getSmbUrl(), "Goodday", Exchange.FILE_NAME, "user/greet/goodday.txt"); template.sendBodyAndHeader(getSmbUrl(), "Hello", Exchange.FILE_NAME, "user/greet/en/hello.txt"); template.sendBodyAndHeader(getSmbUrl(), "World", Exchange.FILE_NAME, "user/world.txt"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(getSmbUrl()) .to("mock:received_send"); } }; } }
SmbRecursiveMinDepthIT
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/H2EmbeddedDatabaseConfigurer.java
{ "start": 1058, "end": 2247 }
class ____ extends AbstractEmbeddedDatabaseConfigurer { private static @Nullable H2EmbeddedDatabaseConfigurer instance; private final Class<? extends Driver> driverClass; /** * Get the singleton {@code H2EmbeddedDatabaseConfigurer} instance. * @return the configurer instance * @throws ClassNotFoundException if H2 is not on the classpath */ @SuppressWarnings("unchecked") public static synchronized H2EmbeddedDatabaseConfigurer getInstance() throws ClassNotFoundException { if (instance == null) { instance = new H2EmbeddedDatabaseConfigurer( (Class<? extends Driver>) ClassUtils.forName("org.h2.Driver", H2EmbeddedDatabaseConfigurer.class.getClassLoader())); } return instance; } private H2EmbeddedDatabaseConfigurer(Class<? extends Driver> driverClass) { this.driverClass = driverClass; } @Override public void configureConnectionProperties(ConnectionProperties properties, String databaseName) { properties.setDriverClass(this.driverClass); properties.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false", databaseName)); properties.setUsername("sa"); properties.setPassword(""); } }
H2EmbeddedDatabaseConfigurer
java
apache__camel
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java
{ "start": 680491, "end": 683754 }
class ____ extends YamlDeserializerBase<OpenApiDefinition> { public OpenApiDefinitionDeserializer() { super(OpenApiDefinition.class); } @Override protected OpenApiDefinition newInstance() { return new OpenApiDefinition(); } @Override protected boolean setProperty(OpenApiDefinition target, String propertyKey, String propertyName, Node node) { propertyKey = org.apache.camel.util.StringHelper.dashToCamelCase(propertyKey); switch(propertyKey) { case "apiContextPath": { String val = asText(node); target.setApiContextPath(val); break; } case "disabled": { String val = asText(node); target.setDisabled(val); break; } case "missingOperation": { String val = asText(node); target.setMissingOperation(val); break; } case "mockIncludePattern": { String val = asText(node); target.setMockIncludePattern(val); break; } case "routeId": { String val = asText(node); target.setRouteId(val); break; } case "specification": { String val = asText(node); target.setSpecification(val); break; } case "id": { String val = asText(node); target.setId(val); break; } case "description": { String val = asText(node); target.setDescription(val); break; } case "note": { String val = asText(node); target.setNote(val); break; } default: { return false; } } return true; } } @YamlType( nodes = "openIdConnect", types = org.apache.camel.model.rest.OpenIdConnectDefinition.class, order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1, displayName = "Open Id Connect", description = "Rest security OpenID Connect definition", deprecated = false, properties = { @YamlProperty(name = "description", type = "string", description = "A short description for security scheme.", displayName = "Description"), @YamlProperty(name = "key", type = "string", required = true, description = "Key used to refer to this security definition", displayName = "Key"), @YamlProperty(name = "url", type = "string", required = true, description = "OpenId Connect URL to discover OAuth2 configuration values.", displayName = "Url") } ) public static
OpenApiDefinitionDeserializer
java
apache__camel
components/camel-jackson/src/main/java/org/apache/camel/component/jackson/ListJacksonDataFormat.java
{ "start": 1003, "end": 1701 }
class ____ extends JacksonDataFormat { public ListJacksonDataFormat() { useList(); } public ListJacksonDataFormat(Class<?> unmarshalType) { super(unmarshalType); useList(); } public ListJacksonDataFormat(Class<?> unmarshalType, Class<?> jsonView) { super(unmarshalType, jsonView); useList(); } public ListJacksonDataFormat(ObjectMapper mapper, Class<?> unmarshalType) { super(mapper, unmarshalType); useList(); } public ListJacksonDataFormat(ObjectMapper mapper, Class<?> unmarshalType, Class<?> jsonView) { super(mapper, unmarshalType, jsonView); useList(); } }
ListJacksonDataFormat
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskTest.java
{ "start": 96461, "end": 97634 }
class ____ implements StreamInputProcessor { private final int totalProcessCalls; private int currentNumProcessCalls; AvailabilityTestInputProcessor(int totalProcessCalls) { this.totalProcessCalls = totalProcessCalls; } @Override public DataInputStatus processInput() { return ++currentNumProcessCalls < totalProcessCalls ? DataInputStatus.MORE_AVAILABLE : DataInputStatus.END_OF_INPUT; } @Override public CompletableFuture<Void> prepareSnapshot( ChannelStateWriter channelStateWriter, final long checkpointId) throws CheckpointException { return FutureUtils.completedVoidFuture(); } @Override public void close() throws IOException {} @Override public CompletableFuture<?> getAvailableFuture() { return AVAILABLE; } } /** * A stream input processor implementation with input unavailable for a specified amount of * time, after which processor is closing. */ private static
AvailabilityTestInputProcessor
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/logging/LogbackAndLog4J2ExcludedLoggingSystemTests.java
{ "start": 1071, "end": 1301 }
class ____ { @Test void whenLogbackAndLog4J2AreNotPresentJULIsTheLoggingSystem() { assertThat(LoggingSystem.get(getClass().getClassLoader())).isInstanceOf(JavaLoggingSystem.class); } }
LogbackAndLog4J2ExcludedLoggingSystemTests
java
google__dagger
dagger-runtime/main/java/dagger/Module.java
{ "start": 868, "end": 997 }
class ____ contributes to the object graph. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @
that
java
mockito__mockito
mockito-core/src/main/java/org/mockito/Mock.java
{ "start": 1050, "end": 1826 }
class ____ extends SampleBaseTestCase { * * &#064;Mock private ArticleCalculator calculator; * &#064;Mock(name = "database") private ArticleDatabase dbMock; * &#064;Mock(answer = RETURNS_MOCKS) private UserProvider userProvider; * &#064;Mock(extraInterfaces = {Queue.class, Observer.class}) private ArticleMonitor articleMonitor; * &#064;Mock(strictness = Mock.Strictness.LENIENT) private ArticleConsumer articleConsumer; * &#064;Mock(stubOnly = true) private Logger logger; * * private ArticleManager manager; * * &#064;Before public void setup() { * manager = new ArticleManager(userProvider, database, calculator, articleMonitor, articleConsumer, logger); * } * } * * public
ArticleManagerTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/event/RMAppAttemptContainerFinishedEvent.java
{ "start": 1241, "end": 1816 }
class ____ extends RMAppAttemptEvent { private final ContainerStatus containerStatus; private final NodeId nodeId; public RMAppAttemptContainerFinishedEvent(ApplicationAttemptId appAttemptId, ContainerStatus containerStatus, NodeId nodeId) { super(appAttemptId, RMAppAttemptEventType.CONTAINER_FINISHED); this.containerStatus = containerStatus; this.nodeId = nodeId; } public ContainerStatus getContainerStatus() { return this.containerStatus; } public NodeId getNodeId() { return this.nodeId; } }
RMAppAttemptContainerFinishedEvent
java
elastic__elasticsearch
x-pack/plugin/sql/sql-action/src/test/java/org/elasticsearch/xpack/sql/action/SqlRequestParsersTests.java
{ "start": 2000, "end": 2197 }
enum ____ org.elasticsearch.xpack.sql.proto.Mode.VALUE", SqlQueryRequest::fromXContent ); assertParsingErrorMessageReason(""" {"mode" : "value"}""", "No
constant
java
google__guava
android/guava-tests/test/com/google/common/graph/StandardImmutableDirectedGraphTest.java
{ "start": 997, "end": 1888 }
class ____ extends AbstractStandardDirectedGraphTest { @Parameters(name = "allowsSelfLoops={0}") public static Collection<Object[]> parameters() { return Arrays.asList(new Object[][] {{false}, {true}}); } private final boolean allowsSelfLoops; private ImmutableGraph.Builder<Integer> graphBuilder; public StandardImmutableDirectedGraphTest(boolean allowsSelfLoops) { this.allowsSelfLoops = allowsSelfLoops; } @Override public Graph<Integer> createGraph() { graphBuilder = GraphBuilder.directed().allowsSelfLoops(allowsSelfLoops).immutable(); return graphBuilder.build(); } @Override final void addNode(Integer n) { graphBuilder.addNode(n); graph = graphBuilder.build(); } @Override final void putEdge(Integer n1, Integer n2) { graphBuilder.putEdge(n1, n2); graph = graphBuilder.build(); } }
StandardImmutableDirectedGraphTest
java
redisson__redisson
redisson/src/main/java/org/redisson/transaction/TransactionTimeoutException.java
{ "start": 766, "end": 994 }
class ____ extends TransactionException { private static final long serialVersionUID = 7126673140273327142L; public TransactionTimeoutException(String message) { super(message); } }
TransactionTimeoutException
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/SystemTypeInference.java
{ "start": 10456, "end": 24737 }
class ____ implements TypeStrategy { private final FunctionKind functionKind; private final List<StaticArgument> staticArgs; private final TypeStrategy origin; private final boolean disableSystemArgs; private SystemOutputStrategy( FunctionKind functionKind, List<StaticArgument> staticArgs, TypeStrategy origin, boolean disableSystemArgs) { this.functionKind = functionKind; this.staticArgs = staticArgs; this.origin = origin; this.disableSystemArgs = disableSystemArgs; } @Override public Optional<DataType> inferType(CallContext callContext) { return origin.inferType(callContext) .map( functionDataType -> { final List<Field> fields = new ArrayList<>(); // According to the SQL standard, pass-through columns should // actually be added at the end of the output row type. However, // looking at the overall landscape we deviate from the standard in // this regard: // - Calcite built-in window functions add them at the beginning // - MATCH_RECOGNIZE adds PARTITION BY columns at the beginning // - Flink SESSION windows add pass-through columns at the beginning // - Oracle adds pass-through columns for all ROW semantics args, so // this whole topic is kind of vendor specific already fields.addAll(derivePassThroughFields(callContext)); fields.addAll(deriveFunctionOutputFields(functionDataType)); if (!disableSystemArgs) { fields.addAll(deriveRowtimeField(callContext)); } final List<Field> uniqueFields = makeFieldNamesUnique(fields); return DataTypes.ROW(uniqueFields).notNull(); }); } private List<Field> makeFieldNamesUnique(List<Field> fields) { final Map<String, Integer> fieldCount = new HashMap<>(); return fields.stream() .map( item -> { final int nextCount = fieldCount.compute( item.getName(), (fieldName, count) -> count == null ? -1 : count + 1); final String newFieldName = nextCount < 0 ? item.getName() : item.getName() + nextCount; return DataTypes.FIELD(newFieldName, item.getDataType()); }) .collect(Collectors.toList()); } private List<Field> derivePassThroughFields(CallContext callContext) { if (functionKind != FunctionKind.PROCESS_TABLE) { return List.of(); } final List<DataType> argDataTypes = callContext.getArgumentDataTypes(); return IntStream.range(0, staticArgs.size()) .mapToObj( pos -> { final StaticArgument arg = staticArgs.get(pos); if (arg.is(StaticArgumentTrait.PASS_COLUMNS_THROUGH)) { return DataType.getFields(argDataTypes.get(pos)).stream(); } if (!arg.is(StaticArgumentTrait.SET_SEMANTIC_TABLE)) { return Stream.<Field>empty(); } final TableSemantics semantics = callContext .getTableSemantics(pos) .orElseThrow(IllegalStateException::new); final DataType rowDataType = DataTypes.ROW(DataType.getFields(argDataTypes.get(pos))); final DataType projectedRow = Projection.of(semantics.partitionByColumns()) .project(rowDataType); return DataType.getFields(projectedRow).stream(); }) .flatMap(s -> s) .collect(Collectors.toList()); } private List<Field> deriveFunctionOutputFields(DataType functionDataType) { final List<DataType> fieldTypes = DataType.getFieldDataTypes(functionDataType); final List<String> fieldNames = DataType.getFieldNames(functionDataType); if (fieldTypes.isEmpty()) { // Before the system type inference was introduced, SQL and // Table API chose a different default field name. // EXPR$0 is chosen for best-effort backwards compatibility for // SQL users. return List.of(DataTypes.FIELD("EXPR$0", functionDataType)); } return IntStream.range(0, fieldTypes.size()) .mapToObj(pos -> DataTypes.FIELD(fieldNames.get(pos), fieldTypes.get(pos))) .collect(Collectors.toList()); } private List<Field> deriveRowtimeField(CallContext callContext) { if (this.functionKind != FunctionKind.PROCESS_TABLE) { return List.of(); } final List<DataType> args = callContext.getArgumentDataTypes(); // Check if on_time is defined and non-empty final int onTimePos = args.size() - 1 - PROCESS_TABLE_FUNCTION_ARG_ON_TIME_OFFSET; final Set<String> onTimeFields = callContext .getArgumentValue(onTimePos, ColumnList.class) .map(ColumnList::getNames) .map(Set::copyOf) .orElse(Set.of()); final Set<String> usedOnTimeFields = new HashSet<>(); final List<LogicalType> onTimeColumns = new ArrayList<>(); final List<String> missingOnTimeColumns = new ArrayList<>(); IntStream.range(0, staticArgs.size()) .forEach( pos -> { final StaticArgument staticArg = staticArgs.get(pos); if (!staticArg.is(StaticArgumentTrait.TABLE)) { return; } final RowType rowType = LogicalTypeUtils.toRowType(args.get(pos).getLogicalType()); final int onTimeColumn = findUniqueOnTimeColumn( staticArg.getName(), rowType, onTimeFields); if (onTimeColumn >= 0) { usedOnTimeFields.add(rowType.getFieldNames().get(onTimeColumn)); onTimeColumns.add(rowType.getTypeAt(onTimeColumn)); return; } if (staticArg.is(StaticArgumentTrait.REQUIRE_ON_TIME)) { throw new ValidationException( String.format( "Table argument '%s' requires a time attribute. " + "Please provide one using the implicit `on_time` argument. " + "For example: myFunction(..., on_time => DESCRIPTOR(`my_timestamp`)", staticArg.getName())); } else { missingOnTimeColumns.add(staticArg.getName()); } }); if (!onTimeColumns.isEmpty() && !missingOnTimeColumns.isEmpty()) { throw new ValidationException( "Invalid time attribute declaration. If multiple tables are declared, the `on_time` argument " + "must reference a time column for each table argument or none. " + "Missing time attributes for: " + missingOnTimeColumns); } final Set<String> unusedOnTimeFields = new HashSet<>(onTimeFields); unusedOnTimeFields.removeAll(usedOnTimeFields); if (!unusedOnTimeFields.isEmpty()) { throw new ValidationException( "Invalid time attribute declaration. " + "Each column in the `on_time` argument must reference at least one " + "column in one of the table arguments. Unknown references: " + unusedOnTimeFields); } if (onTimeColumns.isEmpty()) { return List.of(); } // Don't allow mixtures of time attribute roots final Set<LogicalTypeRoot> onTimeRoots = onTimeColumns.stream() .map(LogicalType::getTypeRoot) .collect(Collectors.toSet()); if (onTimeRoots.size() > 1) { throw new ValidationException( "Invalid time attribute declaration. " + "All columns in the `on_time` argument must reference the same data type kind. " + "But found: " + onTimeRoots); } final LogicalType commonOnTimeType = LogicalTypeMerging.findCommonType(onTimeColumns) .orElseThrow( () -> new IllegalStateException( "Unable to derive data type for PTF result time attribute.")); final LogicalType resultTimestamp = forwardTimeAttribute(commonOnTimeType, onTimeColumns); return List.of( DataTypes.FIELD( PROCESS_TABLE_FUNCTION_RESULT_ROWTIME, DataTypes.of(resultTimestamp))); } private static int findUniqueOnTimeColumn( String tableArgName, RowType rowType, Set<String> onTimeFields) { final List<RowField> fields = rowType.getFields(); int found = -1; for (int pos = 0; pos < fields.size(); pos++) { final RowField field = fields.get(pos); if (!onTimeFields.contains(field.getName())) { continue; } if (found != -1) { throw new ValidationException( String.format( "Ambiguous time attribute found. " + "The `on_time` argument must reference at most one column in a table argument. " + "Currently, the columns in `on_time` point to both '%s' and '%s' in table argument '%s'.", fields.get(found).getName(), field.getName(), tableArgName)); } found = pos; if (isUnsupportedOnTimeColumn(field.getType())) { throw new ValidationException( String.format( "Unsupported data type for time attribute. " + "The `on_time` argument must reference a TIMESTAMP or TIMESTAMP_LTZ column (up to precision 3). " + "However, column '%s' in table argument '%s' has data type '%s'.", field.getName(), tableArgName, field.getType().asSummaryString())); } } return found; } private static LogicalType forwardTimeAttribute( LogicalType timestampType, List<LogicalType> onTimeColumns) { if (onTimeColumns.stream().noneMatch(LogicalTypeChecks::isTimeAttribute)) { return timestampType.copy(false); } switch (timestampType.getTypeRoot()) { case TIMESTAMP_WITHOUT_TIME_ZONE: return new TimestampType( false, TimestampKind.ROWTIME, LogicalTypeChecks.getPrecision(timestampType)); case TIMESTAMP_WITH_LOCAL_TIME_ZONE: return new LocalZonedTimestampType( false, TimestampKind.ROWTIME, LogicalTypeChecks.getPrecision(timestampType)); default: throw new IllegalStateException( "Timestamp type expected for PTF result time attribute."); } } private static boolean isUnsupportedOnTimeColumn(LogicalType type) { return !LogicalTypeChecks.canBeTimeAttributeType(type) || LogicalTypeChecks.getPrecision(type) > 3; } } private static
SystemOutputStrategy
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 23186, "end": 23532 }
interface ____"); } @Test public void autoValueMustNotBeFinal() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "foo.bar.Baz", "package foo.bar;", "", "import com.google.auto.value.AutoValue;", "", "@AutoValue", "public final
Baz
java
apache__rocketmq
test/src/test/java/org/apache/rocketmq/test/recall/SendAndRecallDelayMessageIT.java
{ "start": 1995, "end": 8507 }
class ____ extends BaseConf { private static String initTopic; private static String consumerGroup; private static RMQNormalProducer producer; private static RMQPopConsumer popConsumer; @Before public void init() { initTopic = initTopic(); consumerGroup = initConsumerGroup(); producer = getProducer(NAMESRV_ADDR, initTopic); popConsumer = ConsumerFactory.getRMQPopConsumer(NAMESRV_ADDR, consumerGroup, initTopic, "*", new RMQNormalListener()); mqClients.add(popConsumer); } @AfterClass public static void tearDown() { shutdown(); } @Test public void testSendAndRecv() throws Exception { int delaySecond = 1; String topic = MQRandomUtils.getRandomTopic(); IntegrationTestBase.initTopic(topic, NAMESRV_ADDR, BROKER1_NAME, 1, CQType.SimpleCQ, TopicMessageType.DELAY); MessageQueue messageQueue = new MessageQueue(topic, BROKER1_NAME, 0); String brokerAddress = brokerController1.getBrokerAddr(); List<Message> sendList = buildSendMessageList(topic, delaySecond); List<Message> recvList = new ArrayList<>(); for (Message message : sendList) { producer.getProducer().send(message); } await() .pollInterval(1, TimeUnit.SECONDS) .atMost(delaySecond + 15, TimeUnit.SECONDS) .until(() -> { PopResult popResult = popConsumer.pop(brokerAddress, messageQueue, 60 * 1000, -1); processPopResult(recvList, popResult); return recvList.size() == sendList.size(); }); } @Test public void testSendAndRecall() throws Exception { int delaySecond = 5; String topic = MQRandomUtils.getRandomTopic(); IntegrationTestBase.initTopic(topic, NAMESRV_ADDR, BROKER1_NAME, 1, CQType.SimpleCQ, TopicMessageType.DELAY); MessageQueue messageQueue = new MessageQueue(topic, BROKER1_NAME, 0); String brokerAddress = brokerController1.getBrokerAddr(); List<Message> sendList = buildSendMessageList(topic, delaySecond); List<Message> recvList = new ArrayList<>(); int recallCount = 0; for (Message message : sendList) { SendResult sendResult = producer.getProducer().send(message); if (sendResult.getRecallHandle() != null) { String messageId = producer.getProducer().recallMessage(topic, sendResult.getRecallHandle()); assertEquals(sendResult.getMsgId(), messageId); recallCount += 1; } } assertEquals(sendList.size() - 2, recallCount); // one normal and one delay-level message try { await() .pollInterval(1, TimeUnit.SECONDS) .atMost(delaySecond + 15, TimeUnit.SECONDS) .until(() -> { PopResult popResult = popConsumer.pop(brokerAddress, messageQueue, 60 * 1000, -1); processPopResult(recvList, popResult); return recvList.size() == sendList.size(); }); } catch (Exception e) { } assertEquals(sendList.size() - recallCount, recvList.size()); } @Test public void testSendAndRecall_ukCollision() throws Exception { int delaySecond = 5; String topic = MQRandomUtils.getRandomTopic(); String collisionTopic = MQRandomUtils.getRandomTopic(); IntegrationTestBase.initTopic(topic, NAMESRV_ADDR, BROKER1_NAME, 1, CQType.SimpleCQ, TopicMessageType.DELAY); IntegrationTestBase.initTopic(collisionTopic, NAMESRV_ADDR, BROKER1_NAME, 1, CQType.SimpleCQ, TopicMessageType.DELAY); MessageQueue messageQueue = new MessageQueue(topic, BROKER1_NAME, 0); String brokerAddress = brokerController1.getBrokerAddr(); List<Message> sendList = buildSendMessageList(topic, delaySecond); List<Message> recvList = new ArrayList<>(); int recallCount = 0; for (Message message : sendList) { SendResult sendResult = producer.getProducer().send(message); if (sendResult.getRecallHandle() != null) { RecallMessageHandle.HandleV1 handleEntity = (RecallMessageHandle.HandleV1) RecallMessageHandle.decodeHandle(sendResult.getRecallHandle()); String collisionHandle = RecallMessageHandle.HandleV1.buildHandle(collisionTopic, handleEntity.getBrokerName(), handleEntity.getTimestampStr(), handleEntity.getMessageId()); String messageId = producer.getProducer().recallMessage(collisionTopic, collisionHandle); assertEquals(sendResult.getMsgId(), messageId); recallCount += 1; } } assertEquals(sendList.size() - 2, recallCount); // one normal and one delay-level message try { await() .pollInterval(1, TimeUnit.SECONDS) .atMost(delaySecond + 15, TimeUnit.SECONDS) .until(() -> { PopResult popResult = popConsumer.pop(brokerAddress, messageQueue, 60 * 1000, -1); processPopResult(recvList, popResult); return recvList.size() == sendList.size(); }); } catch (Exception e) { } assertEquals(sendList.size(), recvList.size()); } private void processPopResult(List<Message> recvList, PopResult popResult) { if (popResult.getPopStatus() == PopStatus.FOUND && popResult.getMsgFoundList() != null) { recvList.addAll(popResult.getMsgFoundList()); } } private List<Message> buildSendMessageList(String topic, int delaySecond) { Message msg0 = new Message(topic, "tag", "Hello RocketMQ".getBytes()); // not supported Message msg1 = new Message(topic, "tag", "Hello RocketMQ".getBytes()); // not supported msg1.setDelayTimeLevel(2); Message msg2 = new Message(topic, "tag", "Hello RocketMQ".getBytes()); msg2.setDelayTimeMs(delaySecond * 1000L); Message msg3 = new Message(topic, "tag", "Hello RocketMQ".getBytes()); msg3.setDelayTimeSec(delaySecond); Message msg4 = new Message(topic, "tag", "Hello RocketMQ".getBytes()); msg4.setDeliverTimeMs(System.currentTimeMillis() + delaySecond * 1000L); return Arrays.asList(msg0, msg1, msg2, msg3, msg4); } }
SendAndRecallDelayMessageIT
java
apache__maven
impl/maven-impl/src/main/java/org/apache/maven/impl/cache/Cache.java
{ "start": 13766, "end": 14709 }
class ____<V> extends ComputeReference<V> { final WeakReference<V> weakRef; WeakComputeReference(V value, ReferenceQueue<V> queue) { super(false); this.weakRef = new WeakReference<>(value, queue); } private WeakComputeReference(ReferenceQueue<V> queue) { super(true); this.weakRef = new WeakReference<>(null, queue); } static <V> WeakComputeReference<V> computing(ReferenceQueue<V> queue) { return new WeakComputeReference<>(queue); } @Override public V get() { return weakRef.get(); } @Override public Reference<V> getReference() { return weakRef; } } // Hard compute reference implementation (strong references) private static
WeakComputeReference
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/net/endpoint/LoadBalancer.java
{ "start": 1098, "end": 4120 }
interface ____ { /** * @implSpec * The default implementation returns a new instance of {@link DefaultInteractionMetrics}. * * @return a new interaction metrics instance */ default InteractionMetrics<?> newMetrics() { return new DefaultInteractionMetrics(); } /** * Simple round-robin load balancer. */ LoadBalancer ROUND_ROBIN = (NoMetricsLoadBalancer) servers -> { AtomicInteger idx = new AtomicInteger(); return () -> { if (servers.isEmpty()) { return -1; } int next = idx.getAndIncrement(); return next % servers.size(); }; }; /** * Least requests load balancer. */ LoadBalancer LEAST_REQUESTS = servers -> () -> { int numberOfRequests = Integer.MAX_VALUE; int selected = -1; int idx = 0; for (ServerEndpoint node : servers) { int val = ((DefaultInteractionMetrics)node.metrics()).numberOfInflightRequests(); if (val < numberOfRequests) { numberOfRequests = val; selected = idx; } idx++; } return selected; }; /** * Random load balancer. */ LoadBalancer RANDOM = (NoMetricsLoadBalancer) servers -> () -> { if (servers.isEmpty()) { return -1; } return ThreadLocalRandom.current().nextInt(servers.size()); }; /** * Power of two choices load balancer. */ LoadBalancer POWER_OF_TWO_CHOICES = servers -> () -> { if (servers.isEmpty()) { return -1; } else if (servers.size() == 1) { return 0; } int i1 = ThreadLocalRandom.current().nextInt(servers.size()); int i2 = ThreadLocalRandom.current().nextInt(servers.size()); while (i2 == i1) { i2 = ThreadLocalRandom.current().nextInt(servers.size()); } if (((DefaultInteractionMetrics) servers.get(i1).metrics()).numberOfInflightRequests() < ((DefaultInteractionMetrics) servers.get(i2).metrics()).numberOfInflightRequests()) { return i1; } return i2; }; /** * Consistent hashing load balancer with 4 virtual servers, falling back to a random load balancer. */ LoadBalancer CONSISTENT_HASHING = consistentHashing(4, RANDOM); /** * Sticky load balancer that uses consistent hashing based on a client provided routing key, defaulting to the {@code fallback} * load balancer when no routing key is provided. * * @param numberOfVirtualServers the number of virtual servers * @param fallback the fallback load balancer for non-sticky requests * @return the load balancer */ static LoadBalancer consistentHashing(int numberOfVirtualServers, LoadBalancer fallback) { return servers -> { ServerSelector fallbackSelector = fallback.selector(servers); return new ConsistentHashingSelector(servers, numberOfVirtualServers, fallbackSelector); }; } /** * Create a stateful endpoint selector. * * @param listOfServers the list of servers * @return the selector */ ServerSelector selector(List<? extends ServerEndpoint> listOfServers); }
LoadBalancer
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/runtime/IpScriptFieldTermsQueryTests.java
{ "start": 1215, "end": 6279 }
class ____ extends AbstractScriptFieldQueryTestCase<IpScriptFieldTermsQuery> { @Override protected IpScriptFieldTermsQuery createTestInstance() { return createTestInstance(between(1, 100)); } protected final IpFieldScript.LeafFactory leafFactory = mock(IpFieldScript.LeafFactory.class); @Override public final void testVisit() { assertEmptyVisit(); } protected static BytesRef encode(InetAddress addr) { return new BytesRef(InetAddressPoint.encode(addr)); } private IpScriptFieldTermsQuery createTestInstance(int size) { BytesRefHash terms = new BytesRefHash(size, BigArrays.NON_RECYCLING_INSTANCE); while (terms.size() < size) { terms.add(new BytesRef(InetAddressPoint.encode(randomIp(randomBoolean())))); } return new IpScriptFieldTermsQuery(randomScript(), leafFactory, randomAlphaOfLength(5), terms); } @Override protected IpScriptFieldTermsQuery copy(IpScriptFieldTermsQuery orig) { return new IpScriptFieldTermsQuery(orig.script(), leafFactory, orig.fieldName(), copyTerms(orig.terms())); } private BytesRefHash copyTerms(BytesRefHash terms) { BytesRefHash copy = new BytesRefHash(terms.size(), BigArrays.NON_RECYCLING_INSTANCE); BytesRef spare = new BytesRef(); for (long i = 0; i < terms.size(); i++) { terms.get(i, spare); assertEquals(i, copy.add(spare)); } return copy; } @Override protected IpScriptFieldTermsQuery mutate(IpScriptFieldTermsQuery orig) { Script script = orig.script(); String fieldName = orig.fieldName(); BytesRefHash terms = copyTerms(orig.terms()); switch (randomInt(2)) { case 0 -> script = randomValueOtherThan(script, this::randomScript); case 1 -> fieldName += "modified"; case 2 -> { long size = terms.size() + 1; while (terms.size() < size) { terms.add(new BytesRef(InetAddressPoint.encode(randomIp(randomBoolean())))); } } default -> fail(); } return new IpScriptFieldTermsQuery(script, leafFactory, fieldName, terms); } @Override public void testMatches() { BytesRef ip1 = encode(InetAddresses.forString("192.168.0.1")); BytesRef ip2 = encode(InetAddresses.forString("192.168.0.2")); BytesRef notIp = encode(InetAddresses.forString("192.168.0.3")); BytesRefHash terms = new BytesRefHash(2, BigArrays.NON_RECYCLING_INSTANCE); terms.add(ip1); terms.add(ip2); IpScriptFieldTermsQuery query = new IpScriptFieldTermsQuery(randomScript(), leafFactory, "test", terms); BytesRefHash.Finder finder = terms.newFinder(); assertTrue(query.matches(new BytesRef[] { ip1 }, 1, finder)); assertTrue(query.matches(new BytesRef[] { ip2 }, 1, finder)); assertTrue(query.matches(new BytesRef[] { ip1, notIp }, 2, finder)); assertTrue(query.matches(new BytesRef[] { notIp, ip1 }, 2, finder)); assertFalse(query.matches(new BytesRef[] { notIp }, 1, finder)); assertFalse(query.matches(new BytesRef[] { notIp, ip1 }, 1, finder)); } @Override protected void assertToString(IpScriptFieldTermsQuery query) { if (query.toString(query.fieldName()).contains("...")) { assertBigToString(query); } else { assertLittleToString(query); } } private void assertBigToString(IpScriptFieldTermsQuery query) { String toString = query.toString(query.fieldName()); BytesRef spare = new BytesRef(); assertThat(toString, startsWith("[")); query.terms().get(0, spare); assertThat( toString, containsString(InetAddresses.toAddrString(InetAddressPoint.decode(BytesReference.toBytes(new BytesArray(spare))))) ); query.terms().get(query.terms().size() - 1, spare); assertThat( toString, not(containsString(InetAddresses.toAddrString(InetAddressPoint.decode(BytesReference.toBytes(new BytesArray(spare)))))) ); assertThat(toString, endsWith("...]")); } private void assertLittleToString(IpScriptFieldTermsQuery query) { String toString = query.toString(query.fieldName()); BytesRef spare = new BytesRef(); assertThat(toString, startsWith("[")); for (long i = 0; i < query.terms().size(); i++) { query.terms().get(i, spare); assertThat( toString, containsString(InetAddresses.toAddrString(InetAddressPoint.decode(BytesReference.toBytes(new BytesArray(spare))))) ); } assertThat(toString, endsWith("]")); } public void testBigToString() { assertBigToString(createTestInstance(1000)); } public void testLittleToString() { assertLittleToString(createTestInstance(5)); } }
IpScriptFieldTermsQueryTests
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/google/MultisetTestSuiteBuilder.java
{ "start": 2698, "end": 7033 }
class ____ @Override protected List<Class<? extends AbstractTester>> getTesters() { List<Class<? extends AbstractTester>> testers = copyToList(super.getTesters()); testers.add(CollectionSerializationEqualTester.class); testers.add(MultisetAddTester.class); testers.add(MultisetContainsTester.class); testers.add(MultisetCountTester.class); testers.add(MultisetElementSetTester.class); testers.add(MultisetEqualsTester.class); testers.add(MultisetReadsTester.class); testers.add(MultisetSetCountConditionallyTester.class); testers.add(MultisetSetCountUnconditionallyTester.class); testers.add(MultisetRemoveTester.class); testers.add(MultisetEntrySetTester.class); testers.add(MultisetIteratorTester.class); testers.add(MultisetSerializationTester.class); return testers; } private static Set<Feature<?>> computeEntrySetFeatures(Set<Feature<?>> features) { Set<Feature<?>> derivedFeatures = new HashSet<>(features); derivedFeatures.remove(CollectionFeature.GENERAL_PURPOSE); derivedFeatures.remove(CollectionFeature.SUPPORTS_ADD); derivedFeatures.remove(CollectionFeature.ALLOWS_NULL_VALUES); derivedFeatures.add(CollectionFeature.REJECTS_DUPLICATES_AT_CREATION); if (!derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) { derivedFeatures.remove(CollectionFeature.SERIALIZABLE); } return derivedFeatures; } static Set<Feature<?>> computeElementSetFeatures(Set<Feature<?>> features) { Set<Feature<?>> derivedFeatures = new HashSet<>(features); derivedFeatures.remove(CollectionFeature.GENERAL_PURPOSE); derivedFeatures.remove(CollectionFeature.SUPPORTS_ADD); if (!derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS)) { derivedFeatures.remove(CollectionFeature.SERIALIZABLE); } return derivedFeatures; } private static Set<Feature<?>> computeReserializedMultisetFeatures(Set<Feature<?>> features) { Set<Feature<?>> derivedFeatures = new HashSet<>(features); derivedFeatures.remove(CollectionFeature.SERIALIZABLE); derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); return derivedFeatures; } @Override protected List<TestSuite> createDerivedSuites( FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) { List<TestSuite> derivedSuites = new ArrayList<>(super.createDerivedSuites(parentBuilder)); derivedSuites.add(createElementSetTestSuite(parentBuilder)); if (!parentBuilder.getFeatures().contains(NoRecurse.NO_ENTRY_SET)) { derivedSuites.add( SetTestSuiteBuilder.using(new EntrySetGenerator<E>(parentBuilder.getSubjectGenerator())) .named(getName() + ".entrySet") .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures())) .suppressing(parentBuilder.getSuppressedTests()) .withSetUp(parentBuilder.getSetUp()) .withTearDown(parentBuilder.getTearDown()) .createTestSuite()); } if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) { derivedSuites.add( MultisetTestSuiteBuilder.using( new ReserializedMultisetGenerator<E>(parentBuilder.getSubjectGenerator())) .named(getName() + " reserialized") .withFeatures(computeReserializedMultisetFeatures(parentBuilder.getFeatures())) .suppressing(parentBuilder.getSuppressedTests()) .withSetUp(parentBuilder.getSetUp()) .withTearDown(parentBuilder.getTearDown()) .createTestSuite()); } return derivedSuites; } TestSuite createElementSetTestSuite( FeatureSpecificTestSuiteBuilder<?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) { return SetTestSuiteBuilder.using( new ElementSetGenerator<E>(parentBuilder.getSubjectGenerator())) .named(getName() + ".elementSet") .withFeatures(computeElementSetFeatures(parentBuilder.getFeatures())) .suppressing(parentBuilder.getSuppressedTests()) .withSetUp(parentBuilder.getSetUp()) .withTearDown(parentBuilder.getTearDown()) .createTestSuite(); } static final
literals
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/connections/ConnectionProviderFromBeanContainerTest.java
{ "start": 1116, "end": 3123 }
class ____ { private final ConnectionProvider dummyConnectionProvider = new DummyConnectionProvider(); private Map<String, Object> createSettings() { Map<String, Object> settings = new HashMap<>(); settings.put( AvailableSettings.ALLOW_EXTENSIONS_IN_CDI, "true" ); settings.put( AvailableSettings.BEAN_CONTAINER, new BeanContainer() { @Override @SuppressWarnings("unchecked") public <B> ContainedBean<B> getBean( Class<B> beanType, LifecycleOptions lifecycleOptions, BeanInstanceProducer fallbackProducer) { return new ContainedBean<>() { @Override public B getBeanInstance() { return (B) (beanType == DummyConnectionProvider.class ? dummyConnectionProvider : fallbackProducer.produceBeanInstance( beanType )); } @Override public Class<B> getBeanClass() { return beanType; } }; } @Override public <B> ContainedBean<B> getBean( String name, Class<B> beanType, LifecycleOptions lifecycleOptions, BeanInstanceProducer fallbackProducer) { return new ContainedBean<>() { @Override public B getBeanInstance() { return fallbackProducer.produceBeanInstance( beanType ); } @Override public Class<B> getBeanClass() { return beanType; } }; } @Override public void stop() { } } ); return settings; } @Test public void testProviderFromBeanContainerInUse() { Map<String, Object> settings = createSettings(); settings.putIfAbsent( CONNECTION_PROVIDER, DummyConnectionProvider.class.getName() ); ServiceRegistry serviceRegistry = ServiceRegistryUtil.serviceRegistryBuilder() .applySettings( settings ).build(); try { ConnectionProvider providerInUse = serviceRegistry.getService( ConnectionProvider.class ); assertThat( providerInUse ).isSameAs( dummyConnectionProvider ); } finally { StandardServiceRegistryBuilder.destroy( serviceRegistry ); } } public static
ConnectionProviderFromBeanContainerTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSPermission.java
{ "start": 41267, "end": 43179 }
class ____ extends PermissionVerifier { private Path dst; private short dstAncestorPermission; private short dstParentPermission; /* initialize */ void set(Path src, short srcAncestorPermission, short srcParentPermission, Path dst, short dstAncestorPermission, short dstParentPermission) { super.set(src, srcAncestorPermission, srcParentPermission, NULL_MASK); this.dst = dst; this.dstAncestorPermission = dstAncestorPermission; this.dstParentPermission = dstParentPermission; } @Override void setOpPermission() { opParentPermission = SEARCH_MASK | WRITE_MASK; } @Override void call() throws IOException { fs.rename(path, dst); } @Override protected boolean expectPermissionDeny() { return super.expectPermissionDeny() || (requiredParentPermission & dstParentPermission) != requiredParentPermission || (requiredAncestorPermission & dstAncestorPermission) != requiredAncestorPermission; } @Override protected void logPermissions() { super.logPermissions(); LOG.info("dst ancestor permission: " + Integer.toOctalString(dstAncestorPermission)); LOG.info("dst parent permission: " + Integer.toOctalString(dstParentPermission)); } } final RenamePermissionVerifier renameVerifier = new RenamePermissionVerifier(); /* test if the permission checking of rename is correct */ private void testRename(UserGroupInformation ugi, Path src, Path dst, short srcAncestorPermission, short srcParentPermission, short dstAncestorPermission, short dstParentPermission) throws Exception { renameVerifier.set(src, srcAncestorPermission, srcParentPermission, dst, dstAncestorPermission, dstParentPermission); renameVerifier.verifyPermission(ugi); } /* A
RenamePermissionVerifier
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/BaseCollectorTestCase.java
{ "start": 1582, "end": 4942 }
class ____ extends ESTestCase { protected ClusterName clusterName; protected ClusterService clusterService; protected ClusterState clusterState; protected DiscoveryNodes nodes; protected Metadata metadata; protected ProjectMetadata projectMetadata; protected MockLicenseState licenseState; protected Client client; protected Settings settings; @Override public void setUp() throws Exception { super.setUp(); clusterName = mock(ClusterName.class); clusterService = mock(ClusterService.class); clusterState = mock(ClusterState.class); nodes = mock(DiscoveryNodes.class); metadata = mock(Metadata.class); projectMetadata = mock(ProjectMetadata.class); when(metadata.getProject(any())).thenReturn(projectMetadata); licenseState = mock(MockLicenseState.class); client = mock(Client.class); ThreadPool threadPool = mock(ThreadPool.class); when(client.threadPool()).thenReturn(threadPool); when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY)); settings = Settings.builder().put("path.home", createTempDir()).build(); } protected void whenLocalNodeElectedMaster(final boolean electedMaster) { when(clusterService.state()).thenReturn(clusterState); when(clusterState.getNodes()).thenReturn(nodes); when(nodes.isLocalNodeElectedMaster()).thenReturn(electedMaster); } protected void whenClusterStateWithName(final String name) { when(clusterName.value()).thenReturn(name); when(clusterService.getClusterName()).thenReturn(clusterName); when(clusterState.getClusterName()).thenReturn(clusterName); } protected void whenClusterStateWithUUID(final String clusterUUID) { when(clusterService.state()).thenReturn(clusterState); when(clusterState.metadata()).thenReturn(metadata); when(metadata.clusterUUID()).thenReturn(clusterUUID); } protected void withCollectionTimeout(final Setting<TimeValue> collectionTimeout, final TimeValue timeout) throws Exception { withCollectionSetting(builder -> builder.put(collectionTimeout.getKey(), timeout.getStringRep())); } protected void withCollectionIndices(final String[] collectionIndices) throws Exception { final String key = Collector.INDICES.getKey(); if (collectionIndices != null) { withCollectionSetting(builder -> builder.putList(key, collectionIndices)); } else { withCollectionSetting(builder -> builder.putNull(key)); } } protected void withCollectionSetting(final Function<Settings.Builder, Settings.Builder> builder) throws Exception { settings = Settings.builder().put(settings).put(builder.apply(Settings.builder()).build()).build(); when(clusterService.getClusterSettings()).thenReturn(new ClusterSettings(settings, Sets.newHashSet(new Monitoring(settings) { @Override protected XPackLicenseState getLicenseState() { return licenseState; } }.getSettings()))); } protected static DiscoveryNode localNode(final String uuid) { return DiscoveryNodeUtils.create(uuid, new TransportAddress(TransportAddress.META_ADDRESS, 9300)); } }
BaseCollectorTestCase
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/FlatpackEndpointBuilderFactory.java
{ "start": 26492, "end": 33900 }
interface ____ extends EndpointConsumerBuilder { default FlatpackEndpointConsumerBuilder basic() { return (FlatpackEndpointConsumerBuilder) this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedFlatpackEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedFlatpackEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedFlatpackEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedFlatpackEndpointConsumerBuilder exceptionHandler(String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedFlatpackEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedFlatpackEndpointConsumerBuilder exchangePattern(String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option is a: * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedFlatpackEndpointConsumerBuilder pollStrategy(org.apache.camel.spi.PollingConsumerPollStrategy pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option will be converted to a * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedFlatpackEndpointConsumerBuilder pollStrategy(String pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } } /** * Builder for endpoint producers for the Flatpack component. */ public
AdvancedFlatpackEndpointConsumerBuilder
java
google__dagger
javatests/dagger/internal/codegen/ProductionComponentProcessorTest.java
{ "start": 14374, "end": 15338 }
interface ____ {", " ProductionScoped productionScoped();", "}"); CompilerTests.daggerCompiler(productionScoped, parent, child) .withProcessingOptions(compilerMode.processorOptions()) .compile( subject -> { subject.hasErrorCount(0); subject.generatedSource(goldenFileRule.goldenSource("test/DaggerParent")); }); } @Test public void requestProducerNodeWithProvider_failsWithNotSupportedError() { Source producerModuleFile = CompilerTests.javaSource( "test.SimpleModule", "package test;", "", "import dagger.producers.ProducerModule;", "import dagger.producers.Produces;", "import javax.inject.Provider;", "import java.util.concurrent.Executor;", "import dagger.producers.Production;", "", "@ProducerModule", "final
Child
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/watermark/WatermarkParams.java
{ "start": 1169, "end": 4877 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; private WatermarkEmitStrategy emitStrategy; private String alignGroupName; private Duration alignMaxDrift; private Duration alignUpdateInterval; private long sourceIdleTimeout; public WatermarkParams() {} public WatermarkParams( WatermarkEmitStrategy emitStrategy, String alignGroupName, Duration alignMaxDrift, Duration alignUpdateInterval, long sourceIdleTimeout) { this.emitStrategy = emitStrategy; this.alignGroupName = alignGroupName; this.alignMaxDrift = alignMaxDrift; this.alignUpdateInterval = alignUpdateInterval; this.sourceIdleTimeout = sourceIdleTimeout; } public WatermarkEmitStrategy getEmitStrategy() { return emitStrategy; } public void setEmitStrategy(WatermarkEmitStrategy emitStrategy) { this.emitStrategy = emitStrategy; } public String getAlignGroupName() { return alignGroupName; } public void setAlignGroupName(String alignGroupName) { this.alignGroupName = alignGroupName; } public Duration getAlignMaxDrift() { return alignMaxDrift; } public void setAlignMaxDrift(Duration alignMaxDrift) { this.alignMaxDrift = alignMaxDrift; } public Duration getAlignUpdateInterval() { return alignUpdateInterval; } public void setAlignUpdateInterval(Duration alignUpdateInterval) { this.alignUpdateInterval = alignUpdateInterval; } public long getSourceIdleTimeout() { return sourceIdleTimeout; } public void setSourceIdleTimeout(long sourceIdleTimeout) { this.sourceIdleTimeout = sourceIdleTimeout; } public boolean alignWatermarkEnabled() { return !StringUtils.isNullOrWhitespaceOnly(alignGroupName) && isLegalDuration(alignMaxDrift) && isLegalDuration(alignUpdateInterval); } private boolean isLegalDuration(Duration duration) { return duration != null && !duration.isNegative() && !duration.isZero(); } public static WatermarkParamsBuilder builder() { return new WatermarkParamsBuilder(); } @Override public String toString() { return "WatermarkParams{" + "emitStrategy=" + emitStrategy + ", alignGroupName='" + alignGroupName + '\'' + ", alignMaxDrift=" + alignMaxDrift + ", alignUpdateInterval=" + alignUpdateInterval + ", sourceIdleTimeout=" + sourceIdleTimeout + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WatermarkParams that = (WatermarkParams) o; return sourceIdleTimeout == that.sourceIdleTimeout && emitStrategy == that.emitStrategy && Objects.equals(alignGroupName, that.alignGroupName) && Objects.equals(alignMaxDrift, that.alignMaxDrift) && Objects.equals(alignUpdateInterval, that.alignUpdateInterval); } @Override public int hashCode() { return Objects.hash( emitStrategy, alignGroupName, alignMaxDrift, alignUpdateInterval, sourceIdleTimeout); } /** Builder of WatermarkHintParams. */ @Internal public static
WatermarkParams
java
elastic__elasticsearch
modules/parent-join/src/internalClusterTest/java/org/elasticsearch/join/aggregations/AbstractParentChildTestCase.java
{ "start": 912, "end": 1006 }
class ____ combines stuff used for Children and Parent aggregation tests */ public abstract
which
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/MetadataLoadBalancerProvider.java
{ "start": 5113, "end": 5778 }
class ____ extends SubchannelPicker { private final SubchannelPicker delegatePicker; private final String metadataKey; private final String metadataValue; MetadataPicker(SubchannelPicker delegatePicker, String metadataKey, String metadataValue) { this.delegatePicker = delegatePicker; this.metadataKey = metadataKey; this.metadataValue = metadataValue; } @Override public PickResult pickSubchannel(PickSubchannelArgs args) { args.getHeaders() .put(Metadata.Key.of(metadataKey, Metadata.ASCII_STRING_MARSHALLER), metadataValue); return delegatePicker.pickSubchannel(args); } } }
MetadataPicker
java
spring-projects__spring-framework
spring-core/src/main/java24/org/springframework/core/type/classreading/ClassFileClassMetadata.java
{ "start": 6462, "end": 8281 }
class ____ { private final ClassLoader clasLoader; private String className; private AccessFlags accessFlags; private Set<AccessFlag> innerAccessFlags; private @Nullable String enclosingClassName; private @Nullable String superClassName; private Set<String> interfaceNames = new LinkedHashSet<>(4); private Set<String> memberClassNames = new LinkedHashSet<>(4); private Set<MethodMetadata> declaredMethods = new LinkedHashSet<>(4); private MergedAnnotations mergedAnnotations = MergedAnnotations.of(Collections.emptySet()); public Builder(ClassLoader classLoader) { this.clasLoader = classLoader; } void classEntry(ClassEntry classEntry) { this.className = ClassUtils.convertResourcePathToClassName(classEntry.name().stringValue()); } void accessFlags(AccessFlags accessFlags) { this.accessFlags = accessFlags; } void enclosingClass(ClassEntry thisClass) { String thisClassName = thisClass.name().stringValue(); int currentClassIndex = thisClassName.lastIndexOf('$'); this.enclosingClassName = ClassUtils.convertResourcePathToClassName(thisClassName.substring(0, currentClassIndex)); } void superClass(Superclass superClass) { this.superClassName = ClassUtils.convertResourcePathToClassName(superClass.superclassEntry().name().stringValue()); } void interfaces(Interfaces interfaces) { for (ClassEntry entry : interfaces.interfaces()) { this.interfaceNames.add(ClassUtils.convertResourcePathToClassName(entry.name().stringValue())); } } void nestMembers(String currentClassName, InnerClassesAttribute innerClasses) { for (InnerClassInfo classInfo : innerClasses.classes()) { String innerClassName = classInfo.innerClass().name().stringValue(); if (currentClassName.equals(innerClassName)) { // the current
Builder
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/blockhash/BlockHashTestCase.java
{ "start": 1915, "end": 10764 }
class ____ extends ESTestCase { final CircuitBreaker breaker = newLimitedBreaker(ByteSizeValue.ofGb(1)); final BigArrays bigArrays = new MockBigArrays(PageCacheRecycler.NON_RECYCLING_INSTANCE, mockBreakerService(breaker)); final MockBlockFactory blockFactory = new MockBlockFactory(breaker, bigArrays); @After public void checkBreaker() { blockFactory.ensureAllBlocksAreReleased(); assertThat(breaker.getUsed(), is(0L)); } // A breaker service that always returns the given breaker for getBreaker(CircuitBreaker.REQUEST) private static CircuitBreakerService mockBreakerService(CircuitBreaker breaker) { CircuitBreakerService breakerService = mock(CircuitBreakerService.class); when(breakerService.getBreaker(CircuitBreaker.REQUEST)).thenReturn(breaker); return breakerService; } protected record OrdsAndKeys(String description, int positionOffset, IntBlock ords, Block[] keys, IntVector nonEmpty) {} protected static void hash(boolean collectKeys, BlockHash blockHash, Consumer<OrdsAndKeys> callback, Block... values) { blockHash.add(new Page(values), new GroupingAggregatorFunction.AddInput() { private void addBlock(int positionOffset, IntBlock groupIds) { OrdsAndKeys result = new OrdsAndKeys( blockHash.toString(), positionOffset, groupIds, collectKeys ? blockHash.getKeys() : null, blockHash.nonEmpty() ); try { Set<Integer> allowedOrds = new HashSet<>(); for (int p = 0; p < result.nonEmpty.getPositionCount(); p++) { allowedOrds.add(result.nonEmpty.getInt(p)); } for (int p = 0; p < result.ords.getPositionCount(); p++) { if (result.ords.isNull(p)) { continue; } int start = result.ords.getFirstValueIndex(p); int end = start + result.ords.getValueCount(p); for (int i = start; i < end; i++) { int ord = result.ords.getInt(i); if (false == allowedOrds.contains(ord)) { fail("ord is not allowed " + ord); } } } callback.accept(result); } finally { Releasables.close(result.keys == null ? null : Releasables.wrap(result.keys), result.nonEmpty); } } @Override public void add(int positionOffset, IntArrayBlock groupIds) { addBlock(positionOffset, groupIds); } @Override public void add(int positionOffset, IntBigArrayBlock groupIds) { addBlock(positionOffset, groupIds); } @Override public void add(int positionOffset, IntVector groupIds) { addBlock(positionOffset, groupIds.asBlock()); } @Override public void close() { fail("hashes should not close AddInput"); } }); if (blockHash instanceof LongLongBlockHash == false && blockHash instanceof BytesRefLongBlockHash == false && blockHash instanceof BytesRef2BlockHash == false && blockHash instanceof BytesRef3BlockHash == false) { Block[] keys = blockHash.getKeys(); try (ReleasableIterator<IntBlock> lookup = blockHash.lookup(new Page(keys), ByteSizeValue.ofKb(between(1, 100)))) { while (lookup.hasNext()) { try (IntBlock ords = lookup.next()) { for (int p = 0; p < ords.getPositionCount(); p++) { assertFalse(ords.isNull(p)); } } } } finally { Releasables.closeExpectNoException(keys); } } } private static void assertSeenGroupIdsAndNonEmpty(BlockHash blockHash) { try (BitArray seenGroupIds = blockHash.seenGroupIds(BigArrays.NON_RECYCLING_INSTANCE); IntVector nonEmpty = blockHash.nonEmpty()) { assertThat( "seenGroupIds cardinality doesn't match with nonEmpty size", seenGroupIds.cardinality(), equalTo((long) nonEmpty.getPositionCount()) ); for (int position = 0; position < nonEmpty.getPositionCount(); position++) { int groupId = nonEmpty.getInt(position); assertThat("group " + groupId + " from nonEmpty isn't set in seenGroupIds", seenGroupIds.get(groupId), is(true)); } } } protected void assertOrds(IntBlock ordsBlock, Integer... expectedOrds) { assertOrds(ordsBlock, Arrays.stream(expectedOrds).map(l -> l == null ? null : new int[] { l }).toArray(int[][]::new)); } protected void assertOrds(IntBlock ordsBlock, int[]... expectedOrds) { assertEquals(expectedOrds.length, ordsBlock.getPositionCount()); for (int p = 0; p < expectedOrds.length; p++) { int start = ordsBlock.getFirstValueIndex(p); int count = ordsBlock.getValueCount(p); if (expectedOrds[p] == null) { if (false == ordsBlock.isNull(p)) { StringBuilder error = new StringBuilder(); error.append(p); error.append(": expected null but was ["); for (int i = 0; i < count; i++) { if (i != 0) { error.append(", "); } error.append(ordsBlock.getInt(start + i)); } fail(error.append("]").toString()); } continue; } assertFalse(p + ": expected not null", ordsBlock.isNull(p)); int[] actual = new int[count]; for (int i = 0; i < count; i++) { actual[i] = ordsBlock.getInt(start + i); } assertThat("position " + p, actual, equalTo(expectedOrds[p])); } } protected void assertKeys(Block[] actualKeys, Object... expectedKeys) { Object[][] flipped = new Object[expectedKeys.length][]; for (int r = 0; r < flipped.length; r++) { flipped[r] = new Object[] { expectedKeys[r] }; } assertKeys(actualKeys, flipped); } protected void assertKeys(Block[] actualKeys, Object[][] expectedKeys) { for (int r = 0; r < expectedKeys.length; r++) { assertThat(actualKeys, arrayWithSize(expectedKeys[r].length)); } for (int c = 0; c < actualKeys.length; c++) { assertThat("block " + c, actualKeys[c].getPositionCount(), equalTo(expectedKeys.length)); } for (int r = 0; r < expectedKeys.length; r++) { for (int c = 0; c < actualKeys.length; c++) { if (expectedKeys[r][c] == null) { assertThat("expected null key", actualKeys[c].isNull(r), equalTo(true)); continue; } assertThat("expected non-null key", actualKeys[c].isNull(r), equalTo(false)); if (expectedKeys[r][c] instanceof Integer v) { assertThat(((IntBlock) actualKeys[c]).getInt(r), equalTo(v)); } else if (expectedKeys[r][c] instanceof Long v) { assertThat(((LongBlock) actualKeys[c]).getLong(r), equalTo(v)); } else if (expectedKeys[r][c] instanceof Double v) { assertThat(((DoubleBlock) actualKeys[c]).getDouble(r), equalTo(v)); } else if (expectedKeys[r][c] instanceof String v) { assertThat(((BytesRefBlock) actualKeys[c]).getBytesRef(r, new BytesRef()), equalTo(new BytesRef(v))); } else if (expectedKeys[r][c] instanceof Boolean v) { assertThat(((BooleanBlock) actualKeys[c]).getBoolean(r), equalTo(v)); } else { throw new IllegalArgumentException("unsupported type " + expectedKeys[r][c].getClass()); } } } } protected IntVector intRange(int startInclusive, int endExclusive) { return IntVector.range(startInclusive, endExclusive, TestBlockFactory.getNonBreakingInstance()); } protected IntVector intVector(int... values) { return TestBlockFactory.getNonBreakingInstance().newIntArrayVector(values, values.length); } }
BlockHashTestCase
java
processing__processing4
java/src/processing/mode/java/tweak/HProgressBar.java
{ "start": 958, "end": 2573 }
class ____ { int x, y, size, width; int pos; int lPolyX, rPolyX; Polygon rightPoly, leftPoly; public HProgressBar(int size, int width) { this.size = size; this.width = width; x = 0; y = 0; setPos(0); int xl[] = {0, 0, -(int)(size/1.5)}; int yl[] = {-(int)((float)size/3), (int)((float)size/3), 0}; leftPoly = new Polygon(xl, yl, 3); int xr[] = {0, (int)(size/1.5), 0}; int yr[] = {-(int)((float)size/3), 0, (int)((float)size/3)}; rightPoly = new Polygon(xr, yr, 3); } public void setPos(int pos) { this.pos = pos; lPolyX = 0; rPolyX = 0; if (pos > 0) { rPolyX = pos; } else if (pos < 0) { lPolyX = pos; } } public void setWidth(int width) { this.width = width; } public void draw(Graphics2D g2d) { AffineTransform trans = g2d.getTransform(); g2d.translate(x, y); // draw white cover on text line g2d.setColor(ColorScheme.getInstance().whitePaneColor); g2d.fillRect(-200+lPolyX, -size, 200-lPolyX-width/2, size+1); g2d.fillRect(width/2, -size, 200+rPolyX, size+1); // draw left and right triangles and leading line g2d.setColor(ColorScheme.getInstance().progressFillColor); AffineTransform tmp = g2d.getTransform(); g2d.translate(-width/2 - 5 + lPolyX, -size/2); g2d.fillRect(0, -1, -lPolyX, 2); g2d.fillPolygon(leftPoly); g2d.setTransform(tmp); g2d.translate(width/2 + 5 + rPolyX, -size/2); g2d.fillRect(-rPolyX, -1, rPolyX+1, 2); g2d.fillPolygon(rightPoly); g2d.setTransform(tmp); g2d.setTransform(trans); } }
HProgressBar
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/descriptors/FileSystemValidator.java
{ "start": 1168, "end": 1627 }
class ____ extends ConnectorDescriptorValidator { public static final String CONNECTOR_TYPE_VALUE = "filesystem"; public static final String CONNECTOR_PATH = "connector.path"; @Override public void validate(DescriptorProperties properties) { super.validate(properties); properties.validateValue(CONNECTOR_TYPE, CONNECTOR_TYPE_VALUE, false); properties.validateString(CONNECTOR_PATH, false, 1); } }
FileSystemValidator
java
apache__camel
components/camel-thrift/src/test/java/org/apache/camel/component/thrift/generated/Calculator.java
{ "start": 33122, "end": 34118 }
class ____<I extends Iface> extends org.apache.thrift.ProcessFunction<I, echo_args, echo_result> { public echo() { super("echo"); } @Override public echo_args getEmptyArgsInstance() { return new echo_args(); } @Override public boolean isOneway() { return false; } @Override protected boolean rethrowUnhandledExceptions() { return false; } @Override public echo_result getEmptyResultInstance() { return new echo_result(); } @Override public echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException { echo_result result = getEmptyResultInstance(); result.success = iface.echo(args.w); return result; } } public static
echo
java
apache__kafka
connect/mirror/src/test/java/org/apache/kafka/connect/mirror/integration/MirrorConnectorsWithCustomForwardingAdminIntegrationTest.java
{ "start": 3133, "end": 19210 }
class ____ extends MirrorConnectorsIntegrationBaseTest { private static final int TOPIC_ACL_SYNC_DURATION_MS = 30_000; private static final int FAKE_LOCAL_METADATA_STORE_SYNC_DURATION_MS = 60_000; /* * enable ACL on brokers. */ protected static void enableAclAuthorizer(Properties brokerProps) { brokerProps.put(SocketServerConfigs.LISTENER_SECURITY_PROTOCOL_MAP_CONFIG, "CONTROLLER:SASL_PLAINTEXT,EXTERNAL:SASL_PLAINTEXT"); brokerProps.put(ServerConfigs.AUTHORIZER_CLASS_NAME_CONFIG, "org.apache.kafka.metadata.authorizer.StandardAuthorizer"); brokerProps.put(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG, "PLAIN"); brokerProps.put(BrokerSecurityConfigs.SASL_MECHANISM_INTER_BROKER_PROTOCOL_CONFIG, "PLAIN"); brokerProps.put(KRaftConfigs.SASL_MECHANISM_CONTROLLER_PROTOCOL_CONFIG, "PLAIN"); String listenerSaslJaasConfig = "org.apache.kafka.common.security.plain.PlainLoginModule required " + "username=\"super\" " + "password=\"super_pwd\" " + "user_connector=\"connector_pwd\" " + "user_super=\"super_pwd\";"; brokerProps.put("listener.name.external.plain.sasl.jaas.config", listenerSaslJaasConfig); brokerProps.put("listener.name.controller.plain.sasl.jaas.config", listenerSaslJaasConfig); brokerProps.put("super.users", "User:super"); } /* * return superUser auth config. */ protected static Map<String, String> superUserConfig() { Map<String, String> superUserClientConfig = new HashMap<>(); superUserClientConfig.put("sasl.mechanism", "PLAIN"); superUserClientConfig.put("security.protocol", "SASL_PLAINTEXT"); superUserClientConfig.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required " + "username=\"super\" " + "password=\"super_pwd\";"); return superUserClientConfig; } /* * return connect user auth config. */ protected static Map<String, String> connectorUserConfig() { Map<String, String> connectUserClientConfig = new HashMap<>(); connectUserClientConfig.put("sasl.mechanism", "PLAIN"); connectUserClientConfig.put("security.protocol", "SASL_PLAINTEXT"); connectUserClientConfig.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required " + "username=\"connector\" " + "password=\"connector_pwd\";"); return connectUserClientConfig; } /* * delete all acls from the input kafka cluster */ private static void deleteAllACLs(EmbeddedKafkaCluster cluster) throws Exception { try (final Admin adminClient = cluster.createAdminClient()) { Set<String> topicsToBeDeleted = adminClient.listTopics().names().get(); List<AclBindingFilter> aclBindingFilters = topicsToBeDeleted.stream().map(topic -> new AclBindingFilter( new ResourcePatternFilter(ResourceType.TOPIC, topic, PatternType.ANY), AccessControlEntryFilter.ANY ) ).collect(Collectors.toList()); adminClient.deleteAcls(aclBindingFilters); } } /* * retrieve the acl details based on the input cluster for given topic name. */ protected static Collection<AclBinding> getAclBindings(EmbeddedKafkaCluster cluster, String topic) throws Exception { try (Admin client = cluster.createAdminClient()) { ResourcePatternFilter topicFilter = new ResourcePatternFilter(ResourceType.TOPIC, topic, PatternType.ANY); return client.describeAcls(new AclBindingFilter(topicFilter, AccessControlEntryFilter.ANY)).values().get(); } } @BeforeEach public void startClusters() throws Exception { enableAclAuthorizer(primaryBrokerProps); additionalPrimaryClusterClientsConfigs.putAll(superUserConfig()); primaryWorkerProps.putAll(superUserConfig()); enableAclAuthorizer(backupBrokerProps); additionalBackupClusterClientsConfigs.putAll(superUserConfig()); backupWorkerProps.putAll(superUserConfig()); Map<String, String> additionalConfig = new HashMap<>(superUserConfig()) {{ put(FORWARDING_ADMIN_CLASS, FakeForwardingAdminWithLocalMetadata.class.getName()); }}; superUserConfig().forEach((property, value) -> { additionalConfig.put(CONNECTOR_CLIENT_CONSUMER_OVERRIDES_PREFIX + property, value); additionalConfig.put(CONNECTOR_CLIENT_PRODUCER_OVERRIDES_PREFIX + property, value); additionalConfig.put("consumer." + property, value); additionalConfig.put("producer." + property, value); }); connectorUserConfig().forEach((property, value) -> { additionalConfig.put("admin." + property, value); additionalConfig.put(CONNECTOR_CLIENT_ADMIN_OVERRIDES_PREFIX + property, value); }); startClusters(additionalConfig); try (Admin adminClient = primary.kafka().createAdminClient()) { adminClient.createAcls(List.of( new AclBinding( new ResourcePattern(ResourceType.TOPIC, "*", PatternType.LITERAL), new AccessControlEntry("User:connector", "*", AclOperation.ALL, AclPermissionType.ALLOW) ) )).all().get(); } try (Admin adminClient = backup.kafka().createAdminClient()) { adminClient.createAcls(List.of( new AclBinding( new ResourcePattern(ResourceType.TOPIC, "*", PatternType.LITERAL), new AccessControlEntry("User:connector", "*", AclOperation.ALL, AclPermissionType.ALLOW) ) )).all().get(); } } @AfterEach public void shutdownClusters() throws Exception { deleteAllACLs(primary.kafka()); deleteAllACLs(backup.kafka()); FakeLocalMetadataStore.clear(); super.shutdownClusters(); } @Test public void testReplicationIsCreatingTopicsUsingProvidedForwardingAdmin() throws Exception { produceMessages(primaryProducer, "test-topic-1"); produceMessages(backupProducer, "test-topic-1"); String consumerGroupName = "consumer-group-testReplication"; Map<String, Object> consumerProps = Map.of("group.id", consumerGroupName); // warm up consumers before starting the connectors so we don't need to wait for discovery warmUpConsumer(consumerProps); mm2Config = new MirrorMakerConfig(mm2Props); waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS); waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS); // make sure the topic is auto-created in the other cluster waitForTopicCreated(primary, "backup.test-topic-1"); waitForTopicCreated(backup, "primary.test-topic-1"); waitForTopicCreated(primary, "mm2-offset-syncs.backup.internal"); waitForTopicCreated(primary, "backup.checkpoints.internal"); waitForTopicCreated(primary, "backup.heartbeats"); waitForTopicCreated(backup, "mm2-offset-syncs.primary.internal"); waitForTopicCreated(backup, "primary.checkpoints.internal"); waitForTopicCreated(backup, "primary.heartbeats"); // expect to use FakeForwardingAdminWithLocalMetadata to create remote topics and internal topics into local store waitForTopicToPersistInFakeLocalMetadataStore("backup.test-topic-1"); waitForTopicToPersistInFakeLocalMetadataStore("primary.test-topic-1"); waitForTopicToPersistInFakeLocalMetadataStore("mm2-offset-syncs.backup.internal"); waitForTopicToPersistInFakeLocalMetadataStore("backup.checkpoints.internal"); waitForTopicToPersistInFakeLocalMetadataStore("backup.heartbeats"); waitForTopicToPersistInFakeLocalMetadataStore("mm2-offset-syncs.primary.internal"); waitForTopicToPersistInFakeLocalMetadataStore("primary.checkpoints.internal"); waitForTopicToPersistInFakeLocalMetadataStore("primary.heartbeats"); waitForTopicToPersistInFakeLocalMetadataStore("heartbeats"); } @Test public void testCreatePartitionsUseProvidedForwardingAdmin() throws Exception { mm2Config = new MirrorMakerConfig(mm2Props); produceMessages(backupProducer, "test-topic-1"); produceMessages(primaryProducer, "test-topic-1"); String consumerGroupName = "consumer-group-testReplication"; Map<String, Object> consumerProps = Map.of("group.id", consumerGroupName); // warm up consumers before starting the connectors so we don't need to wait for discovery warmUpConsumer(consumerProps); waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS); waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS); // make sure the topic is auto-created in the other cluster waitForTopicCreated(primary, "backup.test-topic-1"); waitForTopicCreated(backup, "primary.test-topic-1"); // make sure to remote topics are created using FakeForwardingAdminWithLocalMetadata waitForTopicToPersistInFakeLocalMetadataStore("backup.test-topic-1"); waitForTopicToPersistInFakeLocalMetadataStore("primary.test-topic-1"); // increase number of partitions Map<String, NewPartitions> newPartitions = Map.of("test-topic-1", NewPartitions.increaseTo(NUM_PARTITIONS + 1)); try (Admin adminClient = primary.kafka().createAdminClient()) { adminClient.createPartitions(newPartitions).all().get(); } // make sure partition is created in the other cluster waitForTopicPartitionCreated(backup, "primary.test-topic-1", NUM_PARTITIONS + 1); // expect to use FakeForwardingAdminWithLocalMetadata to update number of partitions in local store waitForTopicConfigPersistInFakeLocalMetaDataStore("primary.test-topic-1", "partitions", String.valueOf(NUM_PARTITIONS + 1)); } @Test public void testSyncTopicConfigUseProvidedForwardingAdmin() throws Exception { mm2Props.put("sync.topic.configs.enabled", "true"); mm2Config = new MirrorMakerConfig(mm2Props); produceMessages(backupProducer, "test-topic-1"); produceMessages(primaryProducer, "test-topic-1"); String consumerGroupName = "consumer-group-testReplication"; Map<String, Object> consumerProps = Map.of("group.id", consumerGroupName); // warm up consumers before starting the connectors so we don't need to wait for discovery warmUpConsumer(consumerProps); waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS); waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS); // make sure the topic is auto-created in the other cluster waitForTopicCreated(primary, "backup.test-topic-1"); waitForTopicCreated(backup, "primary.test-topic-1"); // make sure the topic config is synced into the other cluster assertEquals(TopicConfig.CLEANUP_POLICY_COMPACT, getTopicConfig(backup.kafka(), "primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG), "topic config was synced"); // expect to use FakeForwardingAdminWithLocalMetadata to create remote topics into local store waitForTopicToPersistInFakeLocalMetadataStore("backup.test-topic-1"); waitForTopicToPersistInFakeLocalMetadataStore("primary.test-topic-1"); // expect to use FakeForwardingAdminWithLocalMetadata to update topic config in local store waitForTopicConfigPersistInFakeLocalMetaDataStore("primary.test-topic-1", TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT); } @Test public void testSyncTopicACLsUseProvidedForwardingAdmin() throws Exception { mm2Props.put("sync.topic.acls.enabled", "true"); mm2Props.put("sync.topic.acls.interval.seconds", "1"); mm2Config = new MirrorMakerConfig(mm2Props); List<AclBinding> aclBindings = List.of( new AclBinding( new ResourcePattern(ResourceType.TOPIC, "test-topic-1", PatternType.LITERAL), new AccessControlEntry("User:dummy", "*", AclOperation.DESCRIBE, AclPermissionType.ALLOW) ) ); try (Admin adminClient = primary.kafka().createAdminClient()) { adminClient.createAcls(aclBindings).all().get(); } try (Admin adminClient = backup.kafka().createAdminClient()) { adminClient.createAcls(aclBindings).all().get(); } waitUntilMirrorMakerIsRunning(primary, CONNECTOR_LIST, mm2Config, BACKUP_CLUSTER_ALIAS, PRIMARY_CLUSTER_ALIAS); waitUntilMirrorMakerIsRunning(backup, CONNECTOR_LIST, mm2Config, PRIMARY_CLUSTER_ALIAS, BACKUP_CLUSTER_ALIAS); // make sure the topic is auto-created in the other cluster waitForTopicCreated(primary, "backup.test-topic-1"); waitForTopicCreated(backup, "primary.test-topic-1"); // expect to use FakeForwardingAdminWithLocalMetadata to update topic ACLs on remote cluster AclBinding expectedACLOnBackupCluster = new AclBinding( new ResourcePattern(ResourceType.TOPIC, "primary.test-topic-1", PatternType.LITERAL), new AccessControlEntry("User:dummy", "*", AclOperation.DESCRIBE, AclPermissionType.ALLOW) ); AclBinding expectedACLOnPrimaryCluster = new AclBinding( new ResourcePattern(ResourceType.TOPIC, "backup.test-topic-1", PatternType.LITERAL), new AccessControlEntry("User:dummy", "*", AclOperation.DESCRIBE, AclPermissionType.ALLOW) ); // In some rare cases replica topics are created before ACLs are synced, so retry logic is necessary waitForCondition( () -> { assertTrue(getAclBindings(backup.kafka(), "primary.test-topic-1").contains(expectedACLOnBackupCluster), "topic ACLs are not synced on backup cluster"); assertTrue(getAclBindings(primary.kafka(), "backup.test-topic-1").contains(expectedACLOnPrimaryCluster), "topic ACLs are not synced on primary cluster"); return true; }, TOPIC_ACL_SYNC_DURATION_MS, "Topic ACLs were not synced in time" ); // expect to use FakeForwardingAdminWithLocalMetadata to update topic ACLs in FakeLocalMetadataStore.allAcls assertTrue(FakeLocalMetadataStore.aclBindings("dummy").containsAll(List.of(expectedACLOnBackupCluster, expectedACLOnPrimaryCluster))); } void waitForTopicToPersistInFakeLocalMetadataStore(String topicName) throws InterruptedException { waitForCondition(() -> FakeLocalMetadataStore.containsTopic(topicName), FAKE_LOCAL_METADATA_STORE_SYNC_DURATION_MS, "Topic: " + topicName + " didn't get created in the FakeLocalMetadataStore" ); } void waitForTopicConfigPersistInFakeLocalMetaDataStore(String topicName, String configName, String expectedConfigValue) throws InterruptedException { waitForCondition(() -> FakeLocalMetadataStore.topicConfig(topicName).getOrDefault(configName, "").equals(expectedConfigValue), FAKE_LOCAL_METADATA_STORE_SYNC_DURATION_MS, "Topic: " + topicName + "'s configs don't have " + configName + ":" + expectedConfigValue ); } }
MirrorConnectorsWithCustomForwardingAdminIntegrationTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/TargetEmbeddableOnEmbeddedTest.java
{ "start": 879, "end": 1630 }
class ____ { @Test public void testLifecycle(SessionFactoryScope factoryScope) { factoryScope.inTransaction( (session) -> { City cluj = new City(); cluj.setName( "Cluj" ); cluj.setCoordinates( new GPS(46.77120, 23.62360 ) ); session.persist( cluj ); } ); factoryScope.inTransaction( (session) -> { //tag::embeddable-Target-fetching-example[] City city = session.find(City.class, 1L); assert city.getCoordinates() instanceof GPS; //end::embeddable-Target-fetching-example[] assertThat( city.getCoordinates().x() ).isCloseTo( 46.77120, offset( 0.00001 ) ); assertThat( city.getCoordinates().y() ).isCloseTo( 23.62360, offset( 0.00001 ) ); } ); } //tag::embeddable-Target-example[] public
TargetEmbeddableOnEmbeddedTest
java
alibaba__nacos
client/src/main/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegate.java
{ "start": 2407, "end": 9984 }
class ____ implements NamingClientProxy { private final NamingServerListManager serverListManager; private final ServiceInfoUpdateService serviceInfoUpdateService; private final ServiceInfoHolder serviceInfoHolder; private final NamingHttpClientProxy httpClientProxy; private final NamingGrpcClientProxy grpcClientProxy; private final SecurityProxy securityProxy; private ScheduledExecutorService executorService; public NamingClientProxyDelegate(String namespace, ServiceInfoHolder serviceInfoHolder, NacosClientProperties properties, InstancesChangeNotifier changeNotifier, NamingFuzzyWatchServiceListHolder namingFuzzyWatchServiceListHolder) throws NacosException { this.serviceInfoUpdateService = new ServiceInfoUpdateService(properties, serviceInfoHolder, this, changeNotifier); this.serverListManager = new NamingServerListManager(properties, namespace); this.serverListManager.start(); this.serviceInfoHolder = serviceInfoHolder; this.securityProxy = new SecurityProxy(this.serverListManager, NamingHttpClientManager.getInstance().getNacosRestTemplate()); initSecurityProxy(properties); this.httpClientProxy = new NamingHttpClientProxy(namespace, securityProxy, serverListManager, properties); this.grpcClientProxy = new NamingGrpcClientProxy(namespace, securityProxy, serverListManager, properties, serviceInfoHolder, namingFuzzyWatchServiceListHolder); } private void initSecurityProxy(NacosClientProperties properties) { this.executorService = new ScheduledThreadPoolExecutor(1, new NameThreadFactory("com.alibaba.nacos.client.naming.security")); final Properties nacosClientPropertiesView = properties.asProperties(); this.securityProxy.login(nacosClientPropertiesView); this.executorService.scheduleWithFixedDelay(() -> securityProxy.login(nacosClientPropertiesView), 0, SECURITY_INFO_REFRESH_INTERVAL_MILLS, TimeUnit.MILLISECONDS); } @Override public void registerService(String serviceName, String groupName, Instance instance) throws NacosException { getExecuteClientProxy(instance).registerService(serviceName, groupName, instance); } @Override public void batchRegisterService(String serviceName, String groupName, List<Instance> instances) throws NacosException { NAMING_LOGGER.info("batchRegisterInstance instances: {} ,serviceName: {} begin.", instances, serviceName); if (CollectionUtils.isEmpty(instances)) { NAMING_LOGGER.warn("batchRegisterInstance instances is Empty:{}", instances); } grpcClientProxy.batchRegisterService(serviceName, groupName, instances); NAMING_LOGGER.info("batchRegisterInstance instances: {} ,serviceName: {} finish.", instances, serviceName); } @Override public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances) throws NacosException { NAMING_LOGGER.info("batch DeregisterInstance instances: {} ,serviceName: {} begin.", instances, serviceName); if (CollectionUtils.isEmpty(instances)) { NAMING_LOGGER.warn("batch DeregisterInstance instances is Empty:{}", instances); } grpcClientProxy.batchDeregisterService(serviceName, groupName, instances); NAMING_LOGGER.info("batch DeregisterInstance instances: {} ,serviceName: {} finish.", instances, serviceName); } @Override public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException { getExecuteClientProxy(instance).deregisterService(serviceName, groupName, instance); } @Override public void updateInstance(String serviceName, String groupName, Instance instance) throws NacosException { } @Override public ServiceInfo queryInstancesOfService(String serviceName, String groupName, String clusters, boolean healthyOnly) throws NacosException { return grpcClientProxy.queryInstancesOfService(serviceName, groupName, clusters, healthyOnly); } @Override public Service queryService(String serviceName, String groupName) throws NacosException { return null; } @Override public void createService(Service service, AbstractSelector selector) throws NacosException { } @Override public boolean deleteService(String serviceName, String groupName) throws NacosException { return false; } @Override public void updateService(Service service, AbstractSelector selector) throws NacosException { } @Override public ListView<String> getServiceList(int pageNo, int pageSize, String groupName, AbstractSelector selector) throws NacosException { return grpcClientProxy.getServiceList(pageNo, pageSize, groupName, selector); } @Override public ServiceInfo subscribe(String serviceName, String groupName, String clusters) throws NacosException { NAMING_LOGGER.info("[SUBSCRIBE-SERVICE] service:{}, group:{}, clusters:{} ", serviceName, groupName, clusters); String serviceNameWithGroup = NamingUtils.getGroupedName(serviceName, groupName); String serviceKey = ServiceInfo.getKey(serviceNameWithGroup, clusters); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, groupName, clusters); ServiceInfo result = serviceInfoHolder.getServiceInfoMap().get(serviceKey); if (null == result || !isSubscribed(serviceName, groupName, clusters)) { result = grpcClientProxy.subscribe(serviceName, groupName, clusters); } serviceInfoHolder.processServiceInfo(result); return result; } @Override public void unsubscribe(String serviceName, String groupName, String clusters) throws NacosException { NAMING_LOGGER.debug("[UNSUBSCRIBE-SERVICE] service:{}, group:{}, cluster:{} ", serviceName, groupName, clusters); serviceInfoUpdateService.stopUpdateIfContain(serviceName, groupName, clusters); grpcClientProxy.unsubscribe(serviceName, groupName, clusters); } @Override public boolean isSubscribed(String serviceName, String groupName, String clusters) throws NacosException { return grpcClientProxy.isSubscribed(serviceName, groupName, clusters); } @Override public boolean serverHealthy() { return grpcClientProxy.serverHealthy() || httpClientProxy.serverHealthy(); } private NamingClientProxy getExecuteClientProxy(Instance instance) { if (instance.isEphemeral() || grpcClientProxy.isAbilitySupportedByServer( AbilityKey.SERVER_PERSISTENT_INSTANCE_BY_GRPC)) { return grpcClientProxy; } return httpClientProxy; } @Override public void shutdown() throws NacosException { String className = this.getClass().getName(); NAMING_LOGGER.info("{} do shutdown begin", className); serviceInfoUpdateService.shutdown(); serverListManager.shutdown(); httpClientProxy.shutdown(); grpcClientProxy.shutdown(); securityProxy.shutdown(); ThreadUtils.shutdownThreadPool(executorService, NAMING_LOGGER); NAMING_LOGGER.info("{} do shutdown stop", className); } }
NamingClientProxyDelegate
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/internal/AsyncConnectionProvider.java
{ "start": 1382, "end": 5900 }
class ____<K, T extends AsyncCloseable, F extends CompletionStage<T>> { private final Function<K, F> connectionFactory; private final Map<K, Sync<K, T, F>> connections = new ConcurrentHashMap<>(); private volatile boolean closed; /** * Create a new {@link AsyncConnectionProvider}. * * @param connectionFactory must not be {@code null}. */ @SuppressWarnings("unchecked") public AsyncConnectionProvider(Function<? extends K, ? extends F> connectionFactory) { LettuceAssert.notNull(connectionFactory, "AsyncConnectionProvider must not be null"); this.connectionFactory = (Function<K, F>) connectionFactory; } /** * Request a connection for the given the connection {@code key} and return a {@link CompletionStage} that is notified about * the connection outcome. * * @param key the connection {@code key}, must not be {@code null}. * @return */ public F getConnection(K key) { return getSynchronizer(key).getConnection(); } /** * Obtain a connection to a target given the connection {@code key}. * * @param key the connection {@code key}. * @return */ private Sync<K, T, F> getSynchronizer(K key) { if (closed) { throw new IllegalStateException("ConnectionProvider is already closed"); } Sync<K, T, F> sync = connections.get(key); if (sync != null) { return sync; } AtomicBoolean atomicBoolean = new AtomicBoolean(); sync = connections.computeIfAbsent(key, connectionKey -> { Sync<K, T, F> createdSync = new Sync<>(key, connectionFactory.apply(key)); if (closed) { createdSync.cancel(); } return createdSync; }); if (atomicBoolean.compareAndSet(false, true)) { sync.getConnection().whenComplete((c, t) -> { if (t != null) { connections.remove(key); } }); } return sync; } /** * Register a connection identified by {@code key}. Overwrites existing entries. * * @param key the connection {@code key}. * @param connection the connection object. */ public void register(K key, T connection) { connections.put(key, new Sync<>(key, connection)); } /** * @return number of established connections. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public int getConnectionCount() { Sync[] syncs = connections.values().toArray(new Sync[0]); int count = 0; for (Sync sync : syncs) { if (sync.isComplete()) { count++; } } return count; } /** * Close all connections. Pending connections are closed using future chaining. */ @SuppressWarnings("unchecked") public CompletableFuture<Void> close() { this.closed = true; List<CompletableFuture<Void>> futures = new ArrayList<>(); forEach((connectionKey, closeable) -> { futures.add(closeable.closeAsync()); connections.remove(connectionKey); }); return Futures.allOf(futures); } /** * Close a connection by its connection {@code key}. Pending connections are closed using future chaining. * * @param key the connection {@code key}, must not be {@code null}. */ public void close(K key) { LettuceAssert.notNull(key, "ConnectionKey must not be null!"); Sync<K, T, F> sync = connections.get(key); if (sync != null) { connections.remove(key); sync.doWithConnection(AsyncCloseable::closeAsync); } } /** * Execute an action for all established and pending connections. * * @param action the action. */ public void forEach(Consumer<? super T> action) { LettuceAssert.notNull(action, "Action must not be null!"); connections.values().forEach(sync -> { if (sync != null) { sync.doWithConnection(action); } }); } /** * Execute an action for all established and pending {@link AsyncCloseable}s. * * @param action the action. */ public void forEach(BiConsumer<? super K, ? super T> action) { connections.forEach((key, sync) -> sync.doWithConnection(action)); } static
AsyncConnectionProvider
java
apache__flink
flink-core-api/src/main/java/org/apache/flink/api/java/tuple/builder/Tuple7Builder.java
{ "start": 1267, "end": 1560 }
class ____ {@link Tuple7}. * * @param <T0> The type of field 0 * @param <T1> The type of field 1 * @param <T2> The type of field 2 * @param <T3> The type of field 3 * @param <T4> The type of field 4 * @param <T5> The type of field 5 * @param <T6> The type of field 6 */ @Public public
for
java
apache__hadoop
hadoop-tools/hadoop-resourceestimator/src/main/java/org/apache/hadoop/resourceestimator/skylinestore/validator/SkylineStoreValidator.java
{ "start": 1846, "end": 4720 }
class ____ { private static final Logger LOGGER = LoggerFactory.getLogger(SkylineStoreValidator.class); /** * Check if recurrenceId is <em>null</em>. * * @param recurrenceId the id of the recurring pipeline job. * @throws SkylineStoreException if input parameters are invalid. */ public final void validate(final RecurrenceId recurrenceId) throws SkylineStoreException { if (recurrenceId == null) { StringBuilder sb = new StringBuilder(); sb.append("Recurrence id is null, please try again by specifying" + " a valid Recurrence id."); LOGGER.error(sb.toString()); throw new NullRecurrenceIdException(sb.toString()); } } /** * Check if pipelineId is <em>null</em>. * * @param pipelineId the id of the recurring pipeline job. * @throws SkylineStoreException if input parameters are invalid. */ public final void validate(final String pipelineId) throws SkylineStoreException { if (pipelineId == null) { StringBuilder sb = new StringBuilder(); sb.append("pipelineId is null, please try again by specifying" + " a valid pipelineId."); LOGGER.error(sb.toString()); throw new NullPipelineIdException(sb.toString()); } } /** * Check if recurrenceId is <em>null</em> or resourceSkylines is * <em>null</em>. * * @param recurrenceId the id of the recurring pipeline job. * @param resourceSkylines the list of {@link ResourceSkyline}s to be added. * @throws SkylineStoreException if input parameters are invalid. */ public final void validate(final RecurrenceId recurrenceId, final List<ResourceSkyline> resourceSkylines) throws SkylineStoreException { validate(recurrenceId); if (resourceSkylines == null) { StringBuilder sb = new StringBuilder(); sb.append("ResourceSkylines for " + recurrenceId + " is null, please try again by " + "specifying valid ResourceSkylines."); LOGGER.error(sb.toString()); throw new NullResourceSkylineException(sb.toString()); } } /** * Check if pipelineId is <em>null</em> or resourceOverTime is <em>null</em>. * * @param pipelineId the id of the recurring pipeline. * @param resourceOverTime predicted {@code Resource} allocation to be added. * @throws SkylineStoreException if input parameters are invalid. */ public final void validate(final String pipelineId, final RLESparseResourceAllocation resourceOverTime) throws SkylineStoreException { validate(pipelineId); if (resourceOverTime == null) { StringBuilder sb = new StringBuilder(); sb.append("Resource allocation for " + pipelineId + " is null."); LOGGER.error(sb.toString()); throw new NullRLESparseResourceAllocationException(sb.toString()); } } }
SkylineStoreValidator
java
google__dagger
javatests/dagger/functional/subcomponent/module/UsesModuleSubcomponents.java
{ "start": 1914, "end": 2028 }
class ____ {} @Component(modules = OnlyIncludesModuleWithSubcomponents.class)
OnlyIncludesModuleWithSubcomponents
java
apache__flink
flink-datastream/src/test/java/org/apache/flink/datastream/impl/attribute/StreamingJobGraphGeneratorWithAttributeTest.java
{ "start": 2353, "end": 10592 }
class ____ { @Test void testNoOutputUntilEndOfInputWithOperatorChainCase1() throws Exception { ExecutionEnvironmentImpl env = (ExecutionEnvironmentImpl) ExecutionEnvironment.getInstance(); NonKeyedPartitionStream<Integer> source = env.fromSource( DataStreamV2SourceUtils.fromData(Arrays.asList(1, 2, 3)), "test-source"); source.keyBy(x -> x) .process(new NoOutputUntilEndOfInputMapTask()) .withParallelism(2) .process(new TestMapTask()) .withParallelism(2) .toSink(new WrappedSink<>(new DiscardingSink<>())) .withParallelism(3); StreamGraph streamGraph = env.getStreamGraph(); Map<String, StreamNode> nodeMap = new HashMap<>(); for (StreamNode node : streamGraph.getStreamNodes()) { nodeMap.put(node.getOperatorName(), node); } assertThat(nodeMap).hasSize(4); JobGraph jobGraph = StreamingJobGraphGenerator.createJobGraph(streamGraph); Map<String, JobVertex> vertexMap = new HashMap<>(); for (JobVertex vertex : jobGraph.getVertices()) { vertexMap.put(vertex.getName(), vertex); } assertThat(vertexMap).hasSize(3); assertHasOutputPartitionType( vertexMap.get("Source: Collection Source"), ResultPartitionType.PIPELINED_BOUNDED); assertHasOutputPartitionType( vertexMap.get("KeyedProcess -> Process"), ResultPartitionType.BLOCKING); assertThat(vertexMap.get("Source: Collection Source").isAnyOutputBlocking()).isFalse(); assertThat(vertexMap.get("KeyedProcess -> Process").isAnyOutputBlocking()).isTrue(); assertThat(vertexMap.get("Sink: Writer").isAnyOutputBlocking()).isFalse(); } @Test void testPropagateAlongOperatorChain() throws Exception { ExecutionEnvironmentImpl env = (ExecutionEnvironmentImpl) ExecutionEnvironment.getInstance(); NonKeyedPartitionStream<Integer> source = env.fromSource( DataStreamV2SourceUtils.fromData(Arrays.asList(1, 2, 3)), "test-source"); source.keyBy(x -> x) .process(new TestMapTask()) .withParallelism(2) .process(new NoOutputUntilEndOfInputMapTask()) .withParallelism(2) .toSink(new WrappedSink<>(new DiscardingSink<>())) .withParallelism(3); StreamGraph streamGraph = env.getStreamGraph(); Map<String, StreamNode> nodeMap = new HashMap<>(); for (StreamNode node : streamGraph.getStreamNodes()) { nodeMap.put(node.getOperatorName(), node); } assertThat(nodeMap).hasSize(4); JobGraph jobGraph = StreamingJobGraphGenerator.createJobGraph(streamGraph); Map<String, JobVertex> vertexMap = new HashMap<>(); for (JobVertex vertex : jobGraph.getVertices()) { vertexMap.put(vertex.getName(), vertex); } assertThat(vertexMap).hasSize(3); assertHasOutputPartitionType( vertexMap.get("Source: Collection Source"), ResultPartitionType.PIPELINED_BOUNDED); assertHasOutputPartitionType( vertexMap.get("KeyedProcess -> Process"), ResultPartitionType.BLOCKING); assertThat(vertexMap.get("Source: Collection Source").isAnyOutputBlocking()).isFalse(); assertThat(vertexMap.get("KeyedProcess -> Process").isAnyOutputBlocking()).isTrue(); assertThat(vertexMap.get("Sink: Writer").isAnyOutputBlocking()).isFalse(); } @Test void testTwoOutput() throws Exception { ExecutionEnvironmentImpl env = (ExecutionEnvironmentImpl) ExecutionEnvironment.getInstance(); NonKeyedPartitionStream<Integer> source = env.fromSource( DataStreamV2SourceUtils.fromData(Arrays.asList(1, 2, 3)), "test-source"); NonKeyedPartitionStream.ProcessConfigurableAndTwoNonKeyedPartitionStream<Integer, Integer> twoOutputStream = source.process(new TestMapTask()) .withParallelism(2) .process(new TestTwoOutputProcessFunction()) .withParallelism(2); NonKeyedPartitionStream.ProcessConfigurableAndNonKeyedPartitionStream<Integer> firstStream = twoOutputStream.getFirst(); NonKeyedPartitionStream.ProcessConfigurableAndNonKeyedPartitionStream<Integer> secondStream = twoOutputStream.getSecond(); firstStream .process(new NoOutputUntilEndOfInputMapTask()) .withParallelism(2) .toSink(new WrappedSink<>(new DiscardingSink<>())) .withParallelism(3); secondStream .process(new TestMapTask()) .withParallelism(2) .toSink(new WrappedSink<>(new DiscardingSink<>())) .withParallelism(3); StreamGraph streamGraph = env.getStreamGraph(); JobGraph jobGraph = StreamingJobGraphGenerator.createJobGraph(streamGraph); Map<String, JobVertex> vertexMap = new HashMap<>(); for (JobVertex vertex : jobGraph.getVertices()) { vertexMap.put(vertex.getName(), vertex); } assertThat(vertexMap).hasSize(3); assertHasOutputPartitionType( vertexMap.get("Process -> Two-Output-Operator -> (Process, Process)"), ResultPartitionType.BLOCKING); assertThat( vertexMap .get("Process -> Two-Output-Operator -> (Process, Process)") .isAnyOutputBlocking()) .isTrue(); } @Test void testWithoutOperatorChain() throws Exception { ExecutionEnvironmentImpl env = (ExecutionEnvironmentImpl) ExecutionEnvironment.getInstance(); env.getConfiguration().set(PipelineOptions.OPERATOR_CHAINING, false); NonKeyedPartitionStream<Integer> source = env.fromSource( DataStreamV2SourceUtils.fromData(Arrays.asList(1, 2, 3)), "test-source"); source.keyBy(x -> x) .process(new NoOutputUntilEndOfInputMapTask()) .withParallelism(2) .process(new TestMapTask()) .withParallelism(2) .toSink(new WrappedSink<>(new DiscardingSink<>())) .withParallelism(3); StreamGraph streamGraph = env.getStreamGraph(); Map<String, StreamNode> nodeMap = new HashMap<>(); for (StreamNode node : streamGraph.getStreamNodes()) { nodeMap.put(node.getOperatorName(), node); } assertThat(nodeMap).hasSize(4); JobGraph jobGraph = StreamingJobGraphGenerator.createJobGraph(streamGraph); Map<String, JobVertex> vertexMap = new HashMap<>(); for (JobVertex vertex : jobGraph.getVertices()) { vertexMap.put(vertex.getName(), vertex); } assertThat(vertexMap).hasSize(4); assertHasOutputPartitionType( vertexMap.get("Source: Collection Source"), ResultPartitionType.PIPELINED_BOUNDED); assertHasOutputPartitionType(vertexMap.get("KeyedProcess"), ResultPartitionType.BLOCKING); assertHasOutputPartitionType( vertexMap.get("Process"), ResultPartitionType.PIPELINED_BOUNDED); assertThat(vertexMap.get("Source: Collection Source").isAnyOutputBlocking()).isFalse(); assertThat(vertexMap.get("KeyedProcess").isAnyOutputBlocking()).isTrue(); assertThat(vertexMap.get("Process").isAnyOutputBlocking()).isFalse(); assertThat(vertexMap.get("Sink: Writer").isAnyOutputBlocking()).isFalse(); } private void assertHasOutputPartitionType( JobVertex jobVertex, ResultPartitionType partitionType) { assertThat(jobVertex.getProducedDataSets().get(0).getResultType()).isEqualTo(partitionType); } @NoOutputUntilEndOfInput private static
StreamingJobGraphGeneratorWithAttributeTest
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/aggfunctions/MaxAggFunction.java
{ "start": 5987, "end": 6226 }
class ____ extends MaxAggFunction { @Override public DataType getResultType() { return DataTypes.BOOLEAN(); } } /** Built-in String Max aggregate function. */ public static
BooleanMaxAggFunction
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/action/search/TransportSearchIT.java
{ "start": 4259, "end": 27521 }
class ____ extends Plugin implements SearchPlugin { @Override public List<AggregationSpec> getAggregations() { return Collections.singletonList( new AggregationSpec(TestAggregationBuilder.NAME, TestAggregationBuilder::new, TestAggregationBuilder.PARSER) .addResultReader(Max::new) ); } @Override public List<FetchSubPhase> getFetchSubPhases(FetchPhaseConstructionContext context) { /** * Set up a fetch sub phase that throws an exception on indices whose name that start with "boom". */ return Collections.singletonList(fetchContext -> new FetchSubPhaseProcessor() { @Override public void setNextReader(LeafReaderContext readerContext) {} @Override public StoredFieldsSpec storedFieldsSpec() { return StoredFieldsSpec.NO_REQUIREMENTS; } @Override public void process(FetchSubPhase.HitContext hitContext) { if (fetchContext.getIndexName().startsWith("boom")) { throw new RuntimeException("boom"); } } }); } } @Override protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) { return Settings.builder().put(super.nodeSettings(nodeOrdinal, otherSettings)).put("indices.breaker.request.type", "memory").build(); } @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singletonList(TestPlugin.class); } public void testLocalClusterAlias() throws ExecutionException, InterruptedException { long nowInMillis = randomLongBetween(0, Long.MAX_VALUE); IndexRequest indexRequest = new IndexRequest("test"); indexRequest.id("1"); indexRequest.source("field", "value"); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); DocWriteResponse indexResponse = client().index(indexRequest).actionGet(); assertEquals(RestStatus.CREATED, indexResponse.status()); TaskId parentTaskId = new TaskId("node", randomNonNegativeLong()); { SearchRequest searchRequest = SearchRequest.subSearchRequest( parentTaskId, new SearchRequest(), Strings.EMPTY_ARRAY, SearchRequest.DEFAULT_INDICES_OPTIONS, "local", nowInMillis, randomBoolean() ); assertResponse(client().search(searchRequest), searchResponse -> { assertEquals(1, searchResponse.getHits().getTotalHits().value()); SearchHit[] hits = searchResponse.getHits().getHits(); assertEquals(1, hits.length); SearchHit hit = hits[0]; assertEquals("local", hit.getClusterAlias()); assertEquals("test", hit.getIndex()); assertEquals("1", hit.getId()); }); } { SearchRequest searchRequest = SearchRequest.subSearchRequest( parentTaskId, new SearchRequest(), Strings.EMPTY_ARRAY, SearchRequest.DEFAULT_INDICES_OPTIONS, "", nowInMillis, randomBoolean() ); assertResponse(client().search(searchRequest), searchResponse -> { assertEquals(1, searchResponse.getHits().getTotalHits().value()); SearchHit[] hits = searchResponse.getHits().getHits(); assertEquals(1, hits.length); SearchHit hit = hits[0]; assertEquals("", hit.getClusterAlias()); assertEquals("test", hit.getIndex()); assertEquals("1", hit.getId()); }); } } public void testAbsoluteStartMillis() throws ExecutionException, InterruptedException { TaskId parentTaskId = new TaskId("node", randomNonNegativeLong()); { IndexRequest indexRequest = new IndexRequest("test-1970.01.01"); indexRequest.id("1"); indexRequest.source("date", "1970-01-01"); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); DocWriteResponse indexResponse = client().index(indexRequest).actionGet(); assertEquals(RestStatus.CREATED, indexResponse.status()); } { IndexRequest indexRequest = new IndexRequest("test-1982.01.01"); indexRequest.id("1"); indexRequest.source("date", "1982-01-01"); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); DocWriteResponse indexResponse = client().index(indexRequest).actionGet(); assertEquals(RestStatus.CREATED, indexResponse.status()); } { assertHitCount(client().search(new SearchRequest()), 2); } { SearchRequest searchRequest = new SearchRequest("<test-{now/d}>"); searchRequest.indicesOptions(IndicesOptions.fromOptions(true, true, true, true)); assertResponse(client().search(searchRequest), searchResponse -> assertEquals(0, searchResponse.getTotalShards())); } { SearchRequest searchRequest = SearchRequest.subSearchRequest( parentTaskId, new SearchRequest(), Strings.EMPTY_ARRAY, SearchRequest.DEFAULT_INDICES_OPTIONS, "", 0, randomBoolean() ); assertHitCount(client().search(searchRequest), 2); } { SearchRequest searchRequest = SearchRequest.subSearchRequest( parentTaskId, new SearchRequest(), Strings.EMPTY_ARRAY, SearchRequest.DEFAULT_INDICES_OPTIONS, "", 0, randomBoolean() ); searchRequest.indices("<test-{now/d}>"); assertResponse(client().search(searchRequest), searchResponse -> { assertEquals(1, searchResponse.getHits().getTotalHits().value()); assertEquals("test-1970.01.01", searchResponse.getHits().getHits()[0].getIndex()); }); } { SearchRequest searchRequest = SearchRequest.subSearchRequest( parentTaskId, new SearchRequest(), Strings.EMPTY_ARRAY, SearchRequest.DEFAULT_INDICES_OPTIONS, "", 0, randomBoolean() ); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); RangeQueryBuilder rangeQuery = new RangeQueryBuilder("date"); rangeQuery.gte("1970-01-01"); rangeQuery.lt("1982-01-01"); sourceBuilder.query(rangeQuery); searchRequest.source(sourceBuilder); assertResponse(client().search(searchRequest), searchResponse -> { assertEquals(1, searchResponse.getHits().getTotalHits().value()); assertEquals("test-1970.01.01", searchResponse.getHits().getHits()[0].getIndex()); }); } } public void testFinalReduce() throws ExecutionException, InterruptedException { long nowInMillis = randomLongBetween(0, Long.MAX_VALUE); TaskId taskId = new TaskId("node", randomNonNegativeLong()); { IndexRequest indexRequest = new IndexRequest("test"); indexRequest.id("1"); indexRequest.source("price", 10); DocWriteResponse indexResponse = client().index(indexRequest).actionGet(); assertEquals(RestStatus.CREATED, indexResponse.status()); } { IndexRequest indexRequest = new IndexRequest("test"); indexRequest.id("2"); indexRequest.source("price", 100); DocWriteResponse indexResponse = client().index(indexRequest).actionGet(); assertEquals(RestStatus.CREATED, indexResponse.status()); } indicesAdmin().prepareRefresh("test").get(); SearchRequest originalRequest = new SearchRequest(); SearchSourceBuilder source = new SearchSourceBuilder(); source.size(0); originalRequest.source(source); TermsAggregationBuilder terms = new TermsAggregationBuilder("terms").userValueTypeHint(ValueType.NUMERIC); terms.field("price"); terms.size(1); source.aggregation(terms); { SearchRequest searchRequest = randomBoolean() ? originalRequest : SearchRequest.subSearchRequest( taskId, originalRequest, Strings.EMPTY_ARRAY, originalRequest.indicesOptions(), "remote", nowInMillis, true ); assertResponse(client().search(searchRequest), searchResponse -> { assertEquals(2, searchResponse.getHits().getTotalHits().value()); InternalAggregations aggregations = searchResponse.getAggregations(); LongTerms longTerms = aggregations.get("terms"); assertEquals(1, longTerms.getBuckets().size()); }); } { SearchRequest searchRequest = SearchRequest.subSearchRequest( taskId, originalRequest, Strings.EMPTY_ARRAY, originalRequest.indicesOptions(), "remote", nowInMillis, false ); assertResponse(client().search(searchRequest), searchResponse -> { assertEquals(2, searchResponse.getHits().getTotalHits().value()); InternalAggregations aggregations = searchResponse.getAggregations(); LongTerms longTerms = aggregations.get("terms"); assertEquals(2, longTerms.getBuckets().size()); }); } } public void testWaitForRefreshIndexValidation() throws Exception { int numberOfShards = randomIntBetween(3, 10); assertAcked( prepareCreate("test1").setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, numberOfShards)), prepareCreate("test2").setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, numberOfShards)), prepareCreate("test3").setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, numberOfShards)) ); assertAcked( indicesAdmin().prepareAliases(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT).addAlias("test1", "testAlias"), indicesAdmin().prepareAliases(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .addAlias(new String[] { "test2", "test3" }, "testFailedAlias") ); long[] validCheckpoints = new long[numberOfShards]; Arrays.fill(validCheckpoints, SequenceNumbers.UNASSIGNED_SEQ_NO); // no exception prepareSearch("testAlias").setWaitForCheckpoints(Collections.singletonMap("testAlias", validCheckpoints)).get().decRef(); IllegalArgumentException e = expectThrows( IllegalArgumentException.class, prepareSearch("testFailedAlias").setWaitForCheckpoints(Collections.singletonMap("testFailedAlias", validCheckpoints)) ); assertThat( e.getMessage(), containsString( "Failed to resolve wait_for_checkpoints target [testFailedAlias]. Configured target " + "must resolve to a single open index." ) ); IllegalArgumentException e2 = expectThrows( IllegalArgumentException.class, prepareSearch("test1").setWaitForCheckpoints(Collections.singletonMap("test1", new long[2])) ); assertThat( e2.getMessage(), containsString( "Target configured with wait_for_checkpoints must search the same number of shards as " + "checkpoints provided. [2] checkpoints provided. Target [test1] which resolved to index [test1] has [" + numberOfShards + "] shards." ) ); IllegalArgumentException e3 = expectThrows( IllegalArgumentException.class, prepareSearch("testAlias").setWaitForCheckpoints(Collections.singletonMap("testAlias", new long[2])) ); assertThat( e3.getMessage(), containsString( "Target configured with wait_for_checkpoints must search the same number of shards as " + "checkpoints provided. [2] checkpoints provided. Target [testAlias] which resolved to index [test1] has [" + numberOfShards + "] shards." ) ); IllegalArgumentException e4 = expectThrows( IllegalArgumentException.class, prepareSearch("testAlias").setWaitForCheckpoints(Collections.singletonMap("test2", validCheckpoints)) ); assertThat( e4.getMessage(), containsString( "Target configured with wait_for_checkpoints must be a concrete index resolved in " + "this search. Target [test2] is not a concrete index resolved in this search." ) ); } public void testShardCountLimit() throws Exception { try { final int numPrimaries1 = randomIntBetween(2, 10); final int numPrimaries2 = randomIntBetween(1, 10); assertAcked( prepareCreate("test1").setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, numPrimaries1)), prepareCreate("test2").setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, numPrimaries2)) ); // no exception prepareSearch("test1").get().decRef(); updateClusterSettings(Settings.builder().put(TransportSearchAction.SHARD_COUNT_LIMIT_SETTING.getKey(), numPrimaries1 - 1)); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, prepareSearch("test1")); assertThat( e.getMessage(), containsString("Trying to query " + numPrimaries1 + " shards, which is over the limit of " + (numPrimaries1 - 1)) ); updateClusterSettings(Settings.builder().put(TransportSearchAction.SHARD_COUNT_LIMIT_SETTING.getKey(), numPrimaries1)); // no exception prepareSearch("test1").get().decRef(); e = expectThrows(IllegalArgumentException.class, prepareSearch("test1", "test2")); assertThat( e.getMessage(), containsString( "Trying to query " + (numPrimaries1 + numPrimaries2) + " shards, which is over the limit of " + numPrimaries1 ) ); } finally { updateClusterSettings(Settings.builder().putNull(TransportSearchAction.SHARD_COUNT_LIMIT_SETTING.getKey())); } } public void testSearchIdle() throws Exception { int numOfReplicas = randomIntBetween(0, 1); internalCluster().ensureAtLeastNumDataNodes(numOfReplicas + 1); final Settings.Builder settings = indexSettings(randomIntBetween(1, 5), numOfReplicas).put( IndexSettings.INDEX_SEARCH_IDLE_AFTER.getKey(), TimeValue.timeValueMillis(randomIntBetween(50, 500)) ); assertAcked(prepareCreate("test").setSettings(settings).setMapping(""" {"properties":{"created_date":{"type": "date", "format": "yyyy-MM-dd"}}}""")); ensureGreen("test"); assertBusy(() -> { for (String node : internalCluster().nodesInclude("test")) { final IndicesService indicesService = internalCluster().getInstance(IndicesService.class, node); for (IndexShard indexShard : indicesService.indexServiceSafe(resolveIndex("test"))) { assertTrue(indexShard.isSearchIdle()); } } }); prepareIndex("test").setId("1").setSource("created_date", "2020-01-01").get(); prepareIndex("test").setId("2").setSource("created_date", "2020-01-02").get(); prepareIndex("test").setId("3").setSource("created_date", "2020-01-03").get(); assertBusy( () -> assertResponse( prepareSearch("test").setQuery(new RangeQueryBuilder("created_date").gte("2020-01-02").lte("2020-01-03")) .setPreFilterShardSize(randomIntBetween(1, 3)), resp -> assertThat(resp.getHits().getTotalHits().value(), equalTo(2L)) ) ); } public void testCircuitBreakerReduceFail() throws Exception { updateClusterSettings(Settings.builder().put(SearchService.BATCHED_QUERY_PHASE.getKey(), false)); int numShards = randomIntBetween(1, 10); indexSomeDocs("test", numShards, numShards * 3); { final AtomicArray<Boolean> responses = new AtomicArray<>(10); final CountDownLatch latch = new CountDownLatch(10); for (int i = 0; i < 10; i++) { int batchReduceSize = randomIntBetween(2, Math.max(numShards + 1, 3)); SearchRequest request = prepareSearch("test").addAggregation(new TestAggregationBuilder("test")) .setBatchedReduceSize(batchReduceSize) .request(); final int index = i; client().search(request, new ActionListener<>() { @Override public void onResponse(SearchResponse response) { responses.set(index, true); latch.countDown(); } @Override public void onFailure(Exception e) { responses.set(index, false); latch.countDown(); } }); } latch.await(); assertThat(responses.asList().size(), equalTo(10)); for (boolean resp : responses.asList()) { assertTrue(resp); } assertBusy(() -> assertThat(requestBreakerUsed(), equalTo(0L))); } try { updateClusterSettings(Settings.builder().put("indices.breaker.request.limit", "1b")); final Client client = client(); assertBusy(() -> { Exception exc = expectThrows( Exception.class, client.prepareSearch("test").addAggregation(new TestAggregationBuilder("test")) ); assertThat(exc.getCause().getMessage(), containsString("<reduce_aggs>")); }); final AtomicArray<Exception> exceptions = new AtomicArray<>(10); final CountDownLatch latch = new CountDownLatch(10); for (int i = 0; i < 10; i++) { int batchReduceSize = randomIntBetween(2, Math.max(numShards + 1, 3)); SearchRequest request = prepareSearch("test").addAggregation(new TestAggregationBuilder("test")) .setBatchedReduceSize(batchReduceSize) .request(); final int index = i; client().search(request, new ActionListener<>() { @Override public void onResponse(SearchResponse response) { latch.countDown(); } @Override public void onFailure(Exception exc) { exceptions.set(index, exc); latch.countDown(); } }); } latch.await(); assertThat(exceptions.asList().size(), equalTo(10)); for (Exception exc : exceptions.asList()) { assertThat(exc.getCause().getMessage(), containsString("<reduce_aggs>")); } assertBusy(() -> assertThat(requestBreakerUsed(), equalTo(0L))); } finally { updateClusterSettings( Settings.builder().putNull("indices.breaker.request.limit").putNull(SearchService.BATCHED_QUERY_PHASE.getKey()) ); } } public void testCircuitBreakerFetchFail() throws Exception { int numShards = randomIntBetween(1, 10); int numDocs = numShards * 10; indexSomeDocs("boom", numShards, numDocs); final AtomicArray<Exception> exceptions = new AtomicArray<>(10); final CountDownLatch latch = new CountDownLatch(10); for (int i = 0; i < 10; i++) { int batchReduceSize = randomIntBetween(2, Math.max(numShards + 1, 3)); SearchRequest request = prepareSearch("boom").setBatchedReduceSize(batchReduceSize) .setAllowPartialSearchResults(false) .request(); final int index = i; client().search(request, new ActionListener<>() { @Override public void onResponse(SearchResponse response) { latch.countDown(); } @Override public void onFailure(Exception exc) { exceptions.set(index, exc); latch.countDown(); } }); } latch.await(); assertThat(exceptions.asList().size(), equalTo(10)); for (Exception exc : exceptions.asList()) { assertThat(exc.getCause().getMessage(), containsString("boom")); } assertBusy(() -> assertThat(requestBreakerUsed(), equalTo(0L))); } private void indexSomeDocs(String indexName, int numberOfShards, int numberOfDocs) { createIndex(indexName, Settings.builder().put("index.number_of_shards", numberOfShards).build()); for (int i = 0; i < numberOfDocs; i++) { DocWriteResponse indexResponse = prepareIndex(indexName).setSource("number", randomInt()).get(); assertEquals(RestStatus.CREATED, indexResponse.status()); } indicesAdmin().prepareRefresh(indexName).get(); } private long requestBreakerUsed() { NodesStatsResponse stats = clusterAdmin().prepareNodesStats().setBreaker(true).get(); long estimated = 0; for (NodeStats nodeStats : stats.getNodes()) { estimated += nodeStats.getBreaker().getStats(CircuitBreaker.REQUEST).getEstimated(); } return estimated; } /** * A test aggregation that doesn't consume circuit breaker memory when running on shards. * It is used to test the behavior of the circuit breaker when reducing multiple aggregations * together (coordinator node). */ private static
TestPlugin
java
apache__rocketmq
common/src/main/java/org/apache/rocketmq/common/thread/ThreadPoolStatusMonitor.java
{ "start": 903, "end": 1085 }
interface ____ { String describe(); double value(ThreadPoolExecutor executor); boolean needPrintJstack(ThreadPoolExecutor executor, double value); }
ThreadPoolStatusMonitor
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest_maxActive3.java
{ "start": 210, "end": 930 }
class ____ extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:xxx"); dataSource.setTestOnBorrow(false); dataSource.setFilters("stat"); dataSource.setMinIdle(100); dataSource.setMaxActive(10); } protected void tearDown() throws Exception { dataSource.close(); } public void test_error() throws Exception { Exception error = null; try { dataSource.init(); } catch (IllegalArgumentException e) { error = e; } assertNotNull(error); } }
DruidDataSourceTest_maxActive3
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/AbstractStreamTaskNetworkInput.java
{ "start": 2704, "end": 2929 }
class ____ network-based StreamTaskInput where each channel has a designated {@link * RecordDeserializer} for spanning records. Specific implementation bind it to a specific {@link * RecordDeserializer}. */ public abstract
for
java
quarkusio__quarkus
integration-tests/spring-data-jpa/src/main/java/io/quarkus/it/spring/data/jpa/Song.java
{ "start": 326, "end": 1343 }
class ____ { @Id @SequenceGenerator(name = "songSeqGen", sequenceName = "songSeq", initialValue = 100, allocationSize = 1) @GeneratedValue(generator = "songSeqGen") private Long id; private String title; private String author; @JsonIgnore @ManyToMany(mappedBy = "likedSongs") private Set<Person> likes; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Set<Person> getLikes() { return likes; } public void setLikes(Set<Person> likes) { this.likes = likes; } public void removePerson(Person person) { this.likes.remove(person); person.getLikedSongs().remove(this); } }
Song
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/blockloader/docvalues/fn/MvMaxBytesRefsFromOrdsBlockLoader.java
{ "start": 945, "end": 1604 }
class ____ extends AbstractBytesRefsFromOrdsBlockLoader { private final String fieldName; public MvMaxBytesRefsFromOrdsBlockLoader(String fieldName) { super(fieldName); this.fieldName = fieldName; } @Override protected AllReader singletonReader(SortedDocValues docValues) { return new Singleton(docValues); } @Override protected AllReader sortedSetReader(SortedSetDocValues docValues) { return new MvMaxSortedSet(docValues); } @Override public String toString() { return "MvMaxBytesRefsFromOrds[" + fieldName + "]"; } private static
MvMaxBytesRefsFromOrdsBlockLoader
java
apache__dubbo
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java
{ "start": 7151, "end": 7256 }
interface ____ { void callback(int deep, boolean isLast, String prefix, Node node); } }
Callback
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxElapsed.java
{ "start": 1023, "end": 1628 }
class ____<T> extends InternalFluxOperator<T, Tuple2<Long, T>> implements Fuseable { final Scheduler scheduler; FluxElapsed(Flux<T> source, Scheduler scheduler) { super(source); this.scheduler = scheduler; } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super Tuple2<Long, T>> actual) { return new ElapsedSubscriber<>(actual, scheduler); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_ON) return scheduler; if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } static final
FluxElapsed
java
elastic__elasticsearch
modules/repository-azure/src/internalClusterTest/java/org/elasticsearch/repositories/azure/AzureBlobStoreRepositoryTests.java
{ "start": 10644, "end": 11873 }
class ____ extends ErroneousHttpHandler { AzureErroneousHttpHandler(final HttpHandler delegate, final int maxErrorsPerRequest) { super(delegate, maxErrorsPerRequest); } @Override protected void handleAsError(final HttpExchange exchange) throws IOException { try { drainInputStream(exchange.getRequestBody()); AzureHttpHandler.sendError(exchange, randomFrom(RestStatus.INTERNAL_SERVER_ERROR, RestStatus.SERVICE_UNAVAILABLE)); } finally { exchange.close(); } } @Override protected String requestUniqueId(final HttpExchange exchange) { final String requestId = exchange.getRequestHeaders().getFirst("X-ms-client-request-id"); final String range = exchange.getRequestHeaders().getFirst("Content-Range"); return exchange.getRequestMethod() + " " + requestId + (range != null ? " " + range : ""); } } /** * HTTP handler that keeps track of requests performed against Azure Storage. */ @SuppressForbidden(reason = "this test uses a HttpServer to emulate an Azure endpoint") private static
AzureErroneousHttpHandler
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableRetryBiPredicate.java
{ "start": 961, "end": 1620 }
class ____<T> extends AbstractFlowableWithUpstream<T, T> { final BiPredicate<? super Integer, ? super Throwable> predicate; public FlowableRetryBiPredicate( Flowable<T> source, BiPredicate<? super Integer, ? super Throwable> predicate) { super(source); this.predicate = predicate; } @Override public void subscribeActual(Subscriber<? super T> s) { SubscriptionArbiter sa = new SubscriptionArbiter(false); s.onSubscribe(sa); RetryBiSubscriber<T> rs = new RetryBiSubscriber<>(s, predicate, sa, source); rs.subscribeNext(); } static final
FlowableRetryBiPredicate
java
apache__hadoop
hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/StringSignerSecretProvider.java
{ "start": 1092, "end": 1741 }
class ____ extends SignerSecretProvider { private byte[] secret; private byte[][] secrets; public StringSignerSecretProvider() {} @Override public void init(Properties config, ServletContext servletContext, long tokenValidity) throws Exception { String signatureSecret = config.getProperty( AuthenticationFilter.SIGNATURE_SECRET, null); secret = signatureSecret.getBytes(StandardCharsets.UTF_8); secrets = new byte[][]{secret}; } @Override public byte[] getCurrentSecret() { return secret; } @Override public byte[][] getAllSecrets() { return secrets; } }
StringSignerSecretProvider
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/AbstractJupiterTestEngineTests.java
{ "start": 1718, "end": 1812 }
class ____ tests involving the {@link JupiterTestEngine}. * * @since 5.0 */ public abstract
for
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/env/SimpleCommandLineArgsParser.java
{ "start": 2599, "end": 3898 }
class ____ { /** * Parse the given {@code String} array based on the rules described {@linkplain * SimpleCommandLineArgsParser above}, returning a fully-populated * {@link CommandLineArgs} object. * @param args command line arguments, typically from a {@code main()} method */ public CommandLineArgs parse(String... args) { CommandLineArgs commandLineArgs = new CommandLineArgs(); boolean endOfOptions = false; for (String arg : args) { if (!endOfOptions && arg.startsWith("--")) { String optionText = arg.substring(2); int indexOfEqualsSign = optionText.indexOf('='); if (indexOfEqualsSign > -1) { String optionName = optionText.substring(0, indexOfEqualsSign); String optionValue = optionText.substring(indexOfEqualsSign + 1); if (optionName.isEmpty()) { throw new IllegalArgumentException("Invalid argument syntax: " + arg); } commandLineArgs.addOptionArg(optionName, optionValue); } else if (!optionText.isEmpty()){ commandLineArgs.addOptionArg(optionText, null); } else { // '--' End of options delimiter, all remaining args are non-option arguments endOfOptions = true; } } else { commandLineArgs.addNonOptionArg(arg); } } return commandLineArgs; } }
SimpleCommandLineArgsParser
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/impl/EventLoopExecutor.java
{ "start": 652, "end": 1056 }
class ____ implements EventExecutor { final EventLoop eventLoop; public EventLoopExecutor(EventLoop eventLoop) { this.eventLoop = eventLoop; } public EventLoop eventLoop() { return eventLoop; } @Override public boolean inThread() { return eventLoop.inEventLoop(); } @Override public void execute(Runnable command) { eventLoop.execute(command); } }
EventLoopExecutor
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/TimeInStaticInitializerTest.java
{ "start": 1815, "end": 1982 }
class ____ { public static Instant now() { return Instant.now(); } } """) .doTest(); } }
Test
java
apache__camel
components/camel-saxon/src/test/java/org/apache/camel/component/xquery/XQueryWithExplicitTypeTest.java
{ "start": 1084, "end": 1892 }
class ____ extends CamelSpringTestSupport { protected MockEndpoint raleighEndpoint; protected MockEndpoint tampaEndpoint; @Test public void testFunctions() throws Exception { raleighEndpoint.expectedMessageCount(1); tampaEndpoint.expectedMessageCount(0); template.sendBody("direct:start", "<person name='Hadrian' city='Raleigh'/>"); MockEndpoint.assertIsSatisfied(context); } @Override public void doPostSetup() throws Exception { raleighEndpoint = getMockEndpoint("mock:foo.Raleigh"); tampaEndpoint = getMockEndpoint("mock:foo.Tampa"); } @Override protected AbstractXmlApplicationContext createApplicationContext() { return newAppContext("xqueryWithExplicitTypeContext.xml"); } }
XQueryWithExplicitTypeTest
java
apache__camel
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java
{ "start": 488947, "end": 491025 }
class ____ JAXB's unmarshaler.", displayName = "Fragment"), @YamlProperty(name = "id", type = "string", description = "The id of this node", displayName = "Id"), @YamlProperty(name = "ignoreJAXBElement", type = "boolean", defaultValue = "true", description = "Whether to ignore JAXBElement elements - only needed to be set to false in very special use-cases.", displayName = "Ignore JAXBElement"), @YamlProperty(name = "jaxbProviderProperties", type = "string", description = "Refers to a custom java.util.Map to lookup in the registry containing custom JAXB provider properties to be used with the JAXB marshaller.", displayName = "Jaxb Provider Properties"), @YamlProperty(name = "mustBeJAXBElement", type = "boolean", defaultValue = "false", description = "Whether marhsalling must be java objects with JAXB annotations. And if not then it fails. This option can be set to false to relax that, such as when the data is already in XML format.", displayName = "Must Be JAXBElement"), @YamlProperty(name = "namespacePrefix", type = "string", description = "When marshalling using JAXB or SOAP then the JAXB implementation will automatically assign namespace prefixes, such as ns2, ns3, ns4 etc. To control this mapping, Camel allows you to refer to a map which contains the desired mapping.", displayName = "Namespace Prefix"), @YamlProperty(name = "noNamespaceSchemaLocation", type = "string", description = "To define the location of the namespaceless schema", displayName = "No Namespace Schema Location"), @YamlProperty(name = "objectFactory", type = "boolean", defaultValue = "true", description = "Whether to allow using ObjectFactory classes to create the POJO classes during marshalling. This only applies to POJO classes that has not been annotated with JAXB and providing jaxb.index descriptor files.", displayName = "Object Factory"), @YamlProperty(name = "partClass", type = "string", description = "Name of
to
java
quarkusio__quarkus
devtools/maven/src/main/java/io/quarkus/maven/ImagePushMojo.java
{ "start": 479, "end": 788 }
class ____ extends AbstractImageMojo { @Override protected boolean beforeExecute() throws MojoExecutionException { systemProperties = new HashMap<>(systemProperties); systemProperties.put("quarkus.container-image.push", "true"); return super.beforeExecute(); } }
ImagePushMojo
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/hashmaptypehandler/HashMapTypeHandlerTest.java
{ "start": 1108, "end": 3074 }
class ____ { private static SqlSessionFactory sqlSessionFactory; @BeforeAll static void setUp() throws Exception { // create an SqlSessionFactory try (Reader reader = Resources .getResourceAsReader("org/apache/ibatis/submitted/hashmaptypehandler/mybatis-config.xml")) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } // populate in-memory database BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), "org/apache/ibatis/submitted/hashmaptypehandler/CreateDB.sql"); } @Test void shouldNotApplyTypeHandlerToParamMap() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { Mapper mapper = sqlSession.getMapper(Mapper.class); User user = mapper.getUser(1, "User1"); Assertions.assertEquals("User1", user.getName()); } } @Test void shouldNotApplyTypeHandlerToParamMapXml() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { Mapper mapper = sqlSession.getMapper(Mapper.class); User user = mapper.getUserXml(1, "User1"); Assertions.assertEquals("User1", user.getName()); } } @Test void shouldApplyHashMapTypeHandler() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { Mapper mapper = sqlSession.getMapper(Mapper.class); HashMap<String, String> map = new HashMap<>(); map.put("name", "User1"); User user = mapper.getUserWithTypeHandler(map); Assertions.assertNotNull(user); } } @Test void shouldApplyHashMapTypeHandlerXml() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { Mapper mapper = sqlSession.getMapper(Mapper.class); HashMap<String, String> map = new HashMap<>(); map.put("name", "User1"); map.put("dummy", "NoSuchUser"); User user = mapper.getUserWithTypeHandlerXml(map); Assertions.assertNotNull(user); } } }
HashMapTypeHandlerTest
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableRefCountTest.java
{ "start": 27284, "end": 27918 }
class ____ extends ConnectableObservable<Object> { @Override public void connect(Consumer<? super Disposable> connection) { try { connection.accept(Disposable.empty()); } catch (Throwable ex) { throw ExceptionHelper.wrapOrThrow(ex); } } @Override public void reset() { // nothing to do in this test } @Override protected void subscribeActual(Observer<? super Object> observer) { throw new TestException("subscribeActual"); } } static final
BadObservableSubscribe
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/headers/VertxHeadersTest.java
{ "start": 750, "end": 1282 }
class ____ { @RegisterExtension static QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar.addClasses(VertxFilter.class, JaxRsFilter.class, TestResource.class)); @Test void testVaryHeaderValues() { var headers = when().get("/test") .then() .statusCode(200) .extract().headers(); assertThat(headers.getValues(HttpHeaders.VARY)).containsExactlyInAnyOrder("Origin", "Prefer"); } public static
VertxHeadersTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/SQLParserUtilsTest.java
{ "start": 243, "end": 494 }
class ____ { @Test public void test_0() throws Exception { assertEquals( SQLType.SET_PROJECT, SQLParserUtils.getSQLTypeV2("setproject odps.sql.allow.fullscan=true;", DbType.odps)); } }
SQLParserUtilsTest
java
google__error-prone
core/src/main/java/com/google/errorprone/refaster/annotation/Placeholder.java
{ "start": 3266, "end": 3576 }
interface ____ { // TODO(lowasser): consider putting forbiddenKinds here as an annotation parameter /** * Identifies whether the placeholder is allowed to match an expression which simply returns one * of the placeholder arguments unchanged. */ boolean allowsIdentity() default false; }
Placeholder
java
elastic__elasticsearch
modules/lang-expression/src/test/java/org/elasticsearch/script/expression/ExpressionTermsSetQueryTests.java
{ "start": 1423, "end": 3577 }
class ____ extends ESTestCase { private ExpressionScriptEngine service; private SearchLookup lookup; @Override public void setUp() throws Exception { super.setUp(); NumberFieldType fieldType = new NumberFieldType("field", NumberType.DOUBLE); SortedNumericDoubleValues doubleValues = mock(SortedNumericDoubleValues.class); when(doubleValues.advanceExact(anyInt())).thenReturn(true); when(doubleValues.nextValue()).thenReturn(2.718); LeafNumericFieldData atomicFieldData = mock(LeafNumericFieldData.class); when(atomicFieldData.getDoubleValues()).thenReturn(doubleValues); IndexNumericFieldData fieldData = mock(IndexNumericFieldData.class); when(fieldData.getFieldName()).thenReturn("field"); when(fieldData.load(any())).thenReturn(atomicFieldData); service = new ExpressionScriptEngine(); lookup = new SearchLookup( field -> field.equals("field") ? fieldType : null, (ignored, _lookup, fdt) -> fieldData, (ctx, doc) -> Source.empty(XContentType.JSON) ); } private TermsSetQueryScript.LeafFactory compile(String expression) { TermsSetQueryScript.Factory factory = service.compile(null, expression, TermsSetQueryScript.CONTEXT, Collections.emptyMap()); return factory.newFactory(Collections.emptyMap(), lookup); } public void testCompileError() { ScriptException e = expectThrows(ScriptException.class, () -> { compile("doc['field'].value * *@#)(@$*@#$ + 4"); }); assertTrue(e.getCause() instanceof ParseException); } public void testLinkError() { ScriptException e = expectThrows(ScriptException.class, () -> { compile("doc['nonexistent'].value * 5"); }); assertTrue(e.getCause() instanceof ParseException); } public void testFieldAccess() throws IOException { TermsSetQueryScript script = compile("doc['field'].value").newInstance(null); script.setDocument(1); double result = script.execute().doubleValue(); assertEquals(2.718, result, 0.0); } }
ExpressionTermsSetQueryTests
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/proxy/AbstractSystemPropertyProxyTest.java
{ "start": 484, "end": 2400 }
class ____ extends ProxyTestBase { protected static QuarkusUnitTest config(String applicationProperties) { return new QuarkusUnitTest() .withApplicationRoot( jar -> jar.addClasses(Client1.class, Client2.class, Client3.class, ViaHeaderReturningResource.class)) .withConfigurationResource(applicationProperties); } @RestClient Client1 client1; @RestClient Client2 client2; /* * - client1 should use JVM settings, set with -Dhttp.proxyHost, etc (8182) * - CDI managed client2 should use client specific settings as configured in the properties (8181) * - client created with builder should use system settings by default (8182) */ @Test @SetSystemProperty(key = "http.proxyHost", value = "localhost") @SetSystemProperty(key = "http.proxyPort", value = "8182") // the default nonProxyHosts skip proxying localhost @SetSystemProperty(key = "http.nonProxyHosts", value = "example.com") void shouldProxyWithSystemProperties() { assertThat(client1.get().readEntity(String.class)).isEqualTo(PROXY_8182); assertThat(client2.get().readEntity(String.class)).isEqualTo(PROXY_8181); Response response = RestClientBuilder.newBuilder().baseUri(appUri).build(Client2.class).get(); assertThat(response.readEntity(String.class)).isEqualTo(PROXY_8182); response = RestClientBuilder.newBuilder().baseUri(appUri).build(Client2.class).get(); assertThat(response.readEntity(String.class)).isEqualTo(PROXY_8182); RestClientBuilderImpl restClientBuilder = (RestClientBuilderImpl) RestClientBuilder.newBuilder(); response = restClientBuilder.baseUri(appUri).proxyAddress("none", -1) .build(Client2.class).get(); assertThat(response.readEntity(String.class)).isEqualTo(NO_PROXY); } }
AbstractSystemPropertyProxyTest