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
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/update/UpdateResponse.java
{ "start": 3869, "end": 4146 }
class ____ {@link UpdateResponse}. This builder is usually used during xcontent parsing to * temporarily store the parsed values, then the {@link DocWriteResponse.Builder#build()} method is called to * instantiate the {@link UpdateResponse}. */ public static
for
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3872ProfileActivationInRelocatedPomTest.java
{ "start": 1183, "end": 2373 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Verify that profiles are activated in relocated POMs. * * @throws Exception in case of failure */ @Test public void testit() throws Exception { File testDir = extractResources("/mng-3872"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteArtifacts("org.apache.maven.its.mng3872"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("--settings"); verifier.addCliArgument("settings.xml"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); List<String> compileClassPath = verifier.loadLines("target/compile.txt"); assertTrue(compileClassPath.contains("a-0.1.jar"), compileClassPath.toString()); assertTrue(compileClassPath.contains("b-0.1.jar"), compileClassPath.toString()); assertFalse(compileClassPath.contains("c-0.1.jar"), compileClassPath.toString()); } }
MavenITmng3872ProfileActivationInRelocatedPomTest
java
elastic__elasticsearch
x-pack/plugin/old-lucene-versions/src/main/java/org/elasticsearch/xpack/lucene/bwc/codecs/lucene70/Lucene70DocValuesProducer.java
{ "start": 36058, "end": 37304 }
class ____ extends SortedDocValues { final SortedEntry entry; final IndexInput data; final TermsEnum termsEnum; BaseSortedDocValues(SortedEntry entry, IndexInput data) throws IOException { this.entry = entry; this.data = data; this.termsEnum = termsEnum(); } @Override public int getValueCount() { return Math.toIntExact(entry.termsDictSize); } @Override public BytesRef lookupOrd(int ord) throws IOException { termsEnum.seekExact(ord); return termsEnum.term(); } @Override public int lookupTerm(BytesRef key) throws IOException { SeekStatus status = termsEnum.seekCeil(key); switch (status) { case FOUND: return Math.toIntExact(termsEnum.ord()); case NOT_FOUND: case END: default: return Math.toIntExact(-1L - termsEnum.ord()); } } @Override public TermsEnum termsEnum() throws IOException { return new TermsDict(entry, data); } } private abstract static
BaseSortedDocValues
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/internal/EntityEntryContext.java
{ "start": 19853, "end": 21600 }
class ____ implements ManagedEntity { private final Object entityInstance; private EntityEntry entityEntry; private ManagedEntity previous; private ManagedEntity next; private boolean useTracker; public ManagedEntityImpl(Object entityInstance) { this.entityInstance = entityInstance; useTracker = false; } @Override public Object $$_hibernate_getEntityInstance() { return entityInstance; } @Override public EntityEntry $$_hibernate_getEntityEntry() { return entityEntry; } @Override public void $$_hibernate_setEntityEntry(EntityEntry entityEntry) { this.entityEntry = entityEntry; } @Override public ManagedEntity $$_hibernate_getNextManagedEntity() { return next; } @Override public void $$_hibernate_setNextManagedEntity(ManagedEntity next) { this.next = next; } @Override public void $$_hibernate_setUseTracker(boolean useTracker) { this.useTracker = useTracker; } @Override public boolean $$_hibernate_useTracker() { return useTracker; } @Override public ManagedEntity $$_hibernate_getPreviousManagedEntity() { return previous; } @Override public void $$_hibernate_setPreviousManagedEntity(ManagedEntity previous) { this.previous = previous; } @Override public int $$_hibernate_getInstanceId() { return 0; } @Override public void $$_hibernate_setInstanceId(int id) { } @Override public EntityEntry $$_hibernate_setPersistenceInfo(EntityEntry entityEntry, ManagedEntity previous, ManagedEntity next, int instanceId) { final EntityEntry oldEntry = this.entityEntry; this.entityEntry = entityEntry; this.previous = previous; this.next = next; return oldEntry; } } private static
ManagedEntityImpl
java
spring-projects__spring-boot
build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/DefaultTimeZoneOffset.java
{ "start": 798, "end": 1057 }
class ____ can be used to change a UTC time based on the * {@link java.util.TimeZone#getDefault() default TimeZone}. This is required because * {@link ZipEntry#setTime(long)} expects times in the default timezone and not UTC. * * @author Phillip Webb */
that
java
apache__flink
flink-formats/flink-orc-nohive/src/main/java/org/apache/flink/orc/nohive/shim/OrcNoHiveShim.java
{ "start": 1590, "end": 3665 }
class ____ implements OrcShim<VectorizedRowBatch> { private static final long serialVersionUID = 1L; @Override public RecordReader createRecordReader( Configuration conf, TypeDescription schema, int[] selectedFields, List<OrcFilters.Predicate> conjunctPredicates, org.apache.flink.core.fs.Path path, long splitStart, long splitLength) throws IOException { // open ORC file and create reader org.apache.hadoop.fs.Path hPath = new org.apache.hadoop.fs.Path(path.toUri()); Reader orcReader = OrcFile.createReader(hPath, OrcFile.readerOptions(conf)); // get offset and length for the stripes that start in the split Tuple2<Long, Long> offsetAndLength = getOffsetAndLengthForSplit(splitStart, splitLength, orcReader.getStripes()); // create ORC row reader configuration Reader.Options options = new Reader.Options() .schema(schema) .range(offsetAndLength.f0, offsetAndLength.f1) .useZeroCopy(OrcConf.USE_ZEROCOPY.getBoolean(conf)) .skipCorruptRecords(OrcConf.SKIP_CORRUPT_DATA.getBoolean(conf)) .tolerateMissingSchema(OrcConf.TOLERATE_MISSING_SCHEMA.getBoolean(conf)); // TODO configure filters // configure selected fields options.include(computeProjectionMask(schema, selectedFields)); // create ORC row reader RecordReader orcRowsReader = orcReader.rows(options); // assign ids schema.getId(); return orcRowsReader; } @Override public OrcNoHiveBatchWrapper createBatchWrapper(TypeDescription schema, int batchSize) { return new OrcNoHiveBatchWrapper(schema.createRowBatch(batchSize)); } @Override public boolean nextBatch(RecordReader reader, VectorizedRowBatch rowBatch) throws IOException { return reader.nextBatch(rowBatch); } }
OrcNoHiveShim
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/domain/SqmPluralValuedSimplePath.java
{ "start": 1487, "end": 6748 }
class ____<C> extends AbstractSqmSimplePath<C> { public SqmPluralValuedSimplePath( NavigablePath navigablePath, SqmPluralPersistentAttribute<?, C, ?> referencedNavigable, SqmPath<?> lhs, NodeBuilder nodeBuilder) { this( navigablePath, referencedNavigable, lhs, null, nodeBuilder ); } public SqmPluralValuedSimplePath( NavigablePath navigablePath, SqmPluralPersistentAttribute<?, C, ?> referencedNavigable, SqmPath<?> lhs, @Nullable String explicitAlias, NodeBuilder nodeBuilder) { // We need to do an unchecked cast here: PluralPersistentAttribute implements path source with // the element type, but paths generated from it must be collection-typed. //noinspection unchecked super( navigablePath, (SqmPathSource<C>) referencedNavigable, lhs, explicitAlias, nodeBuilder ); } @Override public SqmPluralValuedSimplePath<C> copy(SqmCopyContext context) { final SqmPluralValuedSimplePath<C> existing = context.getCopy( this ); if ( existing != null ) { return existing; } final SqmPath<?> lhsCopy = getLhs().copy( context ); final SqmPluralValuedSimplePath<C> path = context.registerCopy( this, new SqmPluralValuedSimplePath<>( getNavigablePathCopy( lhsCopy ), (SqmPluralPersistentAttribute<?,C,?>) getModel(), lhsCopy, getExplicitAlias(), nodeBuilder() ) ); copyTo( path, context ); return path; } public PluralPersistentAttribute<?, C, ?> getPluralAttribute() { return (SqmPluralPersistentAttribute<?, C, ?>) getModel(); } @Override public @NonNull JavaType<C> getJavaTypeDescriptor() { return getPluralAttribute().getAttributeJavaType(); } @Override public <T> T accept(SemanticQueryWalker<T> walker) { return walker.visitPluralValuedPath( this ); } @Override public SqmPath<?> resolvePathPart( String name, boolean isTerminal, SqmCreationState creationState) { // this is a reference to a collection outside the from clause final CollectionPart.Nature nature = CollectionPart.Nature.fromNameExact( name ); if ( nature == null ) { throw new PathException( "Plural path '" + getNavigablePath() + "' refers to a collection and so element attribute '" + name + "' may not be referenced directly (use element() function)" ); } final SqmPath<?> sqmPath = get( name, true ); creationState.getProcessingStateStack().getCurrent().getPathRegistry().register( sqmPath ); return sqmPath; } @Override public SqmPath<?> resolveIndexedAccess( SqmExpression<?> selector, boolean isTerminal, SqmCreationState creationState) { final SqmPathRegistry pathRegistry = creationState.getCurrentProcessingState().getPathRegistry(); final String alias = selector.toHqlString(); final NavigablePath navigablePath = getParentNavigablePath() .append( getNavigablePath().getLocalName(), alias ) .append( CollectionPart.Nature.ELEMENT.getName() ); final SqmFrom<?, ?> indexedPath = pathRegistry.findFromByPath( navigablePath ); if ( indexedPath != null ) { return indexedPath; } final SqmFrom<?, ?> path = pathRegistry.findFromByPath( castNonNull( navigablePath.getParent() ) ); final SqmAttributeJoin<Object, ?> join; if ( path == null ) { final SqmPathSource<C> referencedPathSource = getReferencedPathSource(); final SqmFrom<?, Object> parent = pathRegistry.resolveFrom( getLhs() ); final SqmExpression<?> index; if ( referencedPathSource instanceof ListPersistentAttribute<?, ?> ) { join = new SqmListJoin<>( parent, (SqmListPersistentAttribute<Object, ?>) referencedPathSource, alias, SqmJoinType.INNER, false, parent.nodeBuilder() ); index = ( (SqmListJoin<?, ?>) join ).index(); } else if ( referencedPathSource instanceof MapPersistentAttribute<?, ?, ?> ) { join = new SqmMapJoin<>( parent, (SqmMapPersistentAttribute<Object, ?, ?>) referencedPathSource, alias, SqmJoinType.INNER, false, parent.nodeBuilder() ); index = ( (SqmMapJoin<?, ?, ?>) join ).key(); } else { throw new NotIndexedCollectionException( "Index operator applied to path '" + getNavigablePath() + "' which is not a list or map" ); } join.setJoinPredicate( creationState.getCreationContext().getNodeBuilder().equal( index, selector ) ); parent.addSqmJoin( join ); pathRegistry.register( join ); } else { //noinspection unchecked join = (SqmAttributeJoin<Object, ?>) path; } final SqmIndexedCollectionAccessPath<Object> result = new SqmIndexedCollectionAccessPath<>( navigablePath, join, selector ); pathRegistry.register( result ); return result; } @Override public SqmExpression<Class<? extends C>> type() { throw new UnsupportedOperationException( "Cannot access the type of plural valued simple paths" ); } @Override public <S extends C> SqmTreatedPath<C, S> treatAs(Class<S> treatJavaType) { throw new UnsupportedOperationException( "Cannot treat plural valued simple paths" ); } @Override public <S extends C> SqmTreatedEntityValuedSimplePath<C, S> treatAs(EntityDomainType<S> treatTarget) { throw new UnsupportedOperationException( "Cannot treat plural valued simple paths" ); } }
SqmPluralValuedSimplePath
java
apache__hadoop
hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/CompressionEmulationUtil.java
{ "start": 6721, "end": 19095 }
class ____ { private static Map<Float, Integer> map = new HashMap<Float, Integer>(60); private static final float MIN_RATIO = 0.07F; private static final float MAX_RATIO = 0.68F; // add the empirically obtained data points in the lookup table CompressionRatioLookupTable() { map.put(.07F,30); map.put(.08F,25); map.put(.09F,60); map.put(.10F,20); map.put(.11F,70); map.put(.12F,15); map.put(.13F,80); map.put(.14F,85); map.put(.15F,90); map.put(.16F,95); map.put(.17F,100); map.put(.18F,105); map.put(.19F,110); map.put(.20F,115); map.put(.21F,120); map.put(.22F,125); map.put(.23F,130); map.put(.24F,140); map.put(.25F,145); map.put(.26F,150); map.put(.27F,155); map.put(.28F,160); map.put(.29F,170); map.put(.30F,175); map.put(.31F,180); map.put(.32F,190); map.put(.33F,195); map.put(.34F,205); map.put(.35F,215); map.put(.36F,225); map.put(.37F,230); map.put(.38F,240); map.put(.39F,250); map.put(.40F,260); map.put(.41F,270); map.put(.42F,280); map.put(.43F,295); map.put(.44F,310); map.put(.45F,325); map.put(.46F,335); map.put(.47F,355); map.put(.48F,375); map.put(.49F,395); map.put(.50F,420); map.put(.51F,440); map.put(.52F,465); map.put(.53F,500); map.put(.54F,525); map.put(.55F,550); map.put(.56F,600); map.put(.57F,640); map.put(.58F,680); map.put(.59F,734); map.put(.60F,813); map.put(.61F,905); map.put(.62F,1000); map.put(.63F,1055); map.put(.64F,1160); map.put(.65F,1355); map.put(.66F,1510); map.put(.67F,1805); map.put(.68F,2170); } /** * Returns the size of the word in {@link RandomTextDataGenerator}'s * dictionary that can generate text with the desired compression ratio. * * @throws RuntimeException If ratio is less than {@value #MIN_RATIO} or * greater than {@value #MAX_RATIO}. */ int getWordSizeForRatio(float ratio) { ratio = standardizeCompressionRatio(ratio); if (ratio >= MIN_RATIO && ratio <= MAX_RATIO) { return map.get(ratio); } else { throw new RuntimeException("Compression ratio should be in the range [" + MIN_RATIO + "," + MAX_RATIO + "]. Configured compression ratio is " + ratio + "."); } } } /** * Setup the data generator's configuration to generate compressible random * text data with the desired compression ratio. * Note that the compression ratio, if configured, will set the * {@link RandomTextDataGenerator}'s list-size and word-size based on * empirical values using the compression ratio set in the configuration. * * Hence to achieve the desired compression ratio, * {@link RandomTextDataGenerator}'s list-size will be set to the default * value i.e {@value RandomTextDataGenerator#DEFAULT_LIST_SIZE}. */ static void setupDataGeneratorConfig(Configuration conf) { boolean compress = isCompressionEmulationEnabled(conf); if (compress) { float ratio = getMapInputCompressionEmulationRatio(conf); LOG.info("GridMix is configured to generate compressed input data with " + " a compression ratio of " + ratio); int wordSize = COMPRESSION_LOOKUP_TABLE.getWordSizeForRatio(ratio); RandomTextDataGenerator.setRandomTextDataGeneratorWordSize(conf, wordSize); // since the compression ratios are computed using the default value of // list size RandomTextDataGenerator.setRandomTextDataGeneratorListSize(conf, RandomTextDataGenerator.DEFAULT_LIST_SIZE); } } /** * Returns a {@link RandomTextDataGenerator} that generates random * compressible text with the desired compression ratio. */ static RandomTextDataGenerator getRandomTextDataGenerator(float ratio, long seed) { int wordSize = COMPRESSION_LOOKUP_TABLE.getWordSizeForRatio(ratio); RandomTextDataGenerator rtg = new RandomTextDataGenerator(RandomTextDataGenerator.DEFAULT_LIST_SIZE, seed, wordSize); return rtg; } /** Publishes compression related data statistics. Following statistics are * published * <ul> * <li>Total compressed input data size</li> * <li>Number of compressed input data files</li> * <li>Compression Ratio</li> * <li>Text data dictionary size</li> * <li>Random text word size</li> * </ul> */ static DataStatistics publishCompressedDataStatistics(Path inputDir, Configuration conf, long uncompressedDataSize) throws IOException { FileSystem fs = inputDir.getFileSystem(conf); CompressionCodecFactory compressionCodecs = new CompressionCodecFactory(conf); // iterate over compressed files and sum up the compressed file sizes long compressedDataSize = 0; int numCompressedFiles = 0; // obtain input data file statuses FileStatus[] outFileStatuses = fs.listStatus(inputDir, new Utils.OutputFileUtils.OutputFilesFilter()); for (FileStatus status : outFileStatuses) { // check if the input file is compressed if (compressionCodecs != null) { CompressionCodec codec = compressionCodecs.getCodec(status.getPath()); if (codec != null) { ++numCompressedFiles; compressedDataSize += status.getLen(); } } } LOG.info("Gridmix is configured to use compressed input data."); // publish the input data size LOG.info("Total size of compressed input data : " + StringUtils.humanReadableInt(compressedDataSize)); LOG.info("Total number of compressed input data files : " + numCompressedFiles); if (numCompressedFiles == 0) { throw new RuntimeException("No compressed file found in the input" + " directory : " + inputDir.toString() + ". To enable compression" + " emulation, run Gridmix either with " + " an input directory containing compressed input file(s) or" + " use the -generate option to (re)generate it. If compression" + " emulation is not desired, disable it by setting '" + COMPRESSION_EMULATION_ENABLE + "' to 'false'."); } // publish compression ratio only if its generated in this gridmix run if (uncompressedDataSize > 0) { // compute the compression ratio double ratio = ((double)compressedDataSize) / uncompressedDataSize; // publish the compression ratio LOG.info("Input Data Compression Ratio : " + ratio); } return new DataStatistics(compressedDataSize, numCompressedFiles, true); } /** * Enables/Disables compression emulation. * @param conf Target configuration where the parameter * {@value #COMPRESSION_EMULATION_ENABLE} will be set. * @param val The value to be set. */ static void setCompressionEmulationEnabled(Configuration conf, boolean val) { conf.setBoolean(COMPRESSION_EMULATION_ENABLE, val); } /** * Checks if compression emulation is enabled or not. Default is {@code true}. */ static boolean isCompressionEmulationEnabled(Configuration conf) { return conf.getBoolean(COMPRESSION_EMULATION_ENABLE, true); } /** * Enables/Disables input decompression emulation. * @param conf Target configuration where the parameter * {@value #INPUT_DECOMPRESSION_EMULATION_ENABLE} will be set. * @param val The value to be set. */ static void setInputCompressionEmulationEnabled(Configuration conf, boolean val) { conf.setBoolean(INPUT_DECOMPRESSION_EMULATION_ENABLE, val); } /** * Check if input decompression emulation is enabled or not. * Default is {@code false}. */ static boolean isInputCompressionEmulationEnabled(Configuration conf) { return conf.getBoolean(INPUT_DECOMPRESSION_EMULATION_ENABLE, false); } /** * Set the map input data compression ratio in the given conf. */ static void setMapInputCompressionEmulationRatio(Configuration conf, float ratio) { conf.setFloat(GRIDMIX_MAP_INPUT_COMPRESSION_RATIO, ratio); } /** * Get the map input data compression ratio using the given configuration. * If the compression ratio is not set in the configuration then use the * default value i.e {@value #DEFAULT_COMPRESSION_RATIO}. */ static float getMapInputCompressionEmulationRatio(Configuration conf) { return conf.getFloat(GRIDMIX_MAP_INPUT_COMPRESSION_RATIO, DEFAULT_COMPRESSION_RATIO); } /** * Set the map output data compression ratio in the given configuration. */ static void setMapOutputCompressionEmulationRatio(Configuration conf, float ratio) { conf.setFloat(GRIDMIX_MAP_OUTPUT_COMPRESSION_RATIO, ratio); } /** * Get the map output data compression ratio using the given configuration. * If the compression ratio is not set in the configuration then use the * default value i.e {@value #DEFAULT_COMPRESSION_RATIO}. */ static float getMapOutputCompressionEmulationRatio(Configuration conf) { return conf.getFloat(GRIDMIX_MAP_OUTPUT_COMPRESSION_RATIO, DEFAULT_COMPRESSION_RATIO); } /** * Set the job output data compression ratio in the given configuration. */ static void setJobOutputCompressionEmulationRatio(Configuration conf, float ratio) { conf.setFloat(GRIDMIX_JOB_OUTPUT_COMPRESSION_RATIO, ratio); } /** * Get the job output data compression ratio using the given configuration. * If the compression ratio is not set in the configuration then use the * default value i.e {@value #DEFAULT_COMPRESSION_RATIO}. */ static float getJobOutputCompressionEmulationRatio(Configuration conf) { return conf.getFloat(GRIDMIX_JOB_OUTPUT_COMPRESSION_RATIO, DEFAULT_COMPRESSION_RATIO); } /** * Standardize the compression ratio i.e round off the compression ratio to * only 2 significant digits. */ static float standardizeCompressionRatio(float ratio) { // round off to 2 significant digits int significant = (int)Math.round(ratio * 100); return ((float)significant)/100; } /** * Returns a {@link InputStream} for a file that might be compressed. */ static InputStream getPossiblyDecompressedInputStream(Path file, Configuration conf, long offset) throws IOException { FileSystem fs = file.getFileSystem(conf); if (isCompressionEmulationEnabled(conf) && isInputCompressionEmulationEnabled(conf)) { CompressionCodecFactory compressionCodecs = new CompressionCodecFactory(conf); CompressionCodec codec = compressionCodecs.getCodec(file); if (codec != null) { Decompressor decompressor = CodecPool.getDecompressor(codec); if (decompressor != null) { CompressionInputStream in = codec.createInputStream(fs.open(file), decompressor); //TODO Seek doesnt work with compressed input stream. // Use SplittableCompressionCodec? return (InputStream)in; } } } FSDataInputStream in = fs.open(file); in.seek(offset); return (InputStream)in; } /** * Returns a {@link OutputStream} for a file that might need * compression. */ static OutputStream getPossiblyCompressedOutputStream(Path file, Configuration conf) throws IOException { FileSystem fs = file.getFileSystem(conf); JobConf jConf = new JobConf(conf); if (org.apache.hadoop.mapred.FileOutputFormat.getCompressOutput(jConf)) { // get the codec
CompressionRatioLookupTable
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/SessionFactory.java
{ "start": 1003, "end": 1783 }
class ____ { /// @Test /// void testStuff(SessionFactoryScope factoryScope) { /// ... /// } /// } /// ``` /// /// @see SessionFactoryExtension /// @see SessionFactoryScope /// /// @author Steve Ebersole @Inherited @Target({ElementType.TYPE, ElementType.METHOD}) @Retention( RetentionPolicy.RUNTIME ) @TestInstance( TestInstance.Lifecycle.PER_CLASS ) @ExtendWith( FailureExpectedExtension.class ) @ExtendWith( ServiceRegistryExtension.class ) @ExtendWith( ServiceRegistryParameterResolver.class ) @ExtendWith( DomainModelExtension.class ) @ExtendWith( DomainModelParameterResolver.class ) @ExtendWith( SessionFactoryExtension.class ) @ExtendWith( SessionFactoryParameterResolver.class ) @ExtendWith( SessionFactoryScopeParameterResolver.class ) public @
SomeTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/AppPage.java
{ "start": 1290, "end": 2029 }
class ____ extends RmView { @Override protected void preHead(Page.HTML<__> html) { commonPreHead(html); String appId = $(YarnWebParams.APPLICATION_ID); set( TITLE, appId.isEmpty() ? "Bad request: missing application ID" : join( "Application ", $(YarnWebParams.APPLICATION_ID))); set(DATATABLES_ID, "attempts ResourceRequests"); set(initID(DATATABLES, "attempts"), WebPageUtils.attemptsTableInit()); setTableStyles(html, "attempts", ".queue {width:6em}", ".ui {width:8em}"); setTableStyles(html, "ResourceRequests"); set(YarnWebParams.WEB_UI_TYPE, YarnWebParams.RM_WEB_UI); } @Override protected Class<? extends SubView> content() { return RMAppBlock.class; } }
AppPage
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/synapse/Synapse.java
{ "start": 130, "end": 224 }
class ____ { public static final SQLDialect dialect = SQLDialect.of(DbType.synapse); }
Synapse
java
resilience4j__resilience4j
resilience4j-micrometer/src/main/java/io/github/resilience4j/micrometer/tagged/ThreadPoolBulkheadMetricNames.java
{ "start": 4556, "end": 8707 }
class ____ { private final ThreadPoolBulkheadMetricNames metricNames = new ThreadPoolBulkheadMetricNames(); /** * Overrides the default metric name {@value ThreadPoolBulkheadMetricNames#DEFAULT_BULKHEAD_QUEUE_DEPTH_METRIC_NAME} * with a given one. * * @param queueDepthMetricName The queue depth metric name. * @return The builder. */ public Builder queueDepthMetricName(String queueDepthMetricName) { metricNames.queueDepthMetricName = requireNonNull(queueDepthMetricName); return this; } /** * Overrides the default metric name {@value ThreadPoolBulkheadMetricNames#DEFAULT_THREAD_POOL_SIZE_METRIC_NAME} * with a given one. * * @param threadPoolSizeMetricName The thread pool size metric name. * @return The builder. */ public Builder threadPoolSizeMetricName(String threadPoolSizeMetricName) { metricNames.threadPoolSizeMetricName = requireNonNull(threadPoolSizeMetricName); return this; } /** * Overrides the default metric name {@value ThreadPoolBulkheadMetricNames#DEFAULT_MAX_THREAD_POOL_SIZE_METRIC_NAME} * with a given one. * * @param maxThreadPoolSizeMetricName The max thread pool size metric name. * @return The builder. */ public Builder maxThreadPoolSizeMetricName(String maxThreadPoolSizeMetricName) { metricNames.maxThreadPoolSizeMetricName = requireNonNull( maxThreadPoolSizeMetricName); return this; } /** * Overrides the default metric name {@value ThreadPoolBulkheadMetricNames#DEFAULT_CORE_THREAD_POOL_SIZE_METRIC_NAME} * with a given one. * * @param coreThreadPoolSizeMetricName The core thread pool size metric name. * @return The builder. */ public Builder coreThreadPoolSizeMetricName(String coreThreadPoolSizeMetricName) { metricNames.coreThreadPoolSizeMetricName = requireNonNull( coreThreadPoolSizeMetricName); return this; } /** * Overrides the default metric name {@value ThreadPoolBulkheadMetricNames#DEFAULT_BULKHEAD_QUEUE_CAPACITY_METRIC_NAME} * with a given one. * * @param queueCapacityMetricName The queue capacity metric name. * @return The builder. */ public Builder queueCapacityMetricName(String queueCapacityMetricName) { metricNames.queueCapacityMetricName = requireNonNull(queueCapacityMetricName); return this; } /** * Overrides the default metric name {@value ThreadPoolBulkheadMetricNames#DEFAULT_BULKHEAD_ACTIVE_THREAD_COUNT_METRIC_NAME} * with a given one. * * @param activeThreadCountMetricName The active thread count metric name. * @return The builder. */ public Builder activeThreadCountMetricName( String activeThreadCountMetricName) { metricNames.activeThreadCountMetricName = requireNonNull( activeThreadCountMetricName); return this; } /** * Overrides the default metric name {@value ThreadPoolBulkheadMetricNames#DEFAULT_BULKHEAD_AVAILABLE_THREAD_COUNT_METRIC_NAME} * with a given one. * * @param availableThreadCountMetricName The active thread count metric name. * @return The builder. */ public Builder availableThreadCountMetricName( String availableThreadCountMetricName) { metricNames.availableThreadCountMetricName = requireNonNull( availableThreadCountMetricName); return this; } /** * Builds {@link ThreadPoolBulkheadMetricNames} instance. * * @return The built {@link ThreadPoolBulkheadMetricNames} instance. */ public ThreadPoolBulkheadMetricNames build() { return metricNames; } } }
Builder
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/AcosEvaluator.java
{ "start": 1123, "end": 4132 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(AcosEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator val; private final DriverContext driverContext; private Warnings warnings; public AcosEvaluator(Source source, EvalOperator.ExpressionEvaluator val, DriverContext driverContext) { this.source = source; this.val = val; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (DoubleBlock valBlock = (DoubleBlock) val.eval(page)) { DoubleVector valVector = valBlock.asVector(); if (valVector == null) { return eval(page.getPositionCount(), valBlock); } return eval(page.getPositionCount(), valVector); } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += val.baseRamBytesUsed(); return baseRamBytesUsed; } public DoubleBlock eval(int positionCount, DoubleBlock valBlock) { try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { switch (valBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } double val = valBlock.getDouble(valBlock.getFirstValueIndex(p)); try { result.appendDouble(Acos.process(val)); } catch (ArithmeticException e) { warnings().registerException(e); result.appendNull(); } } return result.build(); } } public DoubleBlock eval(int positionCount, DoubleVector valVector) { try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { double val = valVector.getDouble(p); try { result.appendDouble(Acos.process(val)); } catch (ArithmeticException e) { warnings().registerException(e); result.appendNull(); } } return result.build(); } } @Override public String toString() { return "AcosEvaluator[" + "val=" + val + "]"; } @Override public void close() { Releasables.closeExpectNoException(val); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
AcosEvaluator
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/JpqlQueryCreator.java
{ "start": 764, "end": 944 }
interface ____ allows implementations to create JPQL queries providing details about parameter bindings and * the selection mechanism. * * @author Mark Paluch * @since 4.0 */
that
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/SerializationOrderTest.java
{ "start": 1731, "end": 1940 }
class ____ { public int d = 4; public int c = 3; public int b = 2; public int a = 1; } // For [databind#311] @JsonPropertyOrder(alphabetic = true) static
BeanFor459
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/FSTestWrapper.java
{ "start": 4532, "end": 4792 }
enum ____ { isDir, isFile, isSymlink }; abstract public void checkFileStatus(String path, fileType expectedType) throws IOException; abstract public void checkFileLinkStatus(String path, fileType expectedType) throws IOException; }
fileType
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/shrink/ResizeNumberOfShardsCalculator.java
{ "start": 1209, "end": 2333 }
interface ____ { /** * Calculates the target number of shards based on the parameters of the request * @param numberOfShards requested number of shards or null if it was not provided * @param maxPrimaryShardSize requested max primary shard size or null if it was not provided * @param sourceMetadata the index metadata of the source index * @return the number of shards for the target index */ int calculate(@Nullable Integer numberOfShards, @Nullable ByteSizeValue maxPrimaryShardSize, IndexMetadata sourceMetadata); /** * Validates the target number of shards based on the operation. For example, in the case of SHRINK it will check if the doc count per * shard is within limits and in the other opetations it will ensure we get the right exceptions if the number of shards is wrong or * less than etc. * @param numberOfShards the number of shards the target index is going to have * @param sourceMetadata the index metadata of the source index */ void validate(int numberOfShards, IndexMetadata sourceMetadata);
ResizeNumberOfShardsCalculator
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/fuseable/HasUpstreamMaybeSource.java
{ "start": 920, "end": 1170 }
interface ____<@NonNull T> { /** * Returns the upstream source of this Maybe. * <p>Allows discovering the chain of observables. * @return the source MaybeSource */ @NonNull MaybeSource<T> source(); }
HasUpstreamMaybeSource
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/common/Shortcut.java
{ "start": 1088, "end": 1760 }
interface ____ { /** * The names and order of arguments for a shortcut. Synonym for {@link #fieldOrder()}. * Defaults to the names and order of the method on which this is declared. */ @AliasFor("fieldOrder") String[] value() default {}; /** * The names and order of arguments for a shortcut. Synonym for {@link #value()}. * Defaults to the names and order of the method on which this is declared. */ @AliasFor("value") String[] fieldOrder() default {}; /** * Strategy for parsing the shortcut String. */ Type type() default Type.DEFAULT; /** * Optional property prefix to be appended to fields. */ String fieldPrefix() default "";
Shortcut
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/web/server/HttpsRedirectSpecTests.java
{ "start": 5424, "end": 5713 }
class ____ { @Bean SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { // @formatter:off http .redirectToHttps(withDefaults()); // @formatter:on return http.build(); } } @Configuration @EnableWebFlux @EnableWebFluxSecurity static
RedirectToHttpConfig
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/StDistanceCartesianPointDocValuesAndSourceEvaluator.java
{ "start": 1101, "end": 3682 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(StDistanceCartesianPointDocValuesAndSourceEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator left; private final EvalOperator.ExpressionEvaluator right; private final DriverContext driverContext; private Warnings warnings; public StDistanceCartesianPointDocValuesAndSourceEvaluator(Source source, EvalOperator.ExpressionEvaluator left, EvalOperator.ExpressionEvaluator right, DriverContext driverContext) { this.source = source; this.left = left; this.right = right; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (LongBlock leftBlock = (LongBlock) left.eval(page)) { try (BytesRefBlock rightBlock = (BytesRefBlock) right.eval(page)) { return eval(page.getPositionCount(), leftBlock, rightBlock); } } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += left.baseRamBytesUsed(); baseRamBytesUsed += right.baseRamBytesUsed(); return baseRamBytesUsed; } public DoubleBlock eval(int positionCount, LongBlock leftBlock, BytesRefBlock rightBlock) { try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { boolean allBlocksAreNulls = true; if (!leftBlock.isNull(p)) { allBlocksAreNulls = false; } if (!rightBlock.isNull(p)) { allBlocksAreNulls = false; } if (allBlocksAreNulls) { result.appendNull(); continue position; } StDistance.processCartesianPointDocValuesAndSource(result, p, leftBlock, rightBlock); } return result.build(); } } @Override public String toString() { return "StDistanceCartesianPointDocValuesAndSourceEvaluator[" + "left=" + left + ", right=" + right + "]"; } @Override public void close() { Releasables.closeExpectNoException(left, right); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
StDistanceCartesianPointDocValuesAndSourceEvaluator
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/SqlPlugin.java
{ "start": 2128, "end": 6381 }
class ____ extends Plugin implements ActionPlugin { private final LicensedFeature.Momentary JDBC_FEATURE = LicensedFeature.momentary("sql", "jdbc", License.OperationMode.PLATINUM); private final LicensedFeature.Momentary ODBC_FEATURE = LicensedFeature.momentary("sql", "odbc", License.OperationMode.PLATINUM); @SuppressWarnings("this-escape") private final SqlLicenseChecker sqlLicenseChecker = new SqlLicenseChecker((mode) -> { XPackLicenseState licenseState = getLicenseState(); switch (mode) { case JDBC: if (JDBC_FEATURE.check(licenseState) == false) { throw LicenseUtils.newComplianceException("jdbc"); } break; case ODBC: if (ODBC_FEATURE.check(licenseState) == false) { throw LicenseUtils.newComplianceException("odbc"); } break; case PLAIN: case CLI: break; default: throw new IllegalArgumentException("Unknown SQL mode " + mode); } }); public SqlPlugin(Settings settings) {} // overridable by tests protected XPackLicenseState getLicenseState() { return XPackPlugin.getSharedLicenseState(); } @Override public Collection<?> createComponents(PluginServices services) { return createComponents( services.client(), services.environment().settings(), services.clusterService().getClusterName().value(), services.linkedProjectConfigService(), services.namedWriteableRegistry() ); } /** * Create components used by the sql plugin. */ Collection<Object> createComponents( Client client, Settings settings, String clusterName, LinkedProjectConfigService linkedProjectConfigService, NamedWriteableRegistry namedWriteableRegistry ) { RemoteClusterResolver remoteClusterResolver = new RemoteClusterResolver(settings, linkedProjectConfigService); IndexResolver indexResolver = new IndexResolver( client, clusterName, SqlDataTypeRegistry.INSTANCE, remoteClusterResolver::remoteClusters ); return Arrays.asList(sqlLicenseChecker, indexResolver, new PlanExecutor(client, indexResolver, namedWriteableRegistry)); } @Override public List<RestHandler> getRestHandlers( Settings settings, NamedWriteableRegistry namedWriteableRegistry, RestController restController, ClusterSettings clusterSettings, IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver, Supplier<DiscoveryNodes> nodesInCluster, Predicate<NodeFeature> clusterSupportsFeature ) { return Arrays.asList( new RestSqlQueryAction(settings), new RestSqlTranslateAction(settings), new RestSqlClearCursorAction(), new RestSqlStatsAction(), new RestSqlAsyncGetResultsAction(), new RestSqlAsyncGetStatusAction(), new RestSqlAsyncDeleteResultsAction() ); } @Override public List<ActionHandler> getActions() { var usageAction = new ActionHandler(XPackUsageFeatureAction.SQL, SqlUsageTransportAction.class); var infoAction = new ActionHandler(XPackInfoFeatureAction.SQL, SqlInfoTransportAction.class); return Arrays.asList( new ActionHandler(SqlQueryAction.INSTANCE, TransportSqlQueryAction.class), new ActionHandler(SqlTranslateAction.INSTANCE, TransportSqlTranslateAction.class), new ActionHandler(SqlClearCursorAction.INSTANCE, TransportSqlClearCursorAction.class), new ActionHandler(SqlStatsAction.INSTANCE, TransportSqlStatsAction.class), new ActionHandler(SqlAsyncGetResultsAction.INSTANCE, TransportSqlAsyncGetResultsAction.class), new ActionHandler(SqlAsyncGetStatusAction.INSTANCE, TransportSqlAsyncGetStatusAction.class), usageAction, infoAction ); } }
SqlPlugin
java
apache__hadoop
hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/ExecutionSummarizer.java
{ "start": 1997, "end": 10534 }
class ____ implements StatListener<JobStats> { static final Logger LOG = LoggerFactory.getLogger(ExecutionSummarizer.class); private static final FastDateFormat UTIL = FastDateFormat.getInstance(); private int numJobsInInputTrace; private int totalSuccessfulJobs; private int totalFailedJobs; private int totalLostJobs; private int totalMapTasksLaunched; private int totalReduceTasksLaunched; private long totalSimulationTime; private long totalRuntime; private final String commandLineArgs; private long startTime; private long endTime; private long simulationStartTime; private String inputTraceLocation; private String inputTraceSignature; private String jobSubmissionPolicy; private String resolver; private DataStatistics dataStats; private String expectedDataSize; /** * Basic constructor initialized with the runtime arguments. */ ExecutionSummarizer(String[] args) { startTime = System.currentTimeMillis(); // flatten the args string and store it commandLineArgs = org.apache.commons.lang3.StringUtils.join(args, ' '); } /** * Default constructor. */ ExecutionSummarizer() { startTime = System.currentTimeMillis(); commandLineArgs = Summarizer.NA; } void start(Configuration conf) { simulationStartTime = System.currentTimeMillis(); } private void processJobState(JobStats stats) { Job job = stats.getJob(); try { if (job.isSuccessful()) { ++totalSuccessfulJobs; } else { ++totalFailedJobs; } } catch (Exception e) { // this behavior is consistent with job-monitor which marks the job as // complete (lost) if the status polling bails out ++totalLostJobs; } } private void processJobTasks(JobStats stats) { totalMapTasksLaunched += stats.getNoOfMaps(); totalReduceTasksLaunched += stats.getNoOfReds(); } private void process(JobStats stats) { // process the job run state processJobState(stats); // process the tasks information processJobTasks(stats); } @Override public void update(JobStats item) { // process only if the simulation has started if (simulationStartTime > 0) { process(item); totalSimulationTime = System.currentTimeMillis() - getSimulationStartTime(); } } // Generates a signature for the trace file based on // - filename // - modification time // - file length // - owner protected static String getTraceSignature(String input) throws IOException { Path inputPath = new Path(input); FileSystem fs = inputPath.getFileSystem(new Configuration()); FileStatus status = fs.getFileStatus(inputPath); Path qPath = fs.makeQualified(status.getPath()); String traceID = status.getModificationTime() + qPath.toString() + status.getOwner() + status.getLen(); return MD5Hash.digest(traceID).toString(); } @SuppressWarnings("unchecked") void finalize(JobFactory factory, String inputPath, long dataSize, UserResolver userResolver, DataStatistics stats, Configuration conf) throws IOException { numJobsInInputTrace = factory.numJobsInTrace; endTime = System.currentTimeMillis(); if ("-".equals(inputPath)) { inputTraceLocation = Summarizer.NA; inputTraceSignature = Summarizer.NA; } else { Path inputTracePath = new Path(inputPath); FileSystem fs = inputTracePath.getFileSystem(conf); inputTraceLocation = fs.makeQualified(inputTracePath).toString(); inputTraceSignature = getTraceSignature(inputPath); } jobSubmissionPolicy = Gridmix.getJobSubmissionPolicy(conf).name(); resolver = userResolver.getClass().getName(); if (dataSize > 0) { expectedDataSize = StringUtils.humanReadableInt(dataSize); } else { expectedDataSize = Summarizer.NA; } dataStats = stats; totalRuntime = System.currentTimeMillis() - getStartTime(); } /** * Summarizes the current {@link Gridmix} run. */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Execution Summary:-"); builder.append("\nInput trace: ").append(getInputTraceLocation()); builder.append("\nInput trace signature: ") .append(getInputTraceSignature()); builder.append("\nTotal number of jobs in trace: ") .append(getNumJobsInTrace()); builder.append("\nExpected input data size: ") .append(getExpectedDataSize()); builder.append("\nInput data statistics: ") .append(getInputDataStatistics()); builder.append("\nTotal number of jobs processed: ") .append(getNumSubmittedJobs()); builder.append("\nTotal number of successful jobs: ") .append(getNumSuccessfulJobs()); builder.append("\nTotal number of failed jobs: ") .append(getNumFailedJobs()); builder.append("\nTotal number of lost jobs: ") .append(getNumLostJobs()); builder.append("\nTotal number of map tasks launched: ") .append(getNumMapTasksLaunched()); builder.append("\nTotal number of reduce task launched: ") .append(getNumReduceTasksLaunched()); builder.append("\nGridmix start time: ") .append(UTIL.format(getStartTime())); builder.append("\nGridmix end time: ").append(UTIL.format(getEndTime())); builder.append("\nGridmix simulation start time: ") .append(UTIL.format(getStartTime())); builder.append("\nGridmix runtime: ") .append(StringUtils.formatTime(getRuntime())); builder.append("\nTime spent in initialization (data-gen etc): ") .append(StringUtils.formatTime(getInitTime())); builder.append("\nTime spent in simulation: ") .append(StringUtils.formatTime(getSimulationTime())); builder.append("\nGridmix configuration parameters: ") .append(getCommandLineArgsString()); builder.append("\nGridmix job submission policy: ") .append(getJobSubmissionPolicy()); builder.append("\nGridmix resolver: ").append(getUserResolver()); builder.append("\n\n"); return builder.toString(); } // Gets the stringified version of DataStatistics static String stringifyDataStatistics(DataStatistics stats) { if (stats != null) { StringBuilder buffer = new StringBuilder(); String compressionStatus = stats.isDataCompressed() ? "Compressed" : "Uncompressed"; buffer.append(compressionStatus).append(" input data size: "); buffer.append(StringUtils.humanReadableInt(stats.getDataSize())); buffer.append(", "); buffer.append("Number of files: ").append(stats.getNumFiles()); return buffer.toString(); } else { return Summarizer.NA; } } // Getters protected String getExpectedDataSize() { return expectedDataSize; } protected String getUserResolver() { return resolver; } protected String getInputDataStatistics() { return stringifyDataStatistics(dataStats); } protected String getInputTraceSignature() { return inputTraceSignature; } protected String getInputTraceLocation() { return inputTraceLocation; } protected int getNumJobsInTrace() { return numJobsInInputTrace; } protected int getNumSuccessfulJobs() { return totalSuccessfulJobs; } protected int getNumFailedJobs() { return totalFailedJobs; } protected int getNumLostJobs() { return totalLostJobs; } protected int getNumSubmittedJobs() { return totalSuccessfulJobs + totalFailedJobs + totalLostJobs; } protected int getNumMapTasksLaunched() { return totalMapTasksLaunched; } protected int getNumReduceTasksLaunched() { return totalReduceTasksLaunched; } protected long getStartTime() { return startTime; } protected long getEndTime() { return endTime; } protected long getInitTime() { return simulationStartTime - startTime; } protected long getSimulationStartTime() { return simulationStartTime; } protected long getSimulationTime() { return totalSimulationTime; } protected long getRuntime() { return totalRuntime; } protected String getCommandLineArgsString() { return commandLineArgs; } protected String getJobSubmissionPolicy() { return jobSubmissionPolicy; } }
ExecutionSummarizer
java
apache__hadoop
hadoop-tools/hadoop-streaming/src/test/java/org/apache/hadoop/streaming/TestStreamReduceNone.java
{ "start": 1054, "end": 1292 }
class ____ hadoopStreaming in MapReduce local mode. * It tests the case where number of reducers is set to 0. In this case, the mappers are expected to write out outputs directly. No reducer/combiner will be activated. */ public
tests
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/runtime/BlockingOperationControl.java
{ "start": 36, "end": 549 }
class ____ { private static volatile IOThreadDetector[] ioThreadDetectors; public static void setIoThreadDetector(IOThreadDetector[] ioThreadDetector) { BlockingOperationControl.ioThreadDetectors = ioThreadDetector; } public static boolean isBlockingAllowed() { for (IOThreadDetector ioThreadDetector : ioThreadDetectors) { if (ioThreadDetector.isInIOThread()) { return false; } } return true; } }
BlockingOperationControl
java
google__guava
android/guava/src/com/google/common/collect/RegularImmutableSortedSet.java
{ "start": 1231, "end": 1392 }
class ____ a * single-element sorted set. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible @SuppressWarnings({"serial", "rawtypes"}) final
for
java
spring-projects__spring-boot
module/spring-boot-health/src/test/java/org/springframework/boot/health/autoconfigure/actuate/endpoint/HealthEndpointAutoConfigurationTests.java
{ "start": 19880, "end": 20185 }
class ____ implements HealthEndpointGroupsPostProcessor { @Override public HealthEndpointGroups postProcessHealthEndpointGroups(HealthEndpointGroups groups) { given(groups.get("test")).willThrow(new RuntimeException("postprocessed")); return groups; } } }
TestHealthEndpointGroupsPostProcessor
java
elastic__elasticsearch
x-pack/qa/full-cluster-restart/src/javaRestTest/java/org/elasticsearch/xpack/restart/MlConfigIndexMappingsFullClusterRestartIT.java
{ "start": 1167, "end": 5280 }
class ____ extends AbstractXpackFullClusterRestartTestCase { private static final String OLD_CLUSTER_JOB_ID = "ml-config-mappings-old-cluster-job"; private static final String NEW_CLUSTER_JOB_ID = "ml-config-mappings-new-cluster-job"; public MlConfigIndexMappingsFullClusterRestartIT(@Name("cluster") FullClusterRestartUpgradeStatus upgradeStatus) { super(upgradeStatus); } @Override protected Settings restClientSettings() { String token = "Basic " + Base64.getEncoder().encodeToString("test_user:x-pack-test-password".getBytes(StandardCharsets.UTF_8)); return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build(); } @Before public void waitForMlTemplates() throws Exception { // We shouldn't wait for ML templates during the upgrade - production won't if (isRunningAgainstOldCluster()) { XPackRestTestHelper.waitForTemplates(client(), XPackRestTestConstants.ML_POST_V7120_TEMPLATES); } } public void testMlConfigIndexMappingsAfterMigration() throws Exception { if (isRunningAgainstOldCluster()) { // trigger .ml-config index creation createAnomalyDetectorJob(OLD_CLUSTER_JOB_ID); // .ml-config has mappings for analytics as the feature was introduced in 7.3.0 assertThat(getDataFrameAnalysisMappings().keySet(), hasItem("outlier_detection")); } else { // trigger .ml-config index mappings update createAnomalyDetectorJob(NEW_CLUSTER_JOB_ID); // assert that the mappings are updated IndexMappingTemplateAsserter.assertMlMappingsMatchTemplates(client()); } } private void createAnomalyDetectorJob(String jobId) throws IOException { String jobConfig = Strings.format(""" { "job_id": "%s", "analysis_config": { "bucket_span": "10m", "detectors": [{ "function": "metric", "field_name": "responsetime" }] }, "data_description": {} }""", jobId); Request putJobRequest = new Request("PUT", "/_ml/anomaly_detectors/" + jobId); putJobRequest.setJsonEntity(jobConfig); Response putJobResponse = client().performRequest(putJobRequest); assertThat(putJobResponse.getStatusLine().getStatusCode(), equalTo(200)); } @SuppressWarnings("unchecked") private Map<String, Object> getConfigIndexMappings() throws Exception { Request getIndexMappingsRequest = new Request("GET", ".ml-config/_mappings"); getIndexMappingsRequest.setOptions(expectVersionSpecificWarnings(v -> { final String systemIndexWarning = "this request accesses system indices: [.ml-config], but in a future major version, direct " + "access to system indices will be prevented by default"; v.current(systemIndexWarning); v.compatible(systemIndexWarning); })); Response getIndexMappingsResponse = client().performRequest(getIndexMappingsRequest); assertThat(getIndexMappingsResponse.getStatusLine().getStatusCode(), equalTo(200)); Map<String, Object> mappings = entityAsMap(getIndexMappingsResponse); mappings = (Map<String, Object>) XContentMapValues.extractValue(mappings, ".ml-config", "mappings"); if (mappings.containsKey("doc")) { mappings = (Map<String, Object>) XContentMapValues.extractValue(mappings, "doc"); } mappings = (Map<String, Object>) XContentMapValues.extractValue(mappings, "properties"); return mappings; } @SuppressWarnings("unchecked") private Map<String, Object> getDataFrameAnalysisMappings() throws Exception { Map<String, Object> mappings = getConfigIndexMappings(); mappings = (Map<String, Object>) XContentMapValues.extractValue(mappings, "analysis", "properties"); return mappings; } }
MlConfigIndexMappingsFullClusterRestartIT
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/resource/ResourceInfoInjectionFilter.java
{ "start": 476, "end": 1025 }
class ____ implements ContainerResponseFilter { @Context private ResourceInfo resourceInfo; @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { Method method = resourceInfo.getResourceMethod(); if (method == null) { responseContext.setStatus(responseContext.getStatus() * 2); } else { responseContext.setEntity(method.getName(), null, MediaType.TEXT_PLAIN_TYPE); } } }
ResourceInfoInjectionFilter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/generator/UUID2GeneratorUniqueIdentifierIdTest.java
{ "start": 1863, "end": 2182 }
class ____ { @Id @GenericGenerator(name = "uuid", strategy = "uuid2") @GeneratedValue(generator = "uuid") @Column(columnDefinition = "UNIQUEIDENTIFIER") UUID id; @ElementCollection @JoinTable(name = "foo_values") @Column(name = "foo_value") final Set<String> fooValues = new HashSet<>(); } }
FooEntity
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableMergeWithMaybe.java
{ "start": 1991, "end": 9876 }
class ____<T> extends AtomicInteger implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = -4592979584110982903L; final Subscriber<? super T> downstream; final AtomicReference<Subscription> mainSubscription; final OtherObserver<T> otherObserver; final AtomicThrowable errors; final AtomicLong requested; final int prefetch; final int limit; volatile SimplePlainQueue<T> queue; T singleItem; volatile boolean cancelled; volatile boolean mainDone; volatile int otherState; long emitted; int consumed; static final int OTHER_STATE_HAS_VALUE = 1; static final int OTHER_STATE_CONSUMED_OR_EMPTY = 2; MergeWithObserver(Subscriber<? super T> downstream) { this.downstream = downstream; this.mainSubscription = new AtomicReference<>(); this.otherObserver = new OtherObserver<>(this); this.errors = new AtomicThrowable(); this.requested = new AtomicLong(); this.prefetch = bufferSize(); this.limit = prefetch - (prefetch >> 2); } @Override public void onSubscribe(Subscription s) { SubscriptionHelper.setOnce(mainSubscription, s, prefetch); } @Override public void onNext(T t) { if (compareAndSet(0, 1)) { long e = emitted; if (requested.get() != e) { SimplePlainQueue<T> q = queue; if (q == null || q.isEmpty()) { emitted = e + 1; downstream.onNext(t); int c = consumed + 1; if (c == limit) { consumed = 0; mainSubscription.get().request(c); } else { consumed = c; } } else { q.offer(t); } } else { SimplePlainQueue<T> q = getOrCreateQueue(); q.offer(t); } if (decrementAndGet() == 0) { return; } } else { SimplePlainQueue<T> q = getOrCreateQueue(); q.offer(t); if (getAndIncrement() != 0) { return; } } drainLoop(); } @Override public void onError(Throwable ex) { if (errors.tryAddThrowableOrReport(ex)) { DisposableHelper.dispose(otherObserver); drain(); } } @Override public void onComplete() { mainDone = true; drain(); } @Override public void request(long n) { BackpressureHelper.add(requested, n); drain(); } @Override public void cancel() { cancelled = true; SubscriptionHelper.cancel(mainSubscription); DisposableHelper.dispose(otherObserver); errors.tryTerminateAndReport(); if (getAndIncrement() == 0) { queue = null; singleItem = null; } } void otherSuccess(T value) { if (compareAndSet(0, 1)) { long e = emitted; if (requested.get() != e) { emitted = e + 1; downstream.onNext(value); otherState = OTHER_STATE_CONSUMED_OR_EMPTY; } else { singleItem = value; otherState = OTHER_STATE_HAS_VALUE; if (decrementAndGet() == 0) { return; } } } else { singleItem = value; otherState = OTHER_STATE_HAS_VALUE; if (getAndIncrement() != 0) { return; } } drainLoop(); } void otherError(Throwable ex) { if (errors.tryAddThrowableOrReport(ex)) { SubscriptionHelper.cancel(mainSubscription); drain(); } } void otherComplete() { otherState = OTHER_STATE_CONSUMED_OR_EMPTY; drain(); } SimplePlainQueue<T> getOrCreateQueue() { SimplePlainQueue<T> q = queue; if (q == null) { q = new SpscArrayQueue<>(bufferSize()); queue = q; } return q; } void drain() { if (getAndIncrement() == 0) { drainLoop(); } } void drainLoop() { Subscriber<? super T> actual = this.downstream; int missed = 1; long e = emitted; int c = consumed; int lim = limit; for (;;) { long r = requested.get(); while (e != r) { if (cancelled) { singleItem = null; queue = null; return; } if (errors.get() != null) { singleItem = null; queue = null; errors.tryTerminateConsumer(downstream); return; } int os = otherState; if (os == OTHER_STATE_HAS_VALUE) { T v = singleItem; singleItem = null; otherState = OTHER_STATE_CONSUMED_OR_EMPTY; os = OTHER_STATE_CONSUMED_OR_EMPTY; actual.onNext(v); e++; continue; } boolean d = mainDone; SimplePlainQueue<T> q = queue; T v = q != null ? q.poll() : null; boolean empty = v == null; if (d && empty && os == OTHER_STATE_CONSUMED_OR_EMPTY) { queue = null; actual.onComplete(); return; } if (empty) { break; } actual.onNext(v); e++; if (++c == lim) { c = 0; mainSubscription.get().request(lim); } } if (e == r) { if (cancelled) { singleItem = null; queue = null; return; } if (errors.get() != null) { singleItem = null; queue = null; errors.tryTerminateConsumer(downstream); return; } boolean d = mainDone; SimplePlainQueue<T> q = queue; boolean empty = q == null || q.isEmpty(); if (d && empty && otherState == 2) { queue = null; actual.onComplete(); return; } } emitted = e; consumed = c; missed = addAndGet(-missed); if (missed == 0) { break; } } } static final
MergeWithObserver
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/architecture/AutoConfigurationChecker.java
{ "start": 1418, "end": 2467 }
class ____ { private final DescribedPredicate<JavaClass> isAutoConfiguration = ArchitectureRules.areRegularAutoConfiguration() .and(ArchitectureRules.areNotKotlinClasses()); EvaluationResult check(JavaClasses javaClasses) { AutoConfigurations autoConfigurations = new AutoConfigurations(); for (JavaClass javaClass : javaClasses) { if (isAutoConfigurationOrEnclosedInAutoConfiguration(javaClass)) { autoConfigurations.add(javaClass); } } return ArchitectureRules.shouldHaveNoPublicMembers().evaluate(autoConfigurations.getConfigurations()); } private boolean isAutoConfigurationOrEnclosedInAutoConfiguration(JavaClass javaClass) { if (this.isAutoConfiguration.test(javaClass)) { return true; } JavaClass enclosingClass = javaClass.getEnclosingClass().orElse(null); while (enclosingClass != null) { if (this.isAutoConfiguration.test(enclosingClass)) { return true; } enclosingClass = enclosingClass.getEnclosingClass().orElse(null); } return false; } private static final
AutoConfigurationChecker
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/form/FormWithConverterTest.java
{ "start": 1609, "end": 1875 }
class ____ { @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) public String hello(@FormParam("message") String message) { return message + "!"; } } public static
Resource
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/fielddata/plain/AbstractLeafOrdinalsFieldData.java
{ "start": 936, "end": 2043 }
class ____ implements LeafOrdinalsFieldData { private final ToScriptFieldFactory<SortedSetDocValues> toScriptFieldFactory; protected AbstractLeafOrdinalsFieldData(ToScriptFieldFactory<SortedSetDocValues> toScriptFieldFactory) { this.toScriptFieldFactory = toScriptFieldFactory; } @Override public final DocValuesScriptFieldFactory getScriptFieldFactory(String name) { return toScriptFieldFactory.getScriptFieldFactory(getOrdinalsValues(), name); } @Override public final SortedBinaryDocValues getBytesValues() { return FieldData.toString(getOrdinalsValues()); } public static LeafOrdinalsFieldData empty(ToScriptFieldFactory<SortedSetDocValues> toScriptFieldFactory) { return new AbstractLeafOrdinalsFieldData(toScriptFieldFactory) { @Override public long ramBytesUsed() { return 0; } @Override public SortedSetDocValues getOrdinalsValues() { return DocValues.emptySortedSet(); } }; } }
AbstractLeafOrdinalsFieldData
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/defaultbean/DefaultProducerFieldTest.java
{ "start": 1582, "end": 1873 }
class ____ { @Inject GreetingBean bean; @Inject Instance<Author> instance; String hello() { return bean.greet(); } Instance<Author> instance() { return instance; } } @Singleton static
Hello
java
quarkusio__quarkus
extensions/micrometer/deployment/src/test/java/io/quarkus/micrometer/deployment/binder/VertxEventBusMetricsTest.java
{ "start": 541, "end": 3065 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withConfigurationResource("test-logging.properties") .overrideConfigKey("quarkus.redis.devservices.enabled", "false") .withEmptyApplication(); final static SimpleMeterRegistry registry = new SimpleMeterRegistry(); @BeforeAll static void setRegistry() { Metrics.addRegistry(registry); } @AfterAll() static void removeRegistry() { Metrics.removeRegistry(registry); } @Inject Vertx vertx; private Search getMeter(String name, String address) { return registry.find(name).tags("address", address); } @Test void testEventBusMetrics() { var bus = vertx.eventBus(); bus.consumer("address").handler(m -> { // ignored }); bus.consumer("address").handler(m -> { // ignored }); bus.<String> consumer("rpc").handler(m -> m.reply(m.body().toUpperCase())); bus.send("address", "a"); bus.publish("address", "b"); String resp = bus.<String> requestAndAwait("rpc", "hello").body(); Assertions.assertEquals("HELLO", resp); Assertions.assertEquals(1, getMeter("eventBus.sent", "address").counter().count()); Assertions.assertEquals(1, getMeter("eventBus.sent", "rpc").counter().count()); Assertions.assertEquals(1, getMeter("eventBus.sent", "rpc").counter().getId().getTags().size()); Assertions.assertEquals(1, getMeter("eventBus.published", "address").counter().count()); Assertions.assertEquals(2, getMeter("eventBus.handlers", "address").gauge().value()); Assertions.assertEquals(1, getMeter("eventBus.handlers", "rpc").gauge().value()); Assertions.assertEquals(1, getMeter("eventBus.handlers", "rpc").gauge().getId().getTags().size()); Assertions.assertEquals(0, getMeter("eventBus.discarded", "address").gauge().value()); Assertions.assertEquals(0, getMeter("eventBus.discarded", "rpc").gauge().value()); Assertions.assertEquals(1, getMeter("eventBus.discarded", "rpc").gauge().getId().getTags().size()); Assertions.assertEquals(3, getMeter("eventBus.delivered", "address").gauge().value()); Assertions.assertEquals(1, getMeter("eventBus.delivered", "rpc").gauge().value()); Assertions.assertEquals(1, getMeter("eventBus.delivered", "rpc").gauge().getId().getTags().size()); } }
VertxEventBusMetricsTest
java
micronaut-projects__micronaut-core
http-client-core/src/main/java/io/micronaut/http/client/StreamingHttpClientFactoryResolver.java
{ "start": 882, "end": 1700 }
class ____ { private static volatile StreamingHttpClientFactory factory; static StreamingHttpClientFactory getFactory() { if (factory == null) { synchronized (StreamingHttpClientFactoryResolver.class) { // double check if (factory == null) { factory = resolveClientFactory(); } } } return factory; } private static StreamingHttpClientFactory resolveClientFactory() { final Iterator<StreamingHttpClientFactory> i = ServiceLoader.load(StreamingHttpClientFactory.class).iterator(); if (i.hasNext()) { return i.next(); } throw new IllegalStateException("No HttpClientFactory present on classpath, cannot create client"); } }
StreamingHttpClientFactoryResolver
java
redisson__redisson
redisson/src/main/java/org/redisson/api/CacheAsync.java
{ "start": 877, "end": 991 }
interface ____ JCache * * @author Nikita Koksharov * * @param <K> key type * @param <V> value type */ public
for
java
alibaba__nacos
api/src/test/java/com/alibaba/nacos/api/remote/request/RequestTest.java
{ "start": 952, "end": 1908 }
class ____ { @BeforeEach void setUp() throws Exception { } @Test void testHeader() { MockRequest request = new MockRequest(); assertTrue(request.getHeaders().isEmpty()); assertNull(request.getHeader("clientIp")); assertEquals("1.1.1.1", request.getHeader("clientIp", "1.1.1.1")); request.putHeader("clientIp", "2.2.2.2"); assertEquals(1, request.getHeaders().size()); assertEquals("2.2.2.2", request.getHeader("clientIp")); assertEquals("2.2.2.2", request.getHeader("clientIp", "1.1.1.1")); request.putAllHeader(Collections.singletonMap("connectionId", "aaa")); assertEquals(2, request.getHeaders().size()); request.putAllHeader(null); assertEquals(2, request.getHeaders().size()); request.clearHeaders(); assertTrue(request.getHeaders().isEmpty()); } private static
RequestTest
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/logging/LoggingSystemPropertiesTests.java
{ "start": 1546, "end": 9937 }
class ____ { private Set<Object> systemPropertyNames; @BeforeEach void captureSystemPropertyNames() { for (LoggingSystemProperty property : LoggingSystemProperty.values()) { System.getProperties().remove(property.getEnvironmentVariableName()); } System.getProperties().remove("LOGGED_APPLICATION_NAME"); this.systemPropertyNames = new HashSet<>(System.getProperties().keySet()); } @AfterEach void restoreSystemProperties() { System.getProperties().keySet().retainAll(this.systemPropertyNames); } @Test void pidIsSet() { new LoggingSystemProperties(new MockEnvironment()).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.PID)).isNotNull(); } @Test void consoleLogPatternIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.console", "console pattern")) .apply(null); assertThat(getSystemProperty(LoggingSystemProperty.CONSOLE_PATTERN)).isEqualTo("console pattern"); } @Test void consoleCharsetWhenNoPropertyUsesCharsetDefault() { LoggingSystemProperties loggingSystemProperties = spy(new LoggingSystemProperties(new MockEnvironment())); given(loggingSystemProperties.getConsole()).willReturn(null); loggingSystemProperties.apply(null); assertThat(getSystemProperty(LoggingSystemProperty.CONSOLE_CHARSET)).isEqualTo(Charset.defaultCharset().name()); } @Test void consoleCharsetWhenNoPropertyUsesSystemConsoleCharsetWhenAvailable() { LoggingSystemProperties loggingSystemProperties = spy(new LoggingSystemProperties(new MockEnvironment())); Console console = mock(Console.class); given(console.charset()).willReturn(StandardCharsets.UTF_16BE); given(loggingSystemProperties.getConsole()).willReturn(console); loggingSystemProperties.apply(null); assertThat(getSystemProperty(LoggingSystemProperty.CONSOLE_CHARSET)) .isEqualTo(StandardCharsets.UTF_16BE.name()); } @Test void consoleCharsetIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.charset.console", "UTF-16")) .apply(null); assertThat(getSystemProperty(LoggingSystemProperty.CONSOLE_CHARSET)).isEqualTo("UTF-16"); } @Test void fileLogPatternIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.pattern.file", "file pattern")) .apply(null); assertThat(getSystemProperty(LoggingSystemProperty.FILE_PATTERN)).isEqualTo("file pattern"); } @Test void fileCharsetWhenNoPropertyUsesUtf8() { new LoggingSystemProperties(new MockEnvironment()).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.FILE_CHARSET)).isEqualTo("UTF-8"); } @Test void fileCharsetIsSet() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.charset.file", "UTF-16")).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.FILE_CHARSET)).isEqualTo("UTF-16"); } @Test void consoleLogPatternCanReferencePid() { new LoggingSystemProperties(environment("logging.pattern.console", "${PID:unknown}")).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.CONSOLE_PATTERN)).matches("[0-9]+"); } @Test void fileLogPatternCanReferencePid() { new LoggingSystemProperties(environment("logging.pattern.file", "${PID:unknown}")).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.FILE_PATTERN)).matches("[0-9]+"); } private String getSystemProperty(LoggingSystemProperty property) { return System.getProperty(property.getEnvironmentVariableName()); } @Test void correlationPatternIsSet() { new LoggingSystemProperties( new MockEnvironment().withProperty("logging.pattern.correlation", "correlation pattern")) .apply(null); assertThat(System.getProperty(LoggingSystemProperty.CORRELATION_PATTERN.getEnvironmentVariableName())) .isEqualTo("correlation pattern"); } @Test void defaultValueResolverIsUsed() { MockEnvironment environment = new MockEnvironment(); Map<String, String> defaultValues = Map .of(LoggingSystemProperty.CORRELATION_PATTERN.getApplicationPropertyName(), "default correlation pattern"); new LoggingSystemProperties(environment, defaultValues::get, null).apply(null); assertThat(System.getProperty(LoggingSystemProperty.CORRELATION_PATTERN.getEnvironmentVariableName())) .isEqualTo("default correlation pattern"); } @Test void loggedApplicationNameWhenHasApplicationName() { new LoggingSystemProperties(new MockEnvironment().withProperty("spring.application.name", "test")).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_NAME)).isEqualTo("test"); } @Test void loggedApplicationNameWhenHasNoApplicationName() { new LoggingSystemProperties(new MockEnvironment()).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_NAME)).isNull(); } @Test void loggedApplicationNameWhenApplicationNameLoggingDisabled() { new LoggingSystemProperties(new MockEnvironment().withProperty("spring.application.name", "test") .withProperty("logging.include-application-name", "false")).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_NAME)).isNull(); } @Test void legacyLoggedApplicationNameWhenHasApplicationName() { new LoggingSystemProperties(new MockEnvironment().withProperty("spring.application.name", "test")).apply(null); assertThat(System.getProperty("LOGGED_APPLICATION_NAME")).isEqualTo("[test] "); } @Test void applicationGroupWhenHasApplicationGroup() { new LoggingSystemProperties(new MockEnvironment().withProperty("spring.application.group", "test")).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_GROUP)).isEqualTo("test"); } @Test void applicationGroupWhenHasNoApplicationGroup() { new LoggingSystemProperties(new MockEnvironment()).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_GROUP)).isNull(); } @Test void applicationGroupWhenApplicationGroupLoggingDisabled() { new LoggingSystemProperties(new MockEnvironment().withProperty("spring.application.group", "test") .withProperty("logging.include-application-group", "false")).apply(null); assertThat(getSystemProperty(LoggingSystemProperty.APPLICATION_GROUP)).isNull(); } @Test void shouldSupportFalseConsoleThreshold() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.threshold.console", "false")) .apply(null); assertThat(System.getProperty(LoggingSystemProperty.CONSOLE_THRESHOLD.getEnvironmentVariableName())) .isEqualTo("OFF"); } @Test void shouldSupportFalseFileThreshold() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.threshold.file", "false")).apply(null); assertThat(System.getProperty(LoggingSystemProperty.FILE_THRESHOLD.getEnvironmentVariableName())) .isEqualTo("OFF"); } @Test void shouldSetFileStructuredLogging() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.structured.format.file", "ecs")) .apply(null); assertThat(System.getProperty(LoggingSystemProperty.FILE_STRUCTURED_FORMAT.getEnvironmentVariableName())) .isEqualTo("ecs"); } @Test void shouldSetConsoleStructuredLogging() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.structured.format.console", "ecs")) .apply(null); assertThat(System.getProperty(LoggingSystemProperty.CONSOLE_STRUCTURED_FORMAT.getEnvironmentVariableName())) .isEqualTo("ecs"); } @Test void shouldSetConsoleLevelThresholdToOffWhenConsoleLoggingDisabled() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.console.enabled", "false")).apply(null); assertThat(System.getProperty(LoggingSystemProperty.CONSOLE_THRESHOLD.getEnvironmentVariableName())) .isEqualTo("OFF"); } @Test void shouldNotChangeConsoleLevelThresholdWhenConsoleLoggingEnabled() { new LoggingSystemProperties(new MockEnvironment().withProperty("logging.console.enabled", "true") .withProperty("logging.threshold.console", "TRACE")).apply(null); assertThat(System.getProperty(LoggingSystemProperty.CONSOLE_THRESHOLD.getEnvironmentVariableName())) .isEqualTo("TRACE"); } private Environment environment(String key, Object value) { StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addLast(new MapPropertySource("test", Collections.singletonMap(key, value))); return environment; } }
LoggingSystemPropertiesTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 57809, "end": 58253 }
class ____ { <@ImmutableTypeParameter T> A<T> k() { return new A<>(); } } """) .doTest(); } @Test public void immutableTypeParameterInstantiation_genericParamExtendsMutable_violation() { compilationHelper .addSourceLines( "MyMutableType.java", """ import com.google.errorprone.annotations.Immutable;
Test
java
alibaba__nacos
naming/src/main/java/com/alibaba/nacos/naming/push/v2/task/PushExecuteTask.java
{ "start": 3802, "end": 8100 }
class ____ implements NamingPushCallback { private final String clientId; private final Subscriber subscriber; private final ServiceInfo serviceInfo; /** * Record the push task execute start time. */ private final long executeStartTime; private final boolean isPushToAll; /** * The actual pushed service info, the host list of service info may be changed by selector. Detail see * implement of {@link com.alibaba.nacos.naming.push.v2.executor.PushExecutor}. */ private ServiceInfo actualServiceInfo; private ServicePushCallback(String clientId, Subscriber subscriber, ServiceInfo serviceInfo, boolean isPushToAll) { this.clientId = clientId; this.subscriber = subscriber; this.serviceInfo = serviceInfo; this.isPushToAll = isPushToAll; this.executeStartTime = System.currentTimeMillis(); this.actualServiceInfo = serviceInfo; } @Override public long getTimeout() { return PushConfig.getInstance().getPushTaskTimeout(); } @Override public void onSuccess() { long pushFinishTime = System.currentTimeMillis(); long pushCostTimeForNetWork = pushFinishTime - executeStartTime; long pushCostTimeForAll = pushFinishTime - delayTask.getLastProcessTime(); long serviceLevelAgreementTime = pushFinishTime - service.getLastUpdatedTime(); if (isPushToAll) { Loggers.PUSH .info("[PUSH-SUCC] {}ms, all delay time {}ms, SLA {}ms, {}, originalSize={}, DataSize={}, target={}", pushCostTimeForNetWork, pushCostTimeForAll, serviceLevelAgreementTime, service, serviceInfo.getHosts().size(), actualServiceInfo.getHosts().size(), subscriber.getIp()); } else { Loggers.PUSH .info("[PUSH-SUCC] {}ms, all delay time {}ms for subscriber {}, {}, originalSize={}, DataSize={}", pushCostTimeForNetWork, pushCostTimeForAll, subscriber.getIp(), service, serviceInfo.getHosts().size(), actualServiceInfo.getHosts().size()); } PushResult result = PushResult .pushSuccess(service, clientId, actualServiceInfo, subscriber, pushCostTimeForNetWork, pushCostTimeForAll, serviceLevelAgreementTime, isPushToAll); NotifyCenter.publishEvent(getPushServiceTraceEvent(pushFinishTime, result)); PushResultHookHolder.getInstance().pushSuccess(result); } @Override public void onFail(Throwable e) { long pushCostTime = System.currentTimeMillis() - executeStartTime; Loggers.PUSH.error("[PUSH-FAIL] {}ms, {}, reason={}, target={}", pushCostTime, service, e.getMessage(), subscriber.getIp()); if (!(e instanceof NoRequiredRetryException)) { Loggers.PUSH.error("Reason detail: ", e); delayTaskEngine.addTask(service, new PushDelayTask(service, PushConfig.getInstance().getPushTaskRetryDelay(), clientId)); } PushResult result = PushResult .pushFailed(service, clientId, actualServiceInfo, subscriber, pushCostTime, e, isPushToAll); PushResultHookHolder.getInstance().pushFailed(result); } public void setActualServiceInfo(ServiceInfo actualServiceInfo) { this.actualServiceInfo = actualServiceInfo; } private PushServiceTraceEvent getPushServiceTraceEvent(long eventTime, PushResult result) { return new PushServiceTraceEvent(eventTime, result.getNetworkCost(), result.getAllCost(), result.getSla(), result.getSubscriber().getIp(), result.getService().getNamespace(), result.getService().getGroup(), result.getService().getName(), result.getData().getHosts().size()); } } }
ServicePushCallback
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/GetLocalizationStatusesRequest.java
{ "start": 1512, "end": 2356 }
class ____ { @Public @Unstable public static GetLocalizationStatusesRequest newInstance( List<ContainerId> containerIds) { GetLocalizationStatusesRequest request = Records.newRecord(GetLocalizationStatusesRequest.class); request.setContainerIds(containerIds); return request; } /** * Get the list of container IDs of the containers for which the localization * statuses are needed. * * @return the list of container IDs. */ @Public @Unstable public abstract List<ContainerId> getContainerIds(); /** * Sets the list of container IDs of containers for which the localization * statuses are needed. * @param containerIds the list of container IDs. */ @Public @Unstable public abstract void setContainerIds(List<ContainerId> containerIds); }
GetLocalizationStatusesRequest
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/config/remote/request/ConfigRemoveRequest.java
{ "start": 827, "end": 1551 }
class ____ extends AbstractConfigRequest { String tag; public ConfigRemoveRequest() { } public ConfigRemoveRequest(String dataId, String group, String tenant, String tag) { super.setDataId(dataId); super.setGroup(group); super.setTenant(tenant); this.tag = tag; } /** * Getter method for property <tt>tag</tt>. * * @return property value of tag */ public String getTag() { return tag; } /** * Setter method for property <tt>tag</tt>. * * @param tag value to be assigned to property tag */ public void setTag(String tag) { this.tag = tag; } }
ConfigRemoveRequest
java
redisson__redisson
redisson-mybatis/src/main/java/org/redisson/mybatis/RedissonCache.java
{ "start": 1044, "end": 3243 }
class ____ implements Cache { private String id; private RMapCache<Object, Object> mapCache; private long timeToLive; private long maxIdleTime; private int maxSize; public RedissonCache(String id) { this.id = id; } @Override public String getId() { return id; } @Override public void putObject(Object o, Object o1) { check(); mapCache.fastPut(o, o1, timeToLive, TimeUnit.MILLISECONDS, maxIdleTime, TimeUnit.MILLISECONDS); } @Override public Object getObject(Object o) { check(); if (maxIdleTime == 0 && maxSize == 0) { return mapCache.getWithTTLOnly(o); } return mapCache.get(o); } @Override public Object removeObject(Object o) { check(); return mapCache.remove(o); } @Override public void clear() { check(); mapCache.clear(); } @Override public int getSize() { check(); return mapCache.size(); } public void setTimeToLive(long timeToLive) { this.timeToLive = timeToLive; } public void setMaxIdleTime(long maxIdleTime) { this.maxIdleTime = maxIdleTime; } public void setMaxSize(int maxSize) { this.maxSize = maxSize; } public ReadWriteLock getReadWriteLock() { return null; } public void setRedissonConfig(String config) { Config cfg; try { InputStream is = getClass().getClassLoader().getResourceAsStream(config); cfg = Config.fromYAML(is); } catch (IOException e) { throw new IllegalArgumentException("Can't parse config", e); } RedissonClient redisson = Redisson.create(cfg); mapCache = getMapCache(id, redisson); if (maxSize > 0) { mapCache.setMaxSize(maxSize); } } protected RMapCache<Object, Object> getMapCache(String id, RedissonClient redisson) { return redisson.getMapCache(id); } private void check() { if (mapCache == null) { throw new IllegalStateException("Redisson config is not defined"); } } }
RedissonCache
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/idbag/IdBagTest.java
{ "start": 753, "end": 3103 }
class ____ { @Test public void testUpdateIdBag(SessionFactoryScope scope) { scope.inTransaction( s -> { User gavin = new User( "gavin" ); Group admins = new Group( "admins" ); Group plebs = new Group( "plebs" ); Group moderators = new Group( "moderators" ); Group banned = new Group( "banned" ); gavin.getGroups().add( plebs ); //gavin.getGroups().add(moderators); s.persist( gavin ); s.persist( plebs ); s.persist( admins ); s.persist( moderators ); s.persist( banned ); } ); scope.inTransaction( s -> { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery<User> criteria = criteriaBuilder.createQuery( User.class ); criteria.from( User.class ); User gavin = s.createQuery( criteria ).uniqueResult(); // User gavin = (User) s.createCriteria( User.class ).uniqueResult(); Group admins = s.getReference( Group.class, "admins" ); Group plebs = s.getReference( Group.class, "plebs" ); Group banned = s.getReference( Group.class, "banned" ); gavin.getGroups().add( admins ); gavin.getGroups().remove( plebs ); //gavin.getGroups().add(banned); s.remove( plebs ); s.remove( banned ); s.remove( s.getReference( Group.class, "moderators" ) ); s.remove( admins ); s.remove( gavin ); } ); } @Test public void testJoin(SessionFactoryScope scope) { scope.inTransaction( session -> { User gavin = new User( "gavin" ); Group admins = new Group( "admins" ); Group plebs = new Group( "plebs" ); gavin.getGroups().add( plebs ); gavin.getGroups().add( admins ); session.persist( gavin ); session.persist( plebs ); session.persist( admins ); List l = session.createQuery( "from User u join u.groups g", User.class ).list(); assertEquals( 1, l.size() ); session.clear(); gavin = (User) session.createQuery( "from User u join fetch u.groups" ).uniqueResult(); assertTrue( Hibernate.isInitialized( gavin.getGroups() ) ); assertEquals( 2, gavin.getGroups().size() ); assertEquals( "admins", ( (Group) gavin.getGroups().get( 0 ) ).getName() ); session.remove( gavin.getGroups().get( 0 ) ); session.remove( gavin.getGroups().get( 1 ) ); session.remove( gavin ); } ); } }
IdBagTest
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/expression/predicate/operator/comparison/StringComparisons.java
{ "start": 463, "end": 1120 }
class ____ { private StringComparisons() {} static Boolean insensitiveEquals(Object l, Object r) { if (l instanceof String && r instanceof String) { return ((String) l).compareToIgnoreCase((String) r) == 0; } if (l == null || r == null) { return null; } throw new EqlIllegalArgumentException("Insensitive comparison can be applied only on strings"); } static Boolean insensitiveNotEquals(Object l, Object r) { Boolean equal = insensitiveEquals(l, r); return equal == null ? null : (equal == Boolean.TRUE ? Boolean.FALSE : Boolean.TRUE); } }
StringComparisons
java
apache__logging-log4j2
log4j-core-test/src/main/java/org/apache/logging/log4j/core/test/junit/CleanFolders.java
{ "start": 1473, "end": 4161 }
class ____ extends SimpleFileVisitor<Path> { private final PrintStream printStream; public DeleteAllFileVisitor(final PrintStream logger) { this.printStream = logger; } @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException { printf("%s Deleting directory %s\n", CLEANER_MARKER, dir); final boolean deleted = Files.deleteIfExists(dir); printf("%s Deleted directory %s: %s\n", CLEANER_MARKER, dir, deleted); return FileVisitResult.CONTINUE; } protected void printf(final String format, final Object... args) { if (printStream != null) { printStream.printf(format, args); } } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { printf("%s Deleting file %s with %s\n", CLEANER_MARKER, file, attrs); final boolean deleted = Files.deleteIfExists(file); printf("%s Deleted file %s: %s\n", CLEANER_MARKER, file, deleted); return FileVisitResult.CONTINUE; } } private static final int MAX_TRIES = 10; public CleanFolders(final boolean before, final boolean after, final int maxTries, final File... files) { super(before, after, maxTries, null, files); } public CleanFolders(final boolean before, final boolean after, final int maxTries, final Path... paths) { super(before, after, maxTries, null, paths); } public CleanFolders(final boolean before, final boolean after, final int maxTries, final String... fileNames) { super(before, after, maxTries, null, fileNames); } public CleanFolders(final File... folders) { super(true, true, MAX_TRIES, null, folders); } public CleanFolders(final Path... paths) { super(true, true, MAX_TRIES, null, paths); } public CleanFolders(final PrintStream logger, final File... folders) { super(true, true, MAX_TRIES, logger, folders); } public CleanFolders(final String... folderNames) { super(true, true, MAX_TRIES, null, folderNames); } @Override protected boolean clean(final Path path, final int tryIndex) throws IOException { cleanFolder(path, tryIndex); return true; } private void cleanFolder(final Path folder, final int tryIndex) throws IOException { if (Files.exists(folder) && Files.isDirectory(folder)) { Files.walkFileTree(folder, new DeleteAllFileVisitor(getPrintStream())); } } }
DeleteAllFileVisitor
java
apache__camel
dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/download/DependencyDownloader.java
{ "start": 1146, "end": 7768 }
interface ____ extends CamelContextAware, StaticService { /** * Classloader able to load from downloaded dependencies. */ ClassLoader getClassLoader(); /** * Sets the classloader to use that will be able to load from downloaded dependencies */ void setClassLoader(ClassLoader classLoader); /** * Adds a listener to capture download activity */ void addDownloadListener(DownloadListener downloadListener); /** * Adds a listener to capture download activity */ void addArtifactDownloadListener(ArtifactDownloadListener downloadListener); String getRepositories(); /** * Additional maven repositories for download on-demand (Use commas to separate multiple repositories). */ void setRepositories(String repositories); /** * Whether downloading from remote Maven repositories is enabled */ void setDownload(boolean download); /** * Whether downloading from remote Maven repositories is enabled */ boolean isDownload(); boolean isFresh(); /** * Make sure we use fresh (i.e. non-cached) resources. */ void setFresh(boolean fresh); String getMavenSettings(); /** * Configure location of Maven settings.xml file */ void setMavenSettings(String mavenSettings); String getMavenSettingsSecurity(); /** * Configure location of Maven settings-security.xml file */ void setMavenSettingsSecurity(String mavenSettingsSecurity); /** * Whether downloading JARs from Maven Central repository is enabled */ boolean isMavenCentralEnabled(); /** * Whether downloading JARs from Maven Central repository is enabled */ void setMavenCentralEnabled(boolean mavenCentralEnabled); /** * Whether downloading JARs from ASF Maven Snapshot repository is enabled */ boolean isMavenApacheSnapshotEnabled(); /** * Whether downloading JARs from ASF Maven Snapshot repository is enabled */ void setMavenApacheSnapshotEnabled(boolean mavenApacheSnapshotEnabled); /** * Downloads the dependency incl transitive dependencies * * @param parentGav maven parent GAV * @param groupId maven group id * @param artifactId maven artifact id * @param version maven version */ void downloadDependencyWithParent(String parentGav, String groupId, String artifactId, String version); /** * Downloads the dependency incl transitive dependencies * * @param groupId maven group id * @param artifactId maven artifact id * @param version maven version */ void downloadDependency(String groupId, String artifactId, String version); /** * Downloads the dependency incl transitive dependencies * * @param groupId maven group id * @param artifactId maven artifact id * @param version maven version * @param extraRepos additional remote maven repositories to use when downloading */ void downloadDependency(String groupId, String artifactId, String version, String extraRepos); /** * Downloads the dependency * * @param groupId maven group id * @param artifactId maven artifact id * @param version maven version * @param transitively whether to include transitive dependencies */ void downloadDependency(String groupId, String artifactId, String version, boolean transitively); /** * Downloads as hidden dependency that are not captured as a requirement * * @param groupId maven group id * @param artifactId maven artifact id * @param version maven version */ void downloadHiddenDependency(String groupId, String artifactId, String version); /** * Downloads a single maven artifact (no transitive dependencies) * * @param groupId maven group id * @param artifactId maven artifact id * @param version maven version * @return the artifact, or null if none found */ MavenArtifact downloadArtifact(String groupId, String artifactId, String version); /** * Downloads maven artifact (can also include transitive dependencies). * * @param groupId maven group id * @param artifactId maven artifact id * @param version maven version * @param transitively whether to include transitive dependencies * @return the artifacts, or null if none found */ List<MavenArtifact> downloadArtifacts(String groupId, String artifactId, String version, boolean transitively); /** * Resolves the available versions for the given maven artifact * * @param groupId maven group id * @param artifactId maven artifact id * @param minimumVersion optional minimum version to avoid resolving too old releases * @param repo to use specific maven repository instead of maven central (used if repo is {@code null}) * @return list of versions of the given artifact (0=camel-core version, 1=runtime version, such as * spring-boot or quarkus) */ List<String[]> resolveAvailableVersions(String groupId, String artifactId, String minimumVersion, String repo); /** * Checks whether the dependency is already on the classpath * * @param groupId maven group id * @param artifactId maven artifact id * @param version maven version * @return true if already on classpath, false if not. */ boolean alreadyOnClasspath(String groupId, String artifactId, String version); /** * When a kamelet is being loaded * * @param name the kamelet name */ void onLoadingKamelet(String name); /** * Gets download record for a given artifact * * @return download record (if any) or <tt>null</tt> if artifact was not downloaded, but could have been resolved * from local disk */ DownloadRecord getDownloadState(String groupId, String artifactId, String version); /** * Gets the records for the downloaded artifacts */ Collection<DownloadRecord> downloadRecords(); /** * Gets the {@link RepositoryResolver} */ RepositoryResolver getRepositoryResolver(); /** * Gets the {@link VersionResolver} */ VersionResolver getVersionResolver(); /** * Set {@link VersionResolver} */ void setVersionResolver(VersionResolver versionResolver); }
DependencyDownloader
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/comparator/InstanceComparator.java
{ "start": 1543, "end": 2426 }
class ____<T> implements Comparator<T> { private final Class<?>[] instanceOrder; /** * Create a new {@link InstanceComparator} instance. * @param instanceOrder the ordered list of classes that should be used when comparing * objects. Classes earlier in the list will be given a higher priority. */ public InstanceComparator(Class<?>... instanceOrder) { Assert.notNull(instanceOrder, "'instanceOrder' array must not be null"); this.instanceOrder = instanceOrder; } @Override public int compare(T o1, T o2) { int i1 = getOrder(o1); int i2 = getOrder(o2); return (Integer.compare(i1, i2)); } private int getOrder(@Nullable T object) { if (object != null) { for (int i = 0; i < this.instanceOrder.length; i++) { if (this.instanceOrder[i].isInstance(object)) { return i; } } } return this.instanceOrder.length; } }
InstanceComparator
java
apache__flink
flink-table/flink-sql-gateway-api/src/main/java/org/apache/flink/table/gateway/api/session/SessionEnvironment.java
{ "start": 8582, "end": 8658 }
interface ____ to create {@link Catalog}. */ @PublicEvolving public
used
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/ingest/DropProcessor.java
{ "start": 1178, "end": 1582 }
class ____ implements Processor.Factory { @Override public Processor create( final Map<String, Processor.Factory> processorFactories, final String tag, final String description, final Map<String, Object> config, final ProjectId projectId ) { return new DropProcessor(tag, description); } } }
Factory
java
google__dagger
javatests/artifacts/hilt-android/simple/app/src/main/java/dagger/hilt/android/simple/SimpleActivity.java
{ "start": 1084, "end": 1844 }
class ____ extends AppCompatActivity { private static final String TAG = SimpleActivity.class.getSimpleName(); @Inject @UserName String userName; @Inject @Model String model; @Inject Thing thing; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "Injected with userName and model: " + userName + ", " + model); setContentView(R.layout.activity_main); ((TextView) findViewById(R.id.greeting)) .setText(getResources().getString(R.string.welcome, userName, model)); Button featureButton = (Button) findViewById(R.id.goto_feature); featureButton.setOnClickListener( view -> startActivity(new Intent(this, FeatureActivity.class))); } }
SimpleActivity
java
google__dagger
javatests/dagger/functional/producers/monitoring/ThreadMonitoredComponent.java
{ "start": 974, "end": 1086 }
interface ____ { @EntryPoint ListenableFuture<ThreadAccumulator> threadAccumulator(); }
ThreadMonitoredComponent
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableZip.java
{ "start": 1195, "end": 2940 }
class ____<T, R> extends Flowable<R> { final Publisher<? extends T>[] sources; final Iterable<? extends Publisher<? extends T>> sourcesIterable; final Function<? super Object[], ? extends R> zipper; final int bufferSize; final boolean delayError; public FlowableZip(Publisher<? extends T>[] sources, Iterable<? extends Publisher<? extends T>> sourcesIterable, Function<? super Object[], ? extends R> zipper, int bufferSize, boolean delayError) { this.sources = sources; this.sourcesIterable = sourcesIterable; this.zipper = zipper; this.bufferSize = bufferSize; this.delayError = delayError; } @Override @SuppressWarnings("unchecked") public void subscribeActual(Subscriber<? super R> s) { Publisher<? extends T>[] sources = this.sources; int count = 0; if (sources == null) { sources = new Publisher[8]; for (Publisher<? extends T> p : sourcesIterable) { if (count == sources.length) { Publisher<? extends T>[] b = new Publisher[count + (count >> 2)]; System.arraycopy(sources, 0, b, 0, count); sources = b; } sources[count++] = p; } } else { count = sources.length; } if (count == 0) { EmptySubscription.complete(s); return; } ZipCoordinator<T, R> coordinator = new ZipCoordinator<>(s, zipper, count, bufferSize, delayError); s.onSubscribe(coordinator); coordinator.subscribe(sources, count); } static final
FlowableZip
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/exceptionpolicy/CustomExceptionPolicyStrategyTest.java
{ "start": 2838, "end": 2997 }
class ____ because * of its cause. Whereas when reversing the order to check, MyUserException is matched to its superclass * IllegalStateException.
policy
java
spring-projects__spring-boot
module/spring-boot-cache/src/test/java/org/springframework/boot/cache/autoconfigure/actuate/endpoint/CachesEndpointAutoConfigurationTests.java
{ "start": 1384, "end": 3188 }
class ____ { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CachesEndpointAutoConfiguration.class)); @Test void runShouldHaveEndpointBean() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) .withPropertyValues("management.endpoints.web.exposure.include=caches") .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); } @Test void runWithoutCacheManagerShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoints.web.exposure.include=caches") .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class)); } @Test void runWhenNotExposedShouldNotHaveEndpointBean() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); } @Test void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.caches.enabled:false") .withPropertyValues("management.endpoints.web.exposure.include=*") .withBean(CacheManager.class, () -> mock(CacheManager.class)) .run((context) -> assertThat(context).doesNotHaveBean(CachesEndpoint.class)); } @Test void runWhenOnlyExposedOverJmxShouldHaveEndpointBeanWithoutWebExtension() { this.contextRunner.withBean(CacheManager.class, () -> mock(CacheManager.class)) .withPropertyValues("management.endpoints.web.exposure.include=info", "spring.jmx.enabled=true", "management.endpoints.jmx.exposure.include=caches") .run((context) -> assertThat(context).hasSingleBean(CachesEndpoint.class) .doesNotHaveBean(CachesEndpointWebExtension.class)); } }
CachesEndpointAutoConfigurationTests
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/score/DecayTests.java
{ "start": 1756, "end": 57429 }
class ____ extends AbstractScalarFunctionTestCase { public DecayTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) { this.testCase = testCaseSupplier.get(); } @ParametersFactory public static Iterable<Object[]> parameters() { List<TestCaseSupplier> testCaseSuppliers = new ArrayList<>(); // Int Linear testCaseSuppliers.addAll(intTestCase(0, 0, 10, 5, 0.5, "linear", 1.0)); testCaseSuppliers.addAll(intTestCase(10, 0, 10, 5, 0.5, "linear", 0.75)); testCaseSuppliers.addAll(intTestCase(50, 5, 100, 10, 0.25, "linear", 0.7375)); testCaseSuppliers.addAll(intTestCase(100, 17, 156, 23, 0.123, "linear", 0.6626923076923077)); testCaseSuppliers.addAll(intTestCase(2500, 0, 10, 0, 0.5, "linear", 0.0)); // Int Exponential testCaseSuppliers.addAll(intTestCase(0, 0, 10, 5, 0.5, "exp", 1.0)); testCaseSuppliers.addAll(intTestCase(10, 0, 10, 5, 0.5, "exp", 0.7071067811865475)); testCaseSuppliers.addAll(intTestCase(50, 5, 100, 10, 0.25, "exp", 0.6155722066724582)); testCaseSuppliers.addAll(intTestCase(100, 17, 156, 23, 0.123, "exp", 0.4466460570185927)); testCaseSuppliers.addAll(intTestCase(2500, 0, 10, 0, 0.5, "exp", 5.527147875260539E-76)); // Int Gaussian testCaseSuppliers.addAll(intTestCase(0, 0, 10, 5, 0.5, "gauss", 1.0)); testCaseSuppliers.addAll(intTestCase(10, 0, 10, 5, 0.5, "gauss", 0.8408964152537146)); testCaseSuppliers.addAll(intTestCase(50, 5, 100, 10, 0.25, "gauss", 0.8438157961300179)); testCaseSuppliers.addAll(intTestCase(100, 17, 156, 23, 0.123, "gauss", 0.7334501109633149)); testCaseSuppliers.addAll(intTestCase(2500, 0, 10, 0, 0.5, "gauss", 0.0)); // Int defaults testCaseSuppliers.addAll(intTestCase(10, 0, 10, null, null, null, 0.5)); // Int random testCaseSuppliers.addAll(intRandomTestCases()); // Long Linear testCaseSuppliers.addAll(longTestCase(0L, 10L, 10000000L, 200L, 0.33, "linear", 1.0)); testCaseSuppliers.addAll(longTestCase(10L, 10L, 10000000L, 200L, 0.33, "linear", 1.0)); testCaseSuppliers.addAll(longTestCase(50000L, 10L, 10000000L, 200L, 0.33, "linear", 0.99666407)); testCaseSuppliers.addAll(longTestCase(300000L, 10L, 10000000L, 200L, 0.33, "linear", 0.97991407)); testCaseSuppliers.addAll(longTestCase(123456789112123L, 10L, 10000000L, 200L, 0.33, "linear", 0.0)); // Long Exponential testCaseSuppliers.addAll(longTestCase(0L, 10L, 10000000L, 200L, 0.33, "exp", 1.0)); testCaseSuppliers.addAll(longTestCase(10L, 10L, 10000000L, 200L, 0.33, "exp", 1.0)); testCaseSuppliers.addAll(longTestCase(50000L, 10L, 10000000L, 200L, 0.33, "exp", 0.9944951761701727)); testCaseSuppliers.addAll(longTestCase(300000L, 10L, 10000000L, 200L, 0.33, "exp", 0.9673096701204178)); testCaseSuppliers.addAll(longTestCase(123456789112123L, 10L, 10000000L, 200L, 0.33, "exp", 0.0)); // Long Gaussian testCaseSuppliers.addAll(longTestCase(0L, 10L, 10000000L, 200L, 0.33, "gauss", 1.0)); testCaseSuppliers.addAll(longTestCase(10L, 10L, 10000000L, 200L, 0.33, "gauss", 1.0)); testCaseSuppliers.addAll(longTestCase(50000L, 10L, 10000000L, 200L, 0.33, "gauss", 0.999972516142306)); testCaseSuppliers.addAll(longTestCase(300000L, 10L, 10000000L, 200L, 0.33, "gauss", 0.9990040963055015)); testCaseSuppliers.addAll(longTestCase(123456789112123L, 10L, 10000000L, 200L, 0.33, "gauss", 0.0)); // Long defaults testCaseSuppliers.addAll(longTestCase(10L, 0L, 10L, null, null, null, 0.5)); // Long random testCaseSuppliers.addAll(longRandomTestCases()); // Double Linear testCaseSuppliers.addAll(doubleTestCase(0.0, 10.0, 10000000.0, 200.0, 0.25, "linear", 1.0)); testCaseSuppliers.addAll(doubleTestCase(10.0, 10.0, 10000000.0, 200.0, 0.25, "linear", 1.0)); testCaseSuppliers.addAll(doubleTestCase(50000.0, 10.0, 10000000.0, 200.0, 0.25, "linear", 0.99626575)); testCaseSuppliers.addAll(doubleTestCase(300000.0, 10.0, 10000000.0, 200.0, 0.25, "linear", 0.97751575)); testCaseSuppliers.addAll(doubleTestCase(123456789112.123, 10.0, 10000000.0, 200.0, 0.25, "linear", 0.0)); // Double Exponential testCaseSuppliers.addAll(doubleTestCase(0.0, 10.0, 10000000.0, 200.0, 0.25, "exp", 1.0)); testCaseSuppliers.addAll(doubleTestCase(10.0, 10.0, 10000000.0, 200.0, 0.25, "exp", 1.0)); testCaseSuppliers.addAll(doubleTestCase(50000.0, 10.0, 10000000.0, 200.0, 0.25, "exp", 0.9931214069469289)); testCaseSuppliers.addAll(doubleTestCase(300000.0, 10.0, 10000000.0, 200.0, 0.25, "exp", 0.959292046002994)); testCaseSuppliers.addAll(doubleTestCase(123456789112.123, 10.0, 10000000.0, 200.0, 0.25, "exp", 0.0)); // Double Gaussian testCaseSuppliers.addAll(doubleTestCase(0.0, 10.0, 10000000.0, 200.0, 0.25, "gauss", 1.0)); testCaseSuppliers.addAll(doubleTestCase(10.0, 10.0, 10000000.0, 200.0, 0.25, "gauss", 1.0)); testCaseSuppliers.addAll(doubleTestCase(50000.0, 10.0, 10000000.0, 200.0, 0.25, "gauss", 0.9999656337419655)); testCaseSuppliers.addAll(doubleTestCase(300000.0, 10.0, 10000000.0, 200.0, 0.25, "gauss", 0.9987548570291238)); testCaseSuppliers.addAll(doubleTestCase(123456789112.123, 10.0, 10000000.0, 200.0, 0.25, "gauss", 0.0)); // Double defaults testCaseSuppliers.addAll(doubleTestCase(10.0, 0.0, 10.0, null, null, null, 0.5)); // Double random testCaseSuppliers.addAll(doubleRandomTestCases()); // GeoPoint Linear testCaseSuppliers.addAll(geoPointTestCase("POINT (1.0 1.0)", "POINT (1 1)", "10000km", "10km", 0.33, "linear", 1.0)); testCaseSuppliers.addAll(geoPointTestCase("POINT (0 0)", "POINT (1 1)", "10000km", "10km", 0.33, "linear", 0.9901342769495362)); testCaseSuppliers.addAll( geoPointTestCase("POINT (12.3 45.6)", "POINT (1 1)", "10000km", "10km", 0.33, "linear", 0.6602313771587869) ); testCaseSuppliers.addAll( geoPointTestCase("POINT (180.0 90.0)", "POINT (1 1)", "10000km", "10km", 0.33, "linear", 0.33761373954395957) ); testCaseSuppliers.addAll( geoPointTestCase("POINT (-180.0 -90.0)", "POINT (1 1)", "10000km", "10km", 0.33, "linear", 0.32271359885955425) ); // GeoPoint Exponential testCaseSuppliers.addAll(geoPointTestCase("POINT (1.0 1.0)", "POINT (1 1)", "10000km", "10km", 0.33, "exp", 1.0)); testCaseSuppliers.addAll(geoPointTestCase("POINT (0 0)", "POINT (1 1)", "10000km", "10km", 0.33, "exp", 0.983807518295976)); testCaseSuppliers.addAll(geoPointTestCase("POINT (12.3 45.6)", "POINT (1 1)", "10000km", "10km", 0.33, "exp", 0.5699412181941212)); testCaseSuppliers.addAll(geoPointTestCase("POINT (180.0 90.0)", "POINT (1 1)", "10000km", "10km", 0.33, "exp", 0.3341838411351592)); testCaseSuppliers.addAll( geoPointTestCase("POINT (-180.0 -90.0)", "POINT (1 1)", "10000km", "10km", 0.33, "exp", 0.32604509444656576) ); // GeoPoint Gaussian testCaseSuppliers.addAll(geoPointTestCase("POINT (1.0 1.0)", "POINT (1 1)", "10000km", "10km", 0.33, "gauss", 1.0)); testCaseSuppliers.addAll(geoPointTestCase("POINT (0 0)", "POINT (1 1)", "10000km", "10km", 0.33, "gauss", 0.9997596437370099)); testCaseSuppliers.addAll( geoPointTestCase("POINT (12.3 45.6)", "POINT (1 1)", "10000km", "10km", 0.33, "gauss", 0.7519296165431535) ); testCaseSuppliers.addAll( geoPointTestCase("POINT (180.0 90.0)", "POINT (1 1)", "10000km", "10km", 0.33, "gauss", 0.33837227875395753) ); testCaseSuppliers.addAll( geoPointTestCase("POINT (-180.0 -90.0)", "POINT (1 1)", "10000km", "10km", 0.33, "gauss", 0.3220953501115956) ); // GeoPoint offset & scale as keywords testCaseSuppliers.addAll(geoPointTestCaseKeywordScale("POINT (1 1)", "POINT (1 1)", "200km", "0km", 0.5, "linear", 1.0)); testCaseSuppliers.addAll(geoPointOffsetKeywordTestCase("POINT (1 1)", "POINT (1 1)", "200km", "0km", 0.5, "linear", 1.0)); // GeoPoint defaults testCaseSuppliers.addAll(geoPointTestCase("POINT (12.3 45.6)", "POINT (1 1)", "10000km", null, null, null, 0.7459413262379005)); // GeoPoint random testCaseSuppliers.addAll(geoPointRandomTestCases()); // CartesianPoint Linear testCaseSuppliers.addAll(cartesianPointTestCase("POINT (0 0)", "POINT (1 1)", 10000.0, 10.0, 0.33, "linear", 1.0)); testCaseSuppliers.addAll(cartesianPointTestCase("POINT (1 1)", "POINT (1 1)", 10000.0, 10.0, 0.33, "linear", 1.0)); testCaseSuppliers.addAll( cartesianPointTestCase("POINT (1000 2000)", "POINT (1 1)", 10000.0, 10.0, 0.33, "linear", 0.8509433324420796) ); testCaseSuppliers.addAll( cartesianPointTestCase("POINT (-2000 1000)", "POINT (1 1)", 10000.0, 10.0, 0.33, "linear", 0.8508234552350306) ); testCaseSuppliers.addAll(cartesianPointTestCase("POINT (10000 20000)", "POINT (1 1)", 10000.0, 10.0, 0.33, "linear", 0.0)); // CartesianPoint Exponential testCaseSuppliers.addAll(cartesianPointTestCase("POINT (0 0)", "POINT (1 1)", 10000.0, 10.0, 0.33, "exp", 1.0)); testCaseSuppliers.addAll(cartesianPointTestCase("POINT (1 1)", "POINT (1 1)", 10000.0, 10.0, 0.33, "exp", 1.0)); testCaseSuppliers.addAll( cartesianPointTestCase("POINT (1000 2000)", "POINT (1 1)", 10000.0, 10.0, 0.33, "exp", 0.7814164075951677) ); testCaseSuppliers.addAll( cartesianPointTestCase("POINT (-2000 1000)", "POINT (1 1)", 10000.0, 10.0, 0.33, "exp", 0.7812614186677811) ); testCaseSuppliers.addAll( cartesianPointTestCase("POINT (10000 20000)", "POINT (1 1)", 10000.0, 10.0, 0.33, "exp", 0.0839287052363121) ); // CartesianPoint Gaussian testCaseSuppliers.addAll(cartesianPointTestCase("POINT (0 0)", "POINT (1 1)", 10000.0, 10.0, 0.33, "gauss", 1.0)); testCaseSuppliers.addAll(cartesianPointTestCase("POINT (1 1)", "POINT (1 1)", 10000.0, 10.0, 0.33, "gauss", 1.0)); testCaseSuppliers.addAll( cartesianPointTestCase("POINT (1000 2000)", "POINT (1 1)", 10000.0, 10.0, 0.33, "gauss", 0.9466060873472042) ); testCaseSuppliers.addAll( cartesianPointTestCase("POINT (-2000 1000)", "POINT (1 1)", 10000.0, 10.0, 0.33, "gauss", 0.9465225092376659) ); testCaseSuppliers.addAll( cartesianPointTestCase("POINT (10000 20000)", "POINT (1 1)", 10000.0, 10.0, 0.33, "gauss", 0.003935602627423666) ); // CartesianPoint defaults testCaseSuppliers.addAll( cartesianPointTestCase("POINT (1000.0 2000.0)", "POINT (0 0)", 10000.0, null, null, null, 0.8881966011250104) ); // Datetime Linear testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "linear", 1.0 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(2020, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "linear", 0.49569100000000005 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(2025, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "linear", 0.37334900000000004 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(1970, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "linear", 0.28202800000000006 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(1900, 12, 12, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "linear", 0.0 ) ); // Datetime Exponential testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "exp", 1.0 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(2020, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "exp", 0.4340956586740692 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(2025, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "exp", 0.3545406919498116 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(1970, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "exp", 0.30481724812400407 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(1900, 12, 12, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "exp", 0.01813481247808857 ) ); // Datetime Gaussian testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "gauss", 1.0 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(2020, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "gauss", 0.5335935393743785 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(2025, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "gauss", 0.3791426943809958 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(1970, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "gauss", 0.27996050542437345 ) ); testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(1900, 12, 12, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "gauss", 5.025924031342025E-7 ) ); // Datetime Defaults testCaseSuppliers.addAll( datetimeTestCase( LocalDateTime.of(2020, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), null, null, null, 0.62315 ) ); // Datetime random testCaseSuppliers.addAll(datetimeRandomTestCases()); // Datenanos Linear testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "linear", 1.0 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(2020, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "linear", 0.49569100000000005 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(2025, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "linear", 0.37334900000000004 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(1970, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "linear", 0.28202800000000006 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(1900, 12, 12, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "linear", 0.0 ) ); // Datenanos Exponential testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "exp", 1.0 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(2020, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "exp", 0.4340956586740692 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(2025, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "exp", 0.3545406919498116 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(1970, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "exp", 0.30481724812400407 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(1900, 12, 12, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "exp", 0.01813481247808857 ) ); // Datenanos Gaussian testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "gauss", 1.0 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(2020, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "gauss", 0.5335935393743785 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(2025, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "gauss", 0.3791426943809958 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(1970, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "gauss", 0.27996050542437345 ) ); testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(1900, 12, 12, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), Duration.ofDays(10), 0.33, "gauss", 5.025924031342025E-7 ) ); // Datenanos default testCaseSuppliers.addAll( dateNanosTestCase( LocalDateTime.of(2025, 8, 20, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), LocalDateTime.of(2000, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), Duration.ofDays(10000), null, null, null, 0.53185 ) ); // Datenanos random testCaseSuppliers.addAll(dateNanosRandomTestCases()); return parameterSuppliersFromTypedData(testCaseSuppliers); } @Override protected Expression build(Source source, List<Expression> args) { return new Decay(source, args.get(0), args.get(1), args.get(2), args.get(3) != null ? args.get(3) : null); } @Override public void testFold() { // Decay cannot be folded } private static List<TestCaseSupplier> intTestCase( int value, int origin, int scale, Integer offset, Double decay, String functionType, double expected ) { return List.of( new TestCaseSupplier( List.of(DataType.INTEGER, DataType.INTEGER, DataType.INTEGER, DataType.SOURCE), () -> new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(value, DataType.INTEGER, "value"), new TestCaseSupplier.TypedData(origin, DataType.INTEGER, "origin").forceLiteral(), new TestCaseSupplier.TypedData(scale, DataType.INTEGER, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(offset, decay, functionType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayIntEvaluator["), DataType.DOUBLE, closeTo(expected, Math.ulp(expected)) ) ) ); } private static List<TestCaseSupplier> intRandomTestCases() { return List.of(new TestCaseSupplier(List.of(DataType.INTEGER, DataType.INTEGER, DataType.INTEGER, DataType.SOURCE), () -> { int randomValue = randomInt(); int randomOrigin = randomInt(); int randomScale = randomInt(); int randomOffset = randomInt(); double randomDecay = randomDouble(); String randomType = getRandomType(); double scoreScriptNumericResult = intDecayWithScoreScript( randomValue, randomOrigin, randomScale, randomOffset, randomDecay, randomType ); return new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(randomValue, DataType.INTEGER, "value"), new TestCaseSupplier.TypedData(randomOrigin, DataType.INTEGER, "origin").forceLiteral(), new TestCaseSupplier.TypedData(randomScale, DataType.INTEGER, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(randomOffset, randomDecay, randomType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayIntEvaluator["), DataType.DOUBLE, decayValueMatcher(scoreScriptNumericResult) ); })); } private static String getRandomType() { return randomFrom("linear", "gauss", "exp"); } private static double intDecayWithScoreScript(int value, int origin, int scale, int offset, double decay, String type) { return switch (type) { case "linear" -> new ScoreScriptUtils.DecayNumericLinear(origin, scale, offset, decay).decayNumericLinear(value); case "gauss" -> new ScoreScriptUtils.DecayNumericGauss(origin, scale, offset, decay).decayNumericGauss(value); case "exp" -> new ScoreScriptUtils.DecayNumericExp(origin, scale, offset, decay).decayNumericExp(value); default -> throw new IllegalArgumentException("Unknown decay function type [" + type + "]"); }; } private static List<TestCaseSupplier> longTestCase( long value, long origin, long scale, Long offset, Double decay, String functionType, double expected ) { return List.of( new TestCaseSupplier( List.of(DataType.LONG, DataType.LONG, DataType.LONG, DataType.SOURCE), () -> new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(value, DataType.LONG, "value"), new TestCaseSupplier.TypedData(origin, DataType.LONG, "origin").forceLiteral(), new TestCaseSupplier.TypedData(scale, DataType.LONG, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(offset, decay, functionType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayLongEvaluator["), DataType.DOUBLE, closeTo(expected, Math.ulp(expected)) ) ) ); } private static List<TestCaseSupplier> longRandomTestCases() { return List.of(new TestCaseSupplier(List.of(DataType.LONG, DataType.LONG, DataType.LONG, DataType.SOURCE), () -> { long randomValue = randomLong(); long randomOrigin = randomLong(); long randomScale = randomLong(); long randomOffset = randomLong(); double randomDecay = randomDouble(); String randomType = randomFrom("linear", "gauss", "exp"); double scoreScriptNumericResult = longDecayWithScoreScript( randomValue, randomOrigin, randomScale, randomOffset, randomDecay, randomType ); return new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(randomValue, DataType.LONG, "value"), new TestCaseSupplier.TypedData(randomOrigin, DataType.LONG, "origin").forceLiteral(), new TestCaseSupplier.TypedData(randomScale, DataType.LONG, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(randomOffset, randomDecay, randomType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayLongEvaluator["), DataType.DOUBLE, decayValueMatcher(scoreScriptNumericResult) ); })); } private static double longDecayWithScoreScript(long value, long origin, long scale, long offset, double decay, String type) { return switch (type) { case "linear" -> new ScoreScriptUtils.DecayNumericLinear(origin, scale, offset, decay).decayNumericLinear(value); case "gauss" -> new ScoreScriptUtils.DecayNumericGauss(origin, scale, offset, decay).decayNumericGauss(value); case "exp" -> new ScoreScriptUtils.DecayNumericExp(origin, scale, offset, decay).decayNumericExp(value); default -> throw new IllegalArgumentException("Unknown decay function type [" + type + "]"); }; } private static List<TestCaseSupplier> doubleTestCase( double value, double origin, double scale, Double offset, Double decay, String functionType, double expected ) { return List.of( new TestCaseSupplier( List.of(DataType.DOUBLE, DataType.DOUBLE, DataType.DOUBLE, DataType.SOURCE), () -> new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(value, DataType.DOUBLE, "value"), new TestCaseSupplier.TypedData(origin, DataType.DOUBLE, "origin").forceLiteral(), new TestCaseSupplier.TypedData(scale, DataType.DOUBLE, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(offset, decay, functionType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayDoubleEvaluator["), DataType.DOUBLE, closeTo(expected, Math.ulp(expected)) ) ) ); } private static List<TestCaseSupplier> doubleRandomTestCases() { return List.of(new TestCaseSupplier(List.of(DataType.DOUBLE, DataType.DOUBLE, DataType.DOUBLE, DataType.SOURCE), () -> { double randomValue = randomLong(); double randomOrigin = randomLong(); double randomScale = randomLong(); double randomOffset = randomLong(); double randomDecay = randomDouble(); String randomType = randomFrom("linear", "gauss", "exp"); double scoreScriptNumericResult = doubleDecayWithScoreScript( randomValue, randomOrigin, randomScale, randomOffset, randomDecay, randomType ); return new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(randomValue, DataType.DOUBLE, "value"), new TestCaseSupplier.TypedData(randomOrigin, DataType.DOUBLE, "origin").forceLiteral(), new TestCaseSupplier.TypedData(randomScale, DataType.DOUBLE, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(randomOffset, randomDecay, randomType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayDoubleEvaluator["), DataType.DOUBLE, decayValueMatcher(scoreScriptNumericResult) ); })); } private static double doubleDecayWithScoreScript(double value, double origin, double scale, double offset, double decay, String type) { return switch (type) { case "linear" -> new ScoreScriptUtils.DecayNumericLinear(origin, scale, offset, decay).decayNumericLinear(value); case "gauss" -> new ScoreScriptUtils.DecayNumericGauss(origin, scale, offset, decay).decayNumericGauss(value); case "exp" -> new ScoreScriptUtils.DecayNumericExp(origin, scale, offset, decay).decayNumericExp(value); default -> throw new IllegalArgumentException("Unknown decay function type [" + type + "]"); }; } private static List<TestCaseSupplier> geoPointTestCase( String valueWkt, String originWkt, String scale, String offset, Double decay, String functionType, double expected ) { return List.of( new TestCaseSupplier( List.of(DataType.GEO_POINT, DataType.GEO_POINT, DataType.TEXT, DataType.SOURCE), () -> new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(GEO.wktToWkb(valueWkt), DataType.GEO_POINT, "value"), new TestCaseSupplier.TypedData(GEO.wktToWkb(originWkt), DataType.GEO_POINT, "origin").forceLiteral(), new TestCaseSupplier.TypedData(scale, DataType.TEXT, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(offset, decay, functionType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayGeoPointEvaluator["), DataType.DOUBLE, closeTo(expected, Math.ulp(expected)) ) ) ); } private static List<TestCaseSupplier> geoPointTestCaseKeywordScale( String valueWkt, String originWkt, String scale, String offset, Double decay, String functionType, double expected ) { return List.of( new TestCaseSupplier( List.of(DataType.GEO_POINT, DataType.GEO_POINT, DataType.KEYWORD, DataType.SOURCE), () -> new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(GEO.wktToWkb(valueWkt), DataType.GEO_POINT, "value"), new TestCaseSupplier.TypedData(GEO.wktToWkb(originWkt), DataType.GEO_POINT, "origin").forceLiteral(), new TestCaseSupplier.TypedData(scale, DataType.KEYWORD, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(offset, decay, functionType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayGeoPointEvaluator["), DataType.DOUBLE, closeTo(expected, Math.ulp(expected)) ) ) ); } private static List<TestCaseSupplier> geoPointRandomTestCases() { return List.of(new TestCaseSupplier(List.of(DataType.GEO_POINT, DataType.GEO_POINT, DataType.KEYWORD, DataType.SOURCE), () -> { GeoPoint randomValue = randomGeoPoint(); GeoPoint randomOrigin = randomGeoPoint(); String randomScale = randomDistance(); String randomOffset = randomDistance(); double randomDecay = randomDouble(); String randomType = randomDecayType(); double scoreScriptNumericResult = geoPointDecayWithScoreScript( randomValue, randomOrigin, randomScale, randomOffset, randomDecay, randomType ); return new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(GEO.wktToWkb(randomValue.toWKT()), DataType.GEO_POINT, "value"), new TestCaseSupplier.TypedData(GEO.wktToWkb(randomOrigin.toWKT()), DataType.GEO_POINT, "origin").forceLiteral(), new TestCaseSupplier.TypedData(randomScale, DataType.KEYWORD, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(randomOffset, randomDecay, randomType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayGeoPointEvaluator["), DataType.DOUBLE, decayValueMatcher(scoreScriptNumericResult) ); })); } private static String randomDecayType() { return randomFrom("linear", "gauss", "exp"); } private static GeoPoint randomGeoPoint() { return new GeoPoint(randomLatitude(), randomLongitude()); } private static double randomLongitude() { return randomDoubleBetween(-180.0, 180.0, true); } private static double randomLatitude() { return randomDoubleBetween(-90.0, 90.0, true); } private static String randomDistance() { return String.format( Locale.ROOT, "%d%s", randomNonNegativeInt(), randomFrom( DistanceUnit.INCH, DistanceUnit.YARD, DistanceUnit.FEET, DistanceUnit.KILOMETERS, DistanceUnit.NAUTICALMILES, DistanceUnit.MILLIMETERS, DistanceUnit.CENTIMETERS, DistanceUnit.MILES, DistanceUnit.METERS ) ); } private static double geoPointDecayWithScoreScript( GeoPoint value, GeoPoint origin, String scale, String offset, double decay, String type ) { String originStr = origin.getX() + "," + origin.getY(); return switch (type) { case "linear" -> new ScoreScriptUtils.DecayGeoLinear(originStr, scale, offset, decay).decayGeoLinear(value); case "gauss" -> new ScoreScriptUtils.DecayGeoGauss(originStr, scale, offset, decay).decayGeoGauss(value); case "exp" -> new ScoreScriptUtils.DecayGeoExp(originStr, scale, offset, decay).decayGeoExp(value); default -> throw new IllegalArgumentException("Unknown decay function type [" + type + "]"); }; } private static List<TestCaseSupplier> geoPointOffsetKeywordTestCase( String valueWkt, String originWkt, String scale, String offset, Double decay, String functionType, double expected ) { return List.of( new TestCaseSupplier( List.of(DataType.GEO_POINT, DataType.GEO_POINT, DataType.TEXT, DataType.SOURCE), () -> new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(GEO.wktToWkb(valueWkt), DataType.GEO_POINT, "value"), new TestCaseSupplier.TypedData(GEO.wktToWkb(originWkt), DataType.GEO_POINT, "origin").forceLiteral(), new TestCaseSupplier.TypedData(scale, DataType.TEXT, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(offset, decay, functionType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayGeoPointEvaluator["), DataType.DOUBLE, closeTo(expected, Math.ulp(expected)) ) ) ); } private static List<TestCaseSupplier> cartesianPointTestCase( String valueWkt, String originWkt, double scale, Double offset, Double decay, String functionType, double expected ) { return List.of( new TestCaseSupplier( List.of(DataType.CARTESIAN_POINT, DataType.CARTESIAN_POINT, DataType.DOUBLE, DataType.SOURCE), () -> new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(CARTESIAN.wktToWkb(valueWkt), DataType.CARTESIAN_POINT, "value"), new TestCaseSupplier.TypedData(CARTESIAN.wktToWkb(originWkt), DataType.CARTESIAN_POINT, "origin").forceLiteral(), new TestCaseSupplier.TypedData(scale, DataType.DOUBLE, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(offset, decay, functionType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayCartesianPointEvaluator["), DataType.DOUBLE, closeTo(expected, Math.ulp(expected)) ) ) ); } private static List<TestCaseSupplier> datetimeTestCase( long value, long origin, Duration scale, Duration offset, Double decay, String functionType, double expected ) { return List.of( new TestCaseSupplier( List.of(DataType.DATETIME, DataType.DATETIME, DataType.TIME_DURATION, DataType.SOURCE), () -> new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(value, DataType.DATETIME, "value"), new TestCaseSupplier.TypedData(origin, DataType.DATETIME, "origin").forceLiteral(), new TestCaseSupplier.TypedData(scale, DataType.TIME_DURATION, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(offset, decay, functionType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayDatetimeEvaluator["), DataType.DOUBLE, closeTo(expected, Math.ulp(expected)) ).withoutEvaluator() ) ); } private static List<TestCaseSupplier> datetimeRandomTestCases() { return List.of(new TestCaseSupplier(List.of(DataType.DATETIME, DataType.DATETIME, DataType.TIME_DURATION, DataType.SOURCE), () -> { // 1970-01-01 long minEpoch = 0L; // 2070-01-01 long maxEpoch = 3155673600000L; long randomValue = randomLongBetween(minEpoch, maxEpoch); long randomOrigin = randomLongBetween(minEpoch, maxEpoch); // Max 1 year long randomScaleMillis = randomNonNegativeLong() % (365L * 24 * 60 * 60 * 1000); // Max 30 days long randomOffsetMillis = randomNonNegativeLong() % (30L * 24 * 60 * 60 * 1000); Duration randomScale = Duration.ofMillis(randomScaleMillis); Duration randomOffset = Duration.ofMillis(randomOffsetMillis); double randomDecay = randomDouble(); String randomType = randomFrom("linear", "gauss", "exp"); double scoreScriptNumericResult = datetimeDecayWithScoreScript( randomValue, randomOrigin, randomScale.toMillis(), randomOffset.toMillis(), randomDecay, randomType ); return new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(randomValue, DataType.DATETIME, "value"), new TestCaseSupplier.TypedData(randomOrigin, DataType.DATETIME, "origin").forceLiteral(), new TestCaseSupplier.TypedData(randomScale, DataType.TIME_DURATION, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(randomOffset, randomDecay, randomType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayDatetimeEvaluator["), DataType.DOUBLE, decayValueMatcher(scoreScriptNumericResult) ); })); } private static double datetimeDecayWithScoreScript(long value, long origin, long scale, long offset, double decay, String type) { String originStr = String.valueOf(origin); String scaleStr = scale + "ms"; String offsetStr = offset + "ms"; ZonedDateTime valueDateTime = Instant.ofEpochMilli(value).atZone(ZoneId.of("UTC")); return switch (type) { case "linear" -> new ScoreScriptUtils.DecayDateLinear(originStr, scaleStr, offsetStr, decay).decayDateLinear(valueDateTime); case "gauss" -> new ScoreScriptUtils.DecayDateGauss(originStr, scaleStr, offsetStr, decay).decayDateGauss(valueDateTime); case "exp" -> new ScoreScriptUtils.DecayDateExp(originStr, scaleStr, offsetStr, decay).decayDateExp(valueDateTime); default -> throw new IllegalArgumentException("Unknown decay function type [" + type + "]"); }; } private static List<TestCaseSupplier> dateNanosTestCase( long value, long origin, Duration scale, Duration offset, Double decay, String functionType, double expected ) { return List.of( new TestCaseSupplier( List.of(DataType.DATE_NANOS, DataType.DATE_NANOS, DataType.TIME_DURATION, DataType.SOURCE), () -> new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(value, DataType.DATE_NANOS, "value"), new TestCaseSupplier.TypedData(origin, DataType.DATE_NANOS, "origin").forceLiteral(), new TestCaseSupplier.TypedData(scale, DataType.TIME_DURATION, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(offset, decay, functionType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayDateNanosEvaluator["), DataType.DOUBLE, closeTo(expected, Math.ulp(expected)) ).withoutEvaluator() ) ); } private static List<TestCaseSupplier> dateNanosRandomTestCases() { return List.of( new TestCaseSupplier(List.of(DataType.DATE_NANOS, DataType.DATE_NANOS, DataType.TIME_DURATION, DataType.SOURCE), () -> { // 1970-01-01 in nanos long minEpochNanos = 0L; // 2070-01-01 in nanos long maxEpochNanos = 3155673600000L * 1_000_000L; long randomValue = randomLongBetween(minEpochNanos, maxEpochNanos); long randomOrigin = randomLongBetween(minEpochNanos, maxEpochNanos); // Max 1 year in milliseconds long randomScaleMillis = randomNonNegativeLong() % (365L * 24 * 60 * 60 * 1000); // Max 30 days in milliseconds long randomOffsetMillis = randomNonNegativeLong() % (30L * 24 * 60 * 60 * 1000); Duration randomScale = Duration.ofMillis(randomScaleMillis); Duration randomOffset = Duration.ofMillis(randomOffsetMillis); double randomDecay = randomDouble(); String randomType = randomFrom("linear", "gauss", "exp"); double scoreScriptNumericResult = dateNanosDecayWithScoreScript( randomValue, randomOrigin, randomScale.toMillis(), randomOffset.toMillis(), randomDecay, randomType ); return new TestCaseSupplier.TestCase( List.of( new TestCaseSupplier.TypedData(randomValue, DataType.DATE_NANOS, "value"), new TestCaseSupplier.TypedData(randomOrigin, DataType.DATE_NANOS, "origin").forceLiteral(), new TestCaseSupplier.TypedData(randomScale, DataType.TIME_DURATION, "scale").forceLiteral(), new TestCaseSupplier.TypedData(createOptionsMap(randomOffset, randomDecay, randomType), DataType.SOURCE, "options") .forceLiteral() ), startsWith("DecayDateNanosEvaluator["), DataType.DOUBLE, decayValueMatcher(scoreScriptNumericResult) ); }) ); } private static double dateNanosDecayWithScoreScript(long value, long origin, long scale, long offset, double decay, String type) { long valueMillis = value / 1_000_000L; long originMillis = origin / 1_000_000L; String originStr = String.valueOf(originMillis); String scaleStr = scale + "ms"; String offsetStr = offset + "ms"; ZonedDateTime valueDateTime = Instant.ofEpochMilli(valueMillis).atZone(ZoneId.of("UTC")); return switch (type) { case "linear" -> new ScoreScriptUtils.DecayDateLinear(originStr, scaleStr, offsetStr, decay).decayDateLinear(valueDateTime); case "gauss" -> new ScoreScriptUtils.DecayDateGauss(originStr, scaleStr, offsetStr, decay).decayDateGauss(valueDateTime); case "exp" -> new ScoreScriptUtils.DecayDateExp(originStr, scaleStr, offsetStr, decay).decayDateExp(valueDateTime); default -> throw new IllegalArgumentException("Unknown decay function type [" + type + "]"); }; } private static MapExpression createOptionsMap(Object offset, Double decay, String functionType) { List<Expression> keyValuePairs = new ArrayList<>(); // Offset if (Objects.nonNull(offset)) { keyValuePairs.add(Literal.keyword(Source.EMPTY, "offset")); switch (offset) { case Integer value -> keyValuePairs.add(Literal.integer(Source.EMPTY, value)); case Long value -> keyValuePairs.add(Literal.fromLong(Source.EMPTY, value)); case Double value -> keyValuePairs.add(Literal.fromDouble(Source.EMPTY, value)); case String value -> keyValuePairs.add(Literal.text(Source.EMPTY, value)); case Duration value -> keyValuePairs.add(Literal.timeDuration(Source.EMPTY, value)); default -> { } } } // Decay if (Objects.nonNull(decay)) { keyValuePairs.add(Literal.keyword(Source.EMPTY, "decay")); keyValuePairs.add(Literal.fromDouble(Source.EMPTY, decay)); } // Type if (Objects.nonNull(functionType)) { keyValuePairs.add(Literal.keyword(Source.EMPTY, "type")); keyValuePairs.add(Literal.keyword(Source.EMPTY, functionType)); } return new MapExpression(Source.EMPTY, keyValuePairs); } private static Matcher<Double> decayValueMatcher(Double value) { if (value == Double.POSITIVE_INFINITY || value == Double.NEGATIVE_INFINITY) { return equalTo(value); } return closeTo(BigDecimal.valueOf(value).setScale(4, RoundingMode.CEILING).doubleValue(), 0.001); } }
DecayTests
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/conf/TestStorageUnit.java
{ "start": 1044, "end": 10467 }
class ____ { final static double KB = 1024.0; final static double MB = KB * 1024.0; final static double GB = MB * 1024.0; final static double TB = GB * 1024.0; final static double PB = TB * 1024.0; final static double EB = PB * 1024.0; @Test public void testByteToKiloBytes() { Map<Double, Double> results = new HashMap<>(); results.put(1024.0, 1.0); results.put(2048.0, 2.0); results.put(-1024.0, -1.0); results.put(34565.0, 33.7549); results.put(223344332.0, 218109.6992); results.put(1234983.0, 1206.0381); results.put(1234332.0, 1205.4023); results.put(0.0, 0.0); for (Map.Entry<Double, Double> entry : results.entrySet()) { assertThat(StorageUnit.BYTES.toKBs(entry.getKey())).isEqualTo(entry.getValue()); } } @Test public void testBytesToMegaBytes() { Map<Double, Double> results = new HashMap<>(); results.put(1048576.0, 1.0); results.put(24117248.0, 23.0); results.put(459920023.0, 438.6139); results.put(234443233.0, 223.5825); results.put(-35651584.0, -34.0); results.put(0.0, 0.0); for (Map.Entry<Double, Double> entry : results.entrySet()) { assertThat(StorageUnit.BYTES.toMBs(entry.getKey())).isEqualTo(entry.getValue()); } } @Test public void testBytesToGigaBytes() { Map<Double, Double> results = new HashMap<>(); results.put(1073741824.0, 1.0); results.put(24696061952.0, 23.0); results.put(459920023.0, 0.4283); results.put(234443233.0, 0.2183); results.put(-36507222016.0, -34.0); results.put(0.0, 0.0); for (Map.Entry<Double, Double> entry : results.entrySet()) { assertThat(StorageUnit.BYTES.toGBs(entry.getKey())).isEqualTo(entry.getValue()); } } @Test public void testBytesToTerraBytes() { Map<Double, Double> results = new HashMap<>(); results.put(1.09951E+12, 1.0); results.put(2.52888E+13, 23.0); results.put(459920023.0, 0.0004); results.put(234443233.0, 0.0002); results.put(-3.73834E+13, -34.0); results.put(0.0, 0.0); for (Map.Entry<Double, Double> entry : results.entrySet()) { assertThat(StorageUnit.BYTES.toTBs(entry.getKey())).isEqualTo(entry.getValue()); } } @Test public void testBytesToPetaBytes() { Map<Double, Double> results = new HashMap<>(); results.put(1.1259E+15, 1.0); results.put(2.58957E+16, 23.0); results.put(4.70958E+11, 0.0004); results.put(234443233.0, 0.0000); // Out of precision window. results.put(-3.82806E+16, -34.0); results.put(0.0, 0.0); for (Map.Entry<Double, Double> entry : results.entrySet()) { assertThat(StorageUnit.BYTES.toPBs(entry.getKey())).isEqualTo(entry.getValue()); } } @Test public void testBytesToExaBytes() { Map<Double, Double> results = new HashMap<>(); results.put(1.15292E+18, 1.0); results.put(2.65172E+19, 23.0); results.put(4.82261E+14, 0.0004); results.put(234443233.0, 0.0000); // Out of precision window. results.put(-3.91993E+19, -34.0); results.put(0.0, 0.0); for (Map.Entry<Double, Double> entry : results.entrySet()) { assertThat(StorageUnit.BYTES.toEBs(entry.getKey())).isEqualTo(entry.getValue()); } } @Test public void testByteConversions() { assertThat(StorageUnit.BYTES.getShortName()).isEqualTo("b"); assertThat(StorageUnit.BYTES.getSuffixChar()).isEqualTo("b"); assertThat(StorageUnit.BYTES.getLongName()).isEqualTo("bytes"); assertThat(StorageUnit.BYTES.toString()).isEqualTo("bytes"); assertThat(StorageUnit.BYTES.toBytes(1)).isEqualTo((1.0)); assertThat(StorageUnit.BYTES.toBytes(1024)). isEqualTo(StorageUnit.BYTES.getDefault(1024)); assertThat(StorageUnit.BYTES.fromBytes(10)).isEqualTo(10.0); } @Test public void testKBConversions() { assertThat(StorageUnit.KB.getShortName()).isEqualTo("kb"); assertThat(StorageUnit.KB.getSuffixChar()).isEqualTo(("k")); assertThat(StorageUnit.KB.getLongName()).isEqualTo("kilobytes"); assertThat(StorageUnit.KB.toString()).isEqualTo("kilobytes"); assertThat(StorageUnit.KB.toKBs(1024)). isEqualTo(StorageUnit.KB.getDefault(1024)); assertThat(StorageUnit.KB.toBytes(1)).isEqualTo(KB); assertThat(StorageUnit.KB.fromBytes(KB)).isEqualTo(1.0); assertThat(StorageUnit.KB.toKBs(10)).isEqualTo((10.0)); assertThat(StorageUnit.KB.toMBs(3.0 * 1024.0)).isEqualTo((3.0)); assertThat(StorageUnit.KB.toGBs(1073741824)).isEqualTo((1024.0)); assertThat(StorageUnit.KB.toTBs(1073741824)).isEqualTo(1.0); assertThat(StorageUnit.KB.toPBs(1.0995116e+12)).isEqualTo((1.0)); assertThat(StorageUnit.KB.toEBs(1.1258999e+15)).isEqualTo((1.0)); } @Test public void testMBConversions() { assertThat(StorageUnit.MB.getShortName()).isEqualTo("mb"); assertThat(StorageUnit.MB.getSuffixChar()).isEqualTo("m"); assertThat(StorageUnit.MB.getLongName()).isEqualTo("megabytes"); assertThat(StorageUnit.MB.toString()).isEqualTo("megabytes"); assertThat(StorageUnit.MB.toMBs(1024)). isEqualTo(StorageUnit.MB.getDefault(1024)); assertThat(StorageUnit.MB.toBytes(1)).isEqualTo(MB); assertThat(StorageUnit.MB.fromBytes(MB)).isEqualTo(1.0); assertThat(StorageUnit.MB.toKBs(1)).isEqualTo(1024.0); assertThat(StorageUnit.MB.toMBs(10)).isEqualTo(10.0); assertThat(StorageUnit.MB.toGBs(44040192)).isEqualTo(43008.0); assertThat(StorageUnit.MB.toTBs(1073741824)).isEqualTo(1024.0); assertThat(StorageUnit.MB.toPBs(1073741824)).isEqualTo(1.0); assertThat(StorageUnit.MB.toEBs(1 * (EB/MB))).isEqualTo(1.0); } @Test public void testGBConversions() { assertThat(StorageUnit.GB.getShortName()).isEqualTo("gb"); assertThat(StorageUnit.GB.getSuffixChar()).isEqualTo("g"); assertThat(StorageUnit.GB.getLongName()).isEqualTo("gigabytes"); assertThat(StorageUnit.GB.toString()).isEqualTo("gigabytes"); assertThat(StorageUnit.GB.toGBs(1024)).isEqualTo( StorageUnit.GB.getDefault(1024)); assertThat(StorageUnit.GB.toBytes(1)).isEqualTo(GB); assertThat(StorageUnit.GB.fromBytes(GB)).isEqualTo((1.0)); assertThat(StorageUnit.GB.toKBs(1)).isEqualTo(1024.0 * 1024); assertThat(StorageUnit.GB.toMBs(10)).isEqualTo((10.0 * 1024)); assertThat(StorageUnit.GB.toGBs(44040192.0)).isEqualTo((44040192.0)); assertThat(StorageUnit.GB.toTBs(1073741824)).isEqualTo((1048576.0)); assertThat(StorageUnit.GB.toPBs(1.07375e+9)).isEqualTo((1024.0078)); assertThat(StorageUnit.GB.toEBs(1 * (EB/GB))).isEqualTo((1.0)); } @Test public void testTBConversions() { assertThat(StorageUnit.TB.getShortName()).isEqualTo(("tb")); assertThat(StorageUnit.TB.getSuffixChar()).isEqualTo(("t")); assertThat(StorageUnit.TB.getLongName()).isEqualTo(("terabytes")); assertThat(StorageUnit.TB.toString()).isEqualTo(("terabytes")); assertThat(StorageUnit.TB.toTBs(1024)).isEqualTo( (StorageUnit.TB.getDefault(1024))); assertThat(StorageUnit.TB.toBytes(1)).isEqualTo((TB)); assertThat(StorageUnit.TB.fromBytes(TB)).isEqualTo((1.0)); assertThat(StorageUnit.TB.toKBs(1)).isEqualTo((1024.0 * 1024* 1024)); assertThat(StorageUnit.TB.toMBs(10)).isEqualTo((10.0 * 1024 * 1024)); assertThat(StorageUnit.TB.toGBs(44040192.0)).isEqualTo(45097156608.0); assertThat(StorageUnit.TB.toTBs(1073741824.0)).isEqualTo(1073741824.0); assertThat(StorageUnit.TB.toPBs(1024)).isEqualTo(1.0); assertThat(StorageUnit.TB.toEBs(1 * (EB/TB))).isEqualTo(1.0); } @Test public void testPBConversions() { assertThat(StorageUnit.PB.getShortName()).isEqualTo(("pb")); assertThat(StorageUnit.PB.getSuffixChar()).isEqualTo(("p")); assertThat(StorageUnit.PB.getLongName()).isEqualTo(("petabytes")); assertThat(StorageUnit.PB.toString()).isEqualTo(("petabytes")); assertThat(StorageUnit.PB.toPBs(1024)).isEqualTo( StorageUnit.PB.getDefault(1024)); assertThat(StorageUnit.PB.toBytes(1)).isEqualTo(PB); assertThat(StorageUnit.PB.fromBytes(PB)).isEqualTo(1.0); assertThat(StorageUnit.PB.toKBs(1)).isEqualTo(PB/KB); assertThat(StorageUnit.PB.toMBs(10)).isEqualTo(10.0 * (PB / MB)); assertThat(StorageUnit.PB.toGBs(44040192.0)).isEqualTo(44040192.0 * PB/GB); assertThat(StorageUnit.PB.toTBs(1073741824.0)).isEqualTo(1073741824.0 * (PB/TB)); assertThat(StorageUnit.PB.toPBs(1024.0)).isEqualTo(1024.0); assertThat(StorageUnit.PB.toEBs(1024.0)).isEqualTo(1.0); } @Test public void testEBConversions() { assertThat(StorageUnit.EB.getShortName()).isEqualTo("eb"); assertThat(StorageUnit.EB.getSuffixChar()).isEqualTo("e"); assertThat(StorageUnit.EB.getLongName()).isEqualTo("exabytes"); assertThat(StorageUnit.EB.toString()).isEqualTo("exabytes"); assertThat(StorageUnit.EB.toEBs(1024)).isEqualTo(StorageUnit.EB.getDefault(1024)); assertThat(StorageUnit.EB.toBytes(1)).isEqualTo(EB); assertThat(StorageUnit.EB.fromBytes(EB)).isEqualTo(1.0); assertThat(StorageUnit.EB.toKBs(1)).isEqualTo(EB/KB); assertThat(StorageUnit.EB.toMBs(10)).isEqualTo(10.0 * (EB / MB)); assertThat(StorageUnit.EB.toGBs(44040192.0)).isEqualTo(44040192.0 * EB/GB); assertThat(StorageUnit.EB.toTBs(1073741824.0)).isEqualTo((1073741824.0 * (EB/TB))); assertThat(StorageUnit.EB.toPBs(1.0)).isEqualTo(1024.0); assertThat(StorageUnit.EB.toEBs(42.0)).isEqualTo(42.0); } }
TestStorageUnit
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/UserGroupInformation.java
{ "start": 72267, "end": 73153 }
class ____ extends EnumMap<LoginParam,String> implements Parameters { LoginParams() { super(LoginParam.class); } // do not add null values, nor allow existing values to be overriden. @Override public String put(LoginParam param, String val) { boolean add = val != null && !containsKey(param); return add ? super.put(param, val) : null; } static LoginParams getDefaults() { LoginParams params = new LoginParams(); params.put(LoginParam.PRINCIPAL, System.getenv("KRB5PRINCIPAL")); params.put(LoginParam.KEYTAB, System.getenv("KRB5KEYTAB")); params.put(LoginParam.CCACHE, System.getenv("KRB5CCNAME")); return params; } } // wrapper to allow access to fields necessary to recreate the same login // context for relogin. explicitly private to prevent external tampering. private static
LoginParams
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/json/Jackson2TesterTests.java
{ "start": 1243, "end": 2668 }
class ____ extends AbstractJsonMarshalTesterTests { @Test @SuppressWarnings("NullAway") // Test null check void initFieldsWhenTestIsNullShouldThrowException() { assertThatIllegalArgumentException().isThrownBy(() -> Jackson2Tester.initFields(null, new ObjectMapper())) .withMessageContaining("'testInstance' must not be null"); } @Test @SuppressWarnings("NullAway") // Test null check void initFieldsWhenMarshallerIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> Jackson2Tester.initFields(new InitFieldsTestClass(), (ObjectMapper) null)) .withMessageContaining("'marshaller' must not be null"); } @Test void initFieldsShouldSetNullFields() { InitFieldsTestClass test = new InitFieldsTestClass(); assertThat(test.test).isNull(); assertThat(test.base).isNull(); Jackson2Tester.initFields(test, new ObjectMapper()); assertThat(test.test).isNotNull(); assertThat(test.base).isNotNull(); ResolvableType type = test.test.getType(); assertThat(type).isNotNull(); assertThat(type.resolve()).isEqualTo(List.class); assertThat(type.resolveGeneric()).isEqualTo(ExampleObject.class); } @Override protected AbstractJsonMarshalTester<Object> createTester(Class<?> resourceLoadClass, ResolvableType type) { return new org.springframework.boot.test.json.Jackson2Tester<>(resourceLoadClass, type, new ObjectMapper()); } abstract static
Jackson2TesterTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/DetectProhibitChar.java
{ "start": 1079, "end": 2679 }
class ____ { byte[] masks = new byte[1024 * 8]; public DetectProhibitChar(){ } public DetectProhibitChar(char prohibits[]){ addProhibitChar(prohibits); } /** * 增加一个跳越字符 * * @param c */ public void addProhibitChar(char c) { int pos = c >> 3; masks[pos] = (byte) ((masks[pos] & 0xFF) | (1 << (c % 8))); } /** * 增加一个string里的所有字符 * * @param str */ public void addProhibitChar(String str) { if (str != null) { char cs[] = str.toCharArray(); for (char c : cs) { addProhibitChar(c); } } } public void addProhibitChar(char prohibits[]) { if (prohibits != null) { for (char c : prohibits) { addProhibitChar(c); } } } public void removeProhibitChar(char c) { int pos = c >> 3; masks[pos] = (byte) ((masks[pos] & 0xFF) & (~(1 << (c % 8)))); } public boolean isProhibitChar(char c) { int pos = c >> 3; int i = (masks[pos] & 0xFF) & (1 << (c % 8)); return (i != 0); } public boolean hasProhibitChar(char cs[]) { if (cs != null) { for (char c : cs) { if (isProhibitChar(c)) { return true; } } } return false; } public boolean hasProhibitChar(String str) { if (str != null) { return hasProhibitChar(str.toCharArray()); } return false; } }
DetectProhibitChar
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/boolean2darrays/Boolean2DArrays_assertHasDimensions_Test.java
{ "start": 1044, "end": 1336 }
class ____ extends Boolean2DArraysBaseTest { @Test void should_delegate_to_Arrays2D() { // WHEN boolean2dArrays.assertHasDimensions(info, actual, 2, 3); // THEN verify(arrays2d).assertHasDimensions(info, failures, actual, 2, 3); } }
Boolean2DArrays_assertHasDimensions_Test
java
apache__flink
flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java
{ "start": 19428, "end": 20738 }
class ____<T, SplitStateT> { final String splitId; final SplitStateT state; @Nullable SourceOutput<T> sourceOutput; private SplitContext(String splitId, SplitStateT state) { this.state = state; this.splitId = splitId; } SourceOutput<T> getOrCreateSplitOutput( ReaderOutput<T> mainOutput, @Nullable Function<T, Boolean> eofRecordHandler, boolean rateLimitingEnabled) { if (sourceOutput == null) { // The split output should have been created when AddSplitsEvent was processed in // SourceOperator. Here we just use this method to get the previously created // output. sourceOutput = mainOutput.createOutputForSplit(splitId); if (eofRecordHandler != null) { sourceOutput = new SourceOutputWrapper<>(sourceOutput, eofRecordHandler); } if (rateLimitingEnabled) { sourceOutput = new RateLimitingSourceOutputWrapper<>(sourceOutput); } } return sourceOutput; } } /** This output will stop sending records after receiving the eof record. */ private static final
SplitContext
java
quarkusio__quarkus
extensions/smallrye-metrics/deployment/src/main/java/io/quarkus/smallrye/metrics/deployment/SmallRyeMetricsConfig.java
{ "start": 509, "end": 1759 }
interface ____ enabled, the value will be resolved as a path relative to * `${quarkus.management.root-path}`. */ @WithDefault("metrics") String path(); /** * Whether metrics published by Quarkus extensions should be enabled. */ @WithName("extensions.enabled") @WithDefault("true") boolean extensionsEnabled(); /** * Apply Micrometer compatibility mode, where instead of regular 'base' and 'vendor' metrics, * Quarkus exposes the same 'jvm' metrics that Micrometer does. Application metrics are unaffected by this mode. * The use case is to facilitate migration from Micrometer-based metrics, because original dashboards for JVM metrics * will continue working without having to rewrite them. */ @WithName("micrometer.compatibility") @WithDefault("false") boolean micrometerCompatibility(); /** * Whether detailed JAX-RS metrics should be enabled. * <p> * See <a href= * "https://github.com/eclipse/microprofile-metrics/blob/2.3.x/spec/src/main/asciidoc/required-metrics.adoc#optional-rest">MicroProfile * Metrics: Optional REST metrics</a>. */ @WithName("jaxrs.enabled") @WithDefault("false") boolean jaxrsEnabled(); }
is
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/TestReservedSpaceCalculator.java
{ "start": 2111, "end": 10007 }
class ____ { private Configuration conf; private DF usage; private ReservedSpaceCalculator reserved; @BeforeEach public void setUp() { conf = new Configuration(); usage = Mockito.mock(DF.class); } @Test public void testReservedSpaceAbsolute() { conf.setClass(DFS_DATANODE_DU_RESERVED_CALCULATOR_KEY, ReservedSpaceCalculatorAbsolute.class, ReservedSpaceCalculator.class); // Test both using global configuration conf.setLong(DFS_DATANODE_DU_RESERVED_KEY, 900); checkReserved(StorageType.DISK, 10000, 900); checkReserved(StorageType.SSD, 10000, 900); checkReserved(StorageType.ARCHIVE, 10000, 900); checkReserved(StorageType.NVDIMM, 10000, 900); } @Test public void testReservedSpaceAbsolutePerStorageType() { conf.setClass(DFS_DATANODE_DU_RESERVED_CALCULATOR_KEY, ReservedSpaceCalculatorAbsolute.class, ReservedSpaceCalculator.class); // Test DISK conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + ".disk", 500); checkReserved(StorageType.DISK, 2300, 500); // Test SSD conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + ".ssd", 750); checkReserved(StorageType.SSD, 1550, 750); // Test NVDIMM conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + ".nvdimm", 300); checkReserved(StorageType.NVDIMM, 1000, 300); } @Test public void testReservedSpacePercentage() { conf.setClass(DFS_DATANODE_DU_RESERVED_CALCULATOR_KEY, ReservedSpaceCalculatorPercentage.class, ReservedSpaceCalculator.class); // Test both using global configuration conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY, 10); checkReserved(StorageType.DISK, 10000, 1000); checkReserved(StorageType.SSD, 10000, 1000); checkReserved(StorageType.ARCHIVE, 10000, 1000); checkReserved(StorageType.NVDIMM, 10000, 1000); conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY, 50); checkReserved(StorageType.DISK, 4000, 2000); checkReserved(StorageType.SSD, 4000, 2000); checkReserved(StorageType.ARCHIVE, 4000, 2000); checkReserved(StorageType.NVDIMM, 4000, 2000); } @Test public void testReservedSpacePercentagePerStorageType() { conf.setClass(DFS_DATANODE_DU_RESERVED_CALCULATOR_KEY, ReservedSpaceCalculatorPercentage.class, ReservedSpaceCalculator.class); // Test DISK conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + ".disk", 20); checkReserved(StorageType.DISK, 1600, 320); // Test SSD conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + ".ssd", 50); checkReserved(StorageType.SSD, 8001, 4000); // Test NVDIMM conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + ".nvdimm", 30); checkReserved(StorageType.NVDIMM, 1000, 300); } @Test public void testReservedSpaceConservativePerStorageType() { // This policy should take the maximum of the two conf.setClass(DFS_DATANODE_DU_RESERVED_CALCULATOR_KEY, ReservedSpaceCalculatorConservative.class, ReservedSpaceCalculator.class); // Test DISK + taking the reserved bytes over percentage, // as that gives more reserved space conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + ".disk", 800); conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + ".disk", 20); checkReserved(StorageType.DISK, 1600, 800); // Test ARCHIVE + taking reserved space based on the percentage, // as that gives more reserved space conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + ".archive", 1300); conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + ".archive", 50); checkReserved(StorageType.ARCHIVE, 6200, 3100); // Test NVDIMM + taking reserved space based on the percentage, // as that gives more reserved space conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + ".nvdimm", 500); conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + ".nvdimm", 20); checkReserved(StorageType.NVDIMM, 3000, 600); } @Test public void testReservedSpaceAggresivePerStorageType() { // This policy should take the maximum of the two conf.setClass(DFS_DATANODE_DU_RESERVED_CALCULATOR_KEY, ReservedSpaceCalculatorAggressive.class, ReservedSpaceCalculator.class); // Test RAM_DISK + taking the reserved bytes over percentage, // as that gives less reserved space conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + ".ram_disk", 100); conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + ".ram_disk", 10); checkReserved(StorageType.RAM_DISK, 1600, 100); // Test ARCHIVE + taking reserved space based on the percentage, // as that gives less reserved space conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + ".archive", 20000); conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + ".archive", 5); checkReserved(StorageType.ARCHIVE, 100000, 5000); } @Test public void testReservedSpaceAbsolutePerDir() { conf.setClass(DFS_DATANODE_DU_RESERVED_CALCULATOR_KEY, ReservedSpaceCalculatorAbsolute.class, ReservedSpaceCalculator.class); String dir1 = "/data/hdfs1/data"; String dir2 = "/data/hdfs2/data"; String dir3 = "/data/hdfs3/data"; conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + "." + dir1 + ".ssd", 900); conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + "." + dir1, 1800); conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + "." + dir2, 2700); conf.setLong(DFS_DATANODE_DU_RESERVED_KEY + ".ssd", 3600); conf.setLong(DFS_DATANODE_DU_RESERVED_KEY, 4500); checkReserved(StorageType.SSD, 10000, 900, dir1); checkReserved(StorageType.DISK, 10000, 1800, dir1); checkReserved(StorageType.SSD, 10000, 2700, dir2); checkReserved(StorageType.DISK, 10000, 2700, dir2); checkReserved(StorageType.SSD, 10000, 3600, dir3); checkReserved(StorageType.DISK, 10000, 4500, dir3); } @Test public void testReservedSpacePercentagePerDir() { conf.setClass(DFS_DATANODE_DU_RESERVED_CALCULATOR_KEY, ReservedSpaceCalculatorPercentage.class, ReservedSpaceCalculator.class); String dir1 = "/data/hdfs1/data"; String dir2 = "/data/hdfs2/data"; String dir3 = "/data/hdfs3/data"; // Set percentage reserved values for different directories conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + "." + dir1 + ".ssd", 20); conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + "." + dir1, 10); conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + "." + dir2, 25); conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY + ".ssd", 30); conf.setLong(DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY, 40); // Verify reserved space calculations for different directories and storage types checkReserved(StorageType.SSD, 10000, 2000, dir1); checkReserved(StorageType.DISK, 10000, 1000, dir1); checkReserved(StorageType.SSD, 10000, 2500, dir2); checkReserved(StorageType.DISK, 10000, 2500, dir2); checkReserved(StorageType.SSD, 10000, 3000, dir3); checkReserved(StorageType.DISK, 10000, 4000, dir3); } @Test public void testInvalidCalculator() { assertThrows(IllegalStateException.class, () -> { conf.set(DFS_DATANODE_DU_RESERVED_CALCULATOR_KEY, "INVALIDTYPE"); reserved = new ReservedSpaceCalculator.Builder(conf) .setUsage(usage) .setStorageType(StorageType.DISK) .build(); }); } private void checkReserved(StorageType storageType, long totalCapacity, long reservedExpected) { checkReserved(storageType, totalCapacity, reservedExpected, "NULL"); } private void checkReserved(StorageType storageType, long totalCapacity, long reservedExpected, String dir) { when(usage.getCapacity()).thenReturn(totalCapacity); reserved = new ReservedSpaceCalculator.Builder(conf).setUsage(usage) .setStorageType(storageType).setDir(dir).build(); assertEquals(reservedExpected, reserved.getReserved()); } }
TestReservedSpaceCalculator
java
apache__kafka
metadata/src/main/java/org/apache/kafka/image/node/ClusterImageBrokersNode.java
{ "start": 1002, "end": 2005 }
class ____ implements MetadataNode { /** * The name of this node. */ public static final String NAME = "brokers"; /** * The cluster image. */ private final ClusterImage image; public ClusterImageBrokersNode(ClusterImage image) { this.image = image; } @Override public Collection<String> childNames() { ArrayList<String> childNames = new ArrayList<>(); for (Integer brokerId : image.brokers().keySet()) { childNames.add(brokerId.toString()); } return childNames; } @Override public MetadataNode child(String name) { try { Integer brokerId = Integer.valueOf(name); BrokerRegistration registration = image.brokers().get(brokerId); if (registration == null) return null; return new MetadataLeafNode(registration.toString()); } catch (NumberFormatException e) { return null; } } }
ClusterImageBrokersNode
java
google__auto
value/src/test/java/com/google/auto/value/processor/NullablesTest.java
{ "start": 3410, "end": 3760 }
class ____ names begin with "no" do not mention @Nullable anywhere.", // All other methods do.", "package foo.bar;", "", "import " + Irrelevant.class.getCanonicalName() + ";", "import " + Nullable.class.getCanonicalName() + ";", "import java.util.List;", "", "abstract
whose
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2668/Issue2668Test.java
{ "start": 644, "end": 1870 }
class ____ { @ProcessorTest @WithClasses( Issue2668Mapper.class ) void shouldCompileCorrectlyWithAvailableConstructors() { } @ProcessorTest @WithClasses( Erroneous2668ListMapper.class ) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic( kind = Kind.ERROR, line = 21, message = "org.mapstruct.ap.test.bugs._2668.Erroneous2668ListMapper.MyArrayList" + " does not have an accessible copy or no-args constructor." ) } ) void errorExpectedBecauseCollectionIsNotUsable() { } @ProcessorTest @WithClasses( Erroneous2668MapMapper.class ) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic( kind = Kind.ERROR, line = 21, message = "org.mapstruct.ap.test.bugs._2668.Erroneous2668MapMapper.MyHashMap" + " does not have an accessible copy or no-args constructor." ) } ) void errorExpectedBecauseMapIsNotUsable() { } }
Issue2668Test
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/placement/csmappingrule/MappingRuleActions.java
{ "start": 1127, "end": 1543 }
class ____ { public static final String DEFAULT_QUEUE_VARIABLE = "%default"; /** * Utility class, hiding constructor. */ private MappingRuleActions() {} /** * PlaceToQueueAction represents a placement action, contains the pattern of * the queue name or path in which the path variables will be substituted * with the variable context's respective values. */ public static
MappingRuleActions
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxCallable.java
{ "start": 950, "end": 1576 }
class ____<T> extends Flux<T> implements Callable<T>, Fuseable, SourceProducer<T> { final Callable<@Nullable T> callable; FluxCallable(Callable<@Nullable T> callable) { this.callable = callable; } @Override public void subscribe(CoreSubscriber<? super T> actual) { actual.onSubscribe(new MonoCallable.MonoCallableSubscription<>(actual, callable)); } @Override public @Nullable T call() throws Exception { return callable.call(); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return SourceProducer.super.scanUnsafe(key); } }
FluxCallable
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/transforms/NullRetentionPolicyConfig.java
{ "start": 1187, "end": 2206 }
class ____ implements RetentionPolicyConfig { public static final ParseField NAME = new ParseField("null_retention_policy"); public static final NullRetentionPolicyConfig INSTANCE = new NullRetentionPolicyConfig(); private NullRetentionPolicyConfig() {} @Override public ActionRequestValidationException validate(ActionRequestValidationException validationException) { return null; } @Override public void checkForDeprecations(String id, NamedXContentRegistry namedXContentRegistry, Consumer<DeprecationIssue> onDeprecation) { throw new UnsupportedOperationException(); } @Override public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { throw new UnsupportedOperationException(); } @Override public String getWriteableName() { return NAME.getPreferredName(); } @Override public void writeTo(final StreamOutput out) throws IOException {} }
NullRetentionPolicyConfig
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/net/impl/VertxEventLoopGroup.java
{ "start": 3451, "end": 5417 }
class ____ { int count = 1; final EventLoop worker; EventLoopHolder(EventLoop worker) { this.worker = worker; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EventLoopHolder that = (EventLoopHolder) o; return Objects.equals(worker, that.worker); } @Override public int hashCode() { return Objects.hashCode(worker); } } // private final Set<EventExecutor> children = new Set<EventExecutor>() { @Override public Iterator<EventExecutor> iterator() { return new EventLoopIterator(workers.iterator()); } @Override public int size() { return workers.size(); } @Override public boolean isEmpty() { return workers.isEmpty(); } @Override public boolean contains(Object o) { return workers.contains(o); } @Override public Object[] toArray() { return workers.toArray(); } @Override public <T> T[] toArray(T[] a) { return workers.toArray(a); } @Override public boolean add(EventExecutor eventExecutor) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> c) { return workers.containsAll(c); } @Override public boolean addAll(Collection<? extends EventExecutor> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } }; private static final
EventLoopHolder
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/engine/cache/DiskLruCacheWrapper.java
{ "start": 520, "end": 6059 }
class ____ implements DiskCache { private static final String TAG = "DiskLruCacheWrapper"; private static final int APP_VERSION = 1; private static final int VALUE_COUNT = 1; private static DiskLruCacheWrapper wrapper; private final SafeKeyGenerator safeKeyGenerator; private final File directory; private final long maxSize; private final DiskCacheWriteLocker writeLocker = new DiskCacheWriteLocker(); private DiskLruCache diskLruCache; /** * Get a DiskCache in the given directory and size. If a disk cache has already been created with * a different directory and/or size, it will be returned instead and the new arguments will be * ignored. * * @param directory The directory for the disk cache * @param maxSize The max size for the disk cache * @return The new disk cache with the given arguments, or the current cache if one already exists * @deprecated Use {@link #create(File, long)} to create a new cache with the specified arguments. */ @SuppressWarnings("deprecation") @Deprecated public static synchronized DiskCache get(File directory, long maxSize) { // TODO calling twice with different arguments makes it return the cache for the same // directory, it's public! if (wrapper == null) { wrapper = new DiskLruCacheWrapper(directory, maxSize); } return wrapper; } /** * Create a new DiskCache in the given directory with a specified max size. * * @param directory The directory for the disk cache * @param maxSize The max size for the disk cache * @return The new disk cache with the given arguments */ @SuppressWarnings("deprecation") public static DiskCache create(File directory, long maxSize) { return new DiskLruCacheWrapper(directory, maxSize); } /** * @deprecated Do not extend this class. */ @Deprecated // Deprecated public API. @SuppressWarnings({"WeakerAccess", "DeprecatedIsStillUsed"}) protected DiskLruCacheWrapper(File directory, long maxSize) { this.directory = directory; this.maxSize = maxSize; this.safeKeyGenerator = new SafeKeyGenerator(); } private synchronized DiskLruCache getDiskCache() throws IOException { if (diskLruCache == null) { diskLruCache = DiskLruCache.open(directory, APP_VERSION, VALUE_COUNT, maxSize); } return diskLruCache; } @Override public File get(Key key) { String safeKey = safeKeyGenerator.getSafeKey(key); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Get: Obtained: " + safeKey + " for for Key: " + key); } File result = null; try { // It is possible that the there will be a put in between these two gets. If so that shouldn't // be a problem because we will always put the same value at the same key so our input streams // will still represent the same data. final DiskLruCache.Value value = getDiskCache().get(safeKey); if (value != null) { result = value.getFile(0); } } catch (IOException e) { if (Log.isLoggable(TAG, Log.WARN)) { Log.w(TAG, "Unable to get from disk cache", e); } } return result; } @Override public void put(Key key, Writer writer) { // We want to make sure that puts block so that data is available when put completes. We may // actually not write any data if we find that data is written by the time we acquire the lock. String safeKey = safeKeyGenerator.getSafeKey(key); writeLocker.acquire(safeKey); try { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Put: Obtained: " + safeKey + " for for Key: " + key); } try { // We assume we only need to put once, so if data was written while we were trying to get // the lock, we can simply abort. DiskLruCache diskCache = getDiskCache(); Value current = diskCache.get(safeKey); if (current != null) { return; } DiskLruCache.Editor editor = diskCache.edit(safeKey); if (editor == null) { throw new IllegalStateException("Had two simultaneous puts for: " + safeKey); } try { File file = editor.getFile(0); if (writer.write(file)) { editor.commit(); } } finally { editor.abortUnlessCommitted(); } } catch (IOException e) { if (Log.isLoggable(TAG, Log.WARN)) { Log.w(TAG, "Unable to put to disk cache", e); } } } finally { writeLocker.release(safeKey); } } @Override public void delete(Key key) { String safeKey = safeKeyGenerator.getSafeKey(key); try { getDiskCache().remove(safeKey); } catch (IOException e) { if (Log.isLoggable(TAG, Log.WARN)) { Log.w(TAG, "Unable to delete from disk cache", e); } } } @Override public synchronized void clear() { try { getDiskCache().delete(); } catch (IOException e) { if (Log.isLoggable(TAG, Log.WARN)) { Log.w(TAG, "Unable to clear disk cache or disk cache cleared externally", e); } } finally { // Delete can close the cache but still throw. If we don't null out the disk cache here, every // subsequent request will try to act on a closed disk cache and fail. By nulling out the disk // cache we at least allow for attempts to open the cache in the future. See #2465. resetDiskCache(); } } private synchronized void resetDiskCache() { diskLruCache = null; } }
DiskLruCacheWrapper
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/cat/RestCatDataFrameAnalyticsAction.java
{ "start": 1687, "end": 8919 }
class ____ extends AbstractCatAction { @Override public List<Route> routes() { return List.of( new Route(GET, "_cat/ml/data_frame/analytics/{" + DataFrameAnalyticsConfig.ID + "}"), new Route(GET, "_cat/ml/data_frame/analytics") ); } @Override public String getName() { return "cat_ml_get_data_frame_analytics_action"; } @Override protected RestChannelConsumer doCatRequest(RestRequest restRequest, NodeClient client) { String dataFrameAnalyticsId = restRequest.param(DataFrameAnalyticsConfig.ID.getPreferredName()); if (Strings.isNullOrEmpty(dataFrameAnalyticsId)) { dataFrameAnalyticsId = Metadata.ALL; } GetDataFrameAnalyticsAction.Request getRequest = new GetDataFrameAnalyticsAction.Request(dataFrameAnalyticsId); getRequest.setAllowNoResources( restRequest.paramAsBoolean( GetDataFrameAnalyticsAction.Request.ALLOW_NO_MATCH.getPreferredName(), getRequest.isAllowNoResources() ) ); GetDataFrameAnalyticsStatsAction.Request getStatsRequest = new GetDataFrameAnalyticsStatsAction.Request(dataFrameAnalyticsId); getStatsRequest.setAllowNoMatch(true); return channel -> client.execute(GetDataFrameAnalyticsAction.INSTANCE, getRequest, new RestActionListener<>(channel) { @Override public void processResponse(GetDataFrameAnalyticsAction.Response getResponse) { client.execute(GetDataFrameAnalyticsStatsAction.INSTANCE, getStatsRequest, new RestResponseListener<>(channel) { @Override public RestResponse buildResponse(GetDataFrameAnalyticsStatsAction.Response getStatsResponse) throws Exception { return RestTable.buildResponse(buildTable(getResponse, getStatsResponse), channel); } }); } }); } @Override protected void documentation(StringBuilder sb) { sb.append("/_cat/ml/data_frame/analytics\n"); sb.append("/_cat/ml/data_frame/analytics/{").append(DataFrameAnalyticsConfig.ID.getPreferredName()).append("}\n"); } @Override protected Table getTableWithHeader(RestRequest unused) { return getTableWithHeader(); } private static Table getTableWithHeader() { return new Table().startHeaders() // DFA config info .addCell("id", TableColumnAttributeBuilder.builder("the id").build()) .addCell("type", TableColumnAttributeBuilder.builder("analysis type").setAliases("t").build()) .addCell("create_time", TableColumnAttributeBuilder.builder("job creation time").setAliases("ct", "createTime").build()) .addCell( "version", TableColumnAttributeBuilder.builder("the version of Elasticsearch when the analytics was created", false) .setAliases("v") .build() ) .addCell("source_index", TableColumnAttributeBuilder.builder("source index", false).setAliases("si", "sourceIndex").build()) .addCell("dest_index", TableColumnAttributeBuilder.builder("destination index", false).setAliases("di", "destIndex").build()) .addCell("description", TableColumnAttributeBuilder.builder("description", false).setAliases("d").build()) .addCell( "model_memory_limit", TableColumnAttributeBuilder.builder("model memory limit", false).setAliases("mml", "modelMemoryLimit").build() ) // DFA stats info .addCell( "state", TableColumnAttributeBuilder.builder("job state") .setAliases("s") .setTextAlignment(TableColumnAttributeBuilder.TextAlign.RIGHT) .build() ) .addCell( "failure_reason", TableColumnAttributeBuilder.builder("failure reason", false).setAliases("fr", "failureReason").build() ) .addCell("progress", TableColumnAttributeBuilder.builder("progress", false).setAliases("p").build()) .addCell( "assignment_explanation", TableColumnAttributeBuilder.builder("why the job is or is not assigned to a node", false) .setAliases("ae", "assignmentExplanation") .build() ) // Node info .addCell("node.id", TableColumnAttributeBuilder.builder("id of the assigned node", false).setAliases("ni", "nodeId").build()) .addCell( "node.name", TableColumnAttributeBuilder.builder("name of the assigned node", false).setAliases("nn", "nodeName").build() ) .addCell( "node.ephemeral_id", TableColumnAttributeBuilder.builder("ephemeral id of the assigned node", false).setAliases("ne", "nodeEphemeralId").build() ) .addCell( "node.address", TableColumnAttributeBuilder.builder("network address of the assigned node", false).setAliases("na", "nodeAddress").build() ) .endHeaders(); } private static Table buildTable( GetDataFrameAnalyticsAction.Response getResponse, GetDataFrameAnalyticsStatsAction.Response getStatsResponse ) { Map<String, Stats> statsById = getStatsResponse.getResponse().results().stream().collect(toMap(Stats::getId, Function.identity())); Table table = getTableWithHeader(); for (DataFrameAnalyticsConfig config : getResponse.getResources().results()) { Stats stats = statsById.get(config.getId()); DiscoveryNode node = stats == null ? null : stats.getNode(); table.startRow() .addCell(config.getId()) .addCell(config.getAnalysis().getWriteableName()) .addCell(config.getCreateTime()) .addCell(config.getVersion()) .addCell(String.join(",", config.getSource().getIndex())) .addCell(config.getDest().getIndex()) .addCell(config.getDescription()) .addCell(config.getModelMemoryLimit()) .addCell(stats == null ? null : stats.getState()) .addCell(stats == null ? null : stats.getFailureReason()) .addCell(stats == null ? null : progressToString(stats.getProgress())) .addCell(stats == null ? null : stats.getAssignmentExplanation()) .addCell(node == null ? null : node.getId()) .addCell(node == null ? null : node.getName()) .addCell(node == null ? null : node.getEphemeralId()) .addCell(node == null ? null : node.getAddress().toString()) .endRow(); } return table; } private static String progressToString(List<PhaseProgress> phases) { return phases.stream().map(p -> p.getPhase() + ":" + p.getProgressPercent()).collect(joining(",")); } }
RestCatDataFrameAnalyticsAction
java
quarkusio__quarkus
extensions/micrometer/deployment/src/test/java/io/quarkus/micrometer/deployment/binder/StorkMetricsDisabledTest.java
{ "start": 391, "end": 1160 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withConfigurationResource("test-logging.properties") .overrideConfigKey("quarkus.micrometer.binder.stork.enabled", "false") .overrideConfigKey("quarkus.micrometer.binder-enabled-default", "false") .overrideConfigKey("quarkus.micrometer.registry-enabled-default", "false") .overrideConfigKey("quarkus.redis.devservices.enabled", "false") .withEmptyApplication(); @Inject Instance<ObservationCollector> bean; @Test void testNoInstancePresentIfNoRedisClientsClass() { assertTrue(bean.isUnsatisfied(), "No Stork metrics bean"); } }
StorkMetricsDisabledTest
java
quarkusio__quarkus
test-framework/junit5-internal/src/main/java/io/quarkus/test/ClearCache.java
{ "start": 210, "end": 1942 }
class ____ { private static final Logger log = Logger.getLogger(ClearCache.class); public static void clearCaches() { clearAnnotationCache(); clearResourceManagerPropertiesCache(); clearBeansIntrospectorCache(); } private static void clearAnnotationCache() { clearMap(AnnotationUtils.class, "repeatableAnnotationContainerCache"); } /** * This will only be effective if the tests are launched with --add-opens java.naming/com.sun.naming.internal=ALL-UNNAMED, * which is the case in the Quarkus codebase where memory usage is actually an issue. * <p> * While not mandatory, this actually helps so enabling it only in the Quarkus codebase has actual value. */ private static void clearResourceManagerPropertiesCache() { try { clearMap(Class.forName("com.sun.naming.internal.ResourceManager"), "propertiesCache"); } catch (ClassNotFoundException e) { // ignore log.debug("Unable to load com.sun.naming.internal.ResourceManager", e); } } private static void clearBeansIntrospectorCache() { try { Introspector.flushCaches(); } catch (Exception e) { // ignore log.debug("Failed to clear java.beans.Introspector cache", e); } } private static void clearMap(Class<?> clazz, String mapField) { try { Field f = clazz.getDeclaredField(mapField); f.setAccessible(true); ((Map) (f.get(null))).clear(); } catch (Exception e) { // ignore log.debugf(e, "Failed to clear cache for %s#%s cache", clazz.getName(), mapField); } } }
ClearCache
java
apache__camel
components/camel-paho/src/main/java/org/apache/camel/component/paho/PahoComponent.java
{ "start": 1226, "end": 2538 }
class ____ extends DefaultComponent { @Metadata private PahoConfiguration configuration = new PahoConfiguration(); @Metadata(label = "advanced") private MqttClient client; public PahoComponent() { this(null); } public PahoComponent(CamelContext context) { super(context); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { // Each endpoint can have its own configuration so make // a copy of the configuration PahoConfiguration pahoConfiguration = getConfiguration().copy(); PahoEndpoint answer = new PahoEndpoint(uri, remaining, this, pahoConfiguration); answer.setClient(client); setProperties(answer, parameters); return answer; } public PahoConfiguration getConfiguration() { return configuration; } /** * To use the shared Paho configuration */ public void setConfiguration(PahoConfiguration configuration) { this.configuration = configuration; } public MqttClient getClient() { return client; } /** * To use a shared Paho client */ public void setClient(MqttClient client) { this.client = client; } }
PahoComponent
java
spring-projects__spring-boot
integration-test/spring-boot-actuator-integration-tests/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java
{ "start": 29858, "end": 30003 }
class ____ { @ReadOperation String readReturningNull() { return null; } } @Endpoint(id = "nulldelete") static
NullReadResponseEndpoint
java
netty__netty
codec-native-quic/src/test/java/io/netty/handler/codec/quic/QuicCodecBuilderTest.java
{ "start": 967, "end": 2896 }
class ____ { @Test void testCopyConstructor() throws IllegalAccessException { TestQuicCodecBuilder original = new TestQuicCodecBuilder(); init(original); TestQuicCodecBuilder copy = new TestQuicCodecBuilder(original); assertThat(copy).usingRecursiveComparison().isEqualTo(original); } private static void init(TestQuicCodecBuilder builder) throws IllegalAccessException { Field[] fields = builder.getClass().getSuperclass().getDeclaredFields(); for (Field field : fields) { modifyField(builder, field); } } private static void modifyField(TestQuicCodecBuilder builder, Field field) throws IllegalAccessException { field.setAccessible(true); Class<?> clazz = field.getType(); if (Boolean.class == clazz) { field.set(builder, Boolean.TRUE); } else if (Integer.class == clazz) { field.set(builder, Integer.MIN_VALUE); } else if (Long.class == clazz) { field.set(builder, Long.MIN_VALUE); } else if (QuicCongestionControlAlgorithm.class == clazz) { field.set(builder, QuicCongestionControlAlgorithm.CUBIC); } else if (FlushStrategy.class == clazz) { field.set(builder, FlushStrategy.afterNumBytes(10)); } else if (Function.class == clazz) { field.set(builder, Function.identity()); } else if (boolean.class == clazz) { field.setBoolean(builder, true); } else if (int.class == clazz) { field.setInt(builder, -1); } else if (byte[].class == clazz) { field.set(builder, new byte[16]); } else if (Executor.class == clazz) { field.set(builder, ImmediateExecutor.INSTANCE); } else { throw new IllegalArgumentException("Unknown field type " + clazz); } } private static final
QuicCodecBuilderTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/integration/MockitoBeanWithMultipleExistingBeansAndOnePrimaryAndOneConflictingQualifierIntegrationTests.java
{ "start": 2979, "end": 3195 }
class ____ { private final BaseService baseService; public Client(BaseService baseService) { this.baseService = baseService; } public void callService() { this.baseService.doSomething(); } } }
Client
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/jdk/AtomicTypeSerializationTest.java
{ "start": 1525, "end": 1877 }
class ____ { public AtomicReference<Date> date; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy+MM+dd") public AtomicReference<Date> date1; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy*MM*dd") public AtomicReference<Date> date2; } // [databind#1673] static
ContextualOptionals
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/ExecutionDeploymentReconciliationHandler.java
{ "start": 1088, "end": 1881 }
interface ____ { /** * Called if some executions are expected to be hosted on a task executor, but aren't. * * @param executionAttemptIds ids of the missing deployments * @param hostingTaskExecutor expected hosting task executor */ void onMissingDeploymentsOf( Collection<ExecutionAttemptID> executionAttemptIds, ResourceID hostingTaskExecutor); /** * Called if some executions are hosted on a task executor, but we don't expect them. * * @param executionAttemptIds ids of the unknown executions * @param hostingTaskExecutor hosting task executor */ void onUnknownDeploymentsOf( Collection<ExecutionAttemptID> executionAttemptIds, ResourceID hostingTaskExecutor); }
ExecutionDeploymentReconciliationHandler
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/action/TransportUpdateConnectorNativeAction.java
{ "start": 817, "end": 1814 }
class ____ extends HandledTransportAction< UpdateConnectorNativeAction.Request, ConnectorUpdateActionResponse> { protected final ConnectorIndexService connectorIndexService; @Inject public TransportUpdateConnectorNativeAction(TransportService transportService, ActionFilters actionFilters, Client client) { super( UpdateConnectorNativeAction.NAME, transportService, actionFilters, UpdateConnectorNativeAction.Request::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.connectorIndexService = new ConnectorIndexService(client); } @Override protected void doExecute( Task task, UpdateConnectorNativeAction.Request request, ActionListener<ConnectorUpdateActionResponse> listener ) { connectorIndexService.updateConnectorNative(request, listener.map(r -> new ConnectorUpdateActionResponse(r.getResult()))); } }
TransportUpdateConnectorNativeAction
java
grpc__grpc-java
alts/src/main/java/io/grpc/alts/internal/AltsFraming.java
{ "start": 2540, "end": 2582 }
class ____ write a frame. * * <p>This
to
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/matching/SpecificResource.java
{ "start": 251, "end": 416 }
class ____ { @GET @Produces(MediaType.TEXT_PLAIN) public String hello(@PathParam("id") String id) { return "specific:" + id; } }
SpecificResource
java
apache__dubbo
dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/FailoverCluster.java
{ "start": 1060, "end": 1332 }
class ____ extends AbstractCluster { public static final String NAME = "failover"; @Override public <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException { return new FailoverClusterInvoker<>(directory); } }
FailoverCluster
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/BeanDisposingRegistration.java
{ "start": 924, "end": 2061 }
class ____<BT> extends BeanRegistration<BT> { private final BeanContext beanContext; private final List<BeanRegistration<?>> dependents; BeanDisposingRegistration(BeanContext beanContext, BeanIdentifier identifier, BeanDefinition<BT> beanDefinition, BT createdBean, List<BeanRegistration<?>> dependents) { super(identifier, beanDefinition, createdBean); this.beanContext = beanContext; this.dependents = dependents; } BeanDisposingRegistration(BeanContext beanContext, BeanIdentifier identifier, BeanDefinition<BT> beanDefinition, BT createdBean) { super(identifier, beanDefinition, createdBean); this.beanContext = beanContext; this.dependents = null; } @Override public void close() { beanContext.destroyBean(this); } public List<BeanRegistration<?>> getDependents() { return dependents; } }
BeanDisposingRegistration
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/ProcessTableFunction.java
{ "start": 19131, "end": 20359 }
class ____<T> extends UserDefinedFunction { /** The code generated collector used to emit rows. */ private transient Collector<T> collector; /** Internal use. Sets the current collector. */ public final void setCollector(Collector<T> collector) { this.collector = collector; } /** * Emits an (implicit or explicit) output row. * * <p>If null is emitted as an explicit row, it will be skipped by the runtime. For implicit * rows, the row's field will be null. * * @param row the output row */ protected final void collect(T row) { collector.collect(row); } @Override public final FunctionKind getKind() { return FunctionKind.PROCESS_TABLE; } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public TypeInference getTypeInference(DataTypeFactory typeFactory) { return TypeInferenceExtractor.forProcessTableFunction(typeFactory, (Class) getClass()); } /** * Context that can be added as a first argument to the eval() method for additional information * about the input tables and other services provided by the framework. */ @PublicEvolving public
ProcessTableFunction
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/ClassTemplateInvocationContextProvider.java
{ "start": 4236, "end": 4683 }
class ____ represented by the supplied {@code context}. * * <p>If this method returns {@code false} (which is the default) and the * provider returns an empty stream from * {@link #provideClassTemplateInvocationContexts}, this will be considered * an execution error. Override this method to return {@code true} to ignore * the absence of invocation contexts for this provider. * * @param context the extension context for the
template
java
google__truth
extensions/liteproto/src/main/java/com/google/common/truth/extensions/proto/LiteProtoTruth.java
{ "start": 1055, "end": 1641 }
class ____ a subset of what {@code ProtoTruth} provides, so if you are already * using {@code ProtoTruth}, you should not import this class. {@code LiteProtoTruth} is only useful * if you cannot depend on {@code ProtoTruth} for dependency management reasons. * * <p>Note: Usage of different failure strategies such as <em>assume</em> and <em>expect</em> should * rely on {@linkplain com.google.common.truth.StandardSubjectBuilder#about(Subject.Factory) * about(liteProtos())} to begin a chain with those alternative behaviors. */ @CheckReturnValue @NullMarked public final
implements
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/mapping/condition/HeadersCondition.java
{ "start": 1078, "end": 3308 }
class ____ implements Condition<HeadersCondition, HttpRequest> { private final Set<NameValueExpression> expressions; public HeadersCondition(String... headers) { Set<NameValueExpression> expressions = null; if (headers != null) { for (String header : headers) { NameValueExpression expr = NameValueExpression.parse(header); String name = expr.getName(); if (HttpHeaderNames.ACCEPT.getName().equalsIgnoreCase(name) || HttpHeaderNames.CONTENT_TYPE.getName().equalsIgnoreCase(name)) { continue; } if (expressions == null) { expressions = new LinkedHashSet<>(); } expressions.add(expr); } } this.expressions = expressions == null ? Collections.emptySet() : expressions; } private HeadersCondition(Set<NameValueExpression> expressions) { this.expressions = expressions; } @Override public HeadersCondition combine(HeadersCondition other) { Set<NameValueExpression> set = new LinkedHashSet<>(expressions); set.addAll(other.expressions); return new HeadersCondition(set); } @Override public HeadersCondition match(HttpRequest request) { for (NameValueExpression expression : expressions) { if (!expression.match(request::hasHeader, request::header)) { return null; } } return this; } @Override public int compareTo(HeadersCondition other, HttpRequest request) { return other.expressions.size() - expressions.size(); } @Override public int hashCode() { return expressions.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || obj.getClass() != HeadersCondition.class) { return false; } return expressions.equals(((HeadersCondition) obj).expressions); } @Override public String toString() { return "HeadersCondition{headers=" + expressions + '}'; } }
HeadersCondition
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/multipart/PathFileDownload.java
{ "start": 224, "end": 1137 }
class ____ implements FileDownload { private final String partName; private final File file; public PathFileDownload(File file) { this(null, file); } public PathFileDownload(String partName, File file) { this.partName = partName; this.file = file; } @Override public String name() { return partName; } @Override public Path filePath() { return file.toPath(); } @Override public String fileName() { return file.getName(); } @Override public long size() { try { return Files.size(file.toPath()); } catch (IOException e) { throw new RuntimeException("Failed to get size", e); } } @Override public String contentType() { return null; } @Override public String charSet() { return null; } }
PathFileDownload
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ParametersButNotParameterized.java
{ "start": 1656, "end": 2704 }
class ____ extends BugChecker implements ClassTreeMatcher { private static final String PARAMETERIZED = "org.junit.runners.Parameterized"; private static final String PARAMETER = "org.junit.runners.Parameterized.Parameter"; private static final String PARAMETERS = "org.junit.runners.Parameterized.Parameters"; @Override public Description matchClass(ClassTree tree, VisitorState state) { if (!hasJUnit4TestRunner.matches(tree, state)) { return NO_MATCH; } if (tree.getMembers().stream() .noneMatch( m -> hasAnnotation(m, PARAMETER, state) || hasAnnotation(m, PARAMETERS, state))) { return NO_MATCH; } AnnotationTree annotation = getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "RunWith"); SuggestedFix.Builder fix = SuggestedFix.builder(); fix.replace( annotation, String.format("@RunWith(%s.class)", SuggestedFixes.qualifyType(state, fix, PARAMETERIZED))); return describeMatch(tree, fix.build()); } }
ParametersButNotParameterized
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/long_/LongAssert_isNotEqualTo_long_Test.java
{ "start": 884, "end": 1201 }
class ____ extends LongAssertBaseTest { @Override protected LongAssert invoke_api_method() { return assertions.isNotEqualTo(8L); } @Override protected void verify_internal_effects() { verify(longs).assertNotEqual(getInfo(assertions), getActual(assertions), 8L); } }
LongAssert_isNotEqualTo_long_Test
java
apache__camel
components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/QueueReplyManager.java
{ "start": 2806, "end": 5069 }
class ____ implements DestinationCreationStrategy { private final DestinationCreationStrategy delegate; private Destination destination; DestinationResolverDelegate(DestinationCreationStrategy delegate) { this.delegate = delegate; } @Override public Destination createDestination(Session session, String destinationName, boolean topic) throws JMSException { QueueReplyManager.this.lock.lock(); try { // resolve the reply to destination if (destination == null) { destination = delegate.createDestination(session, destinationName, topic); setReplyTo(destination); } } finally { QueueReplyManager.this.lock.unlock(); } return destination; } @Override public Destination createTemporaryDestination(Session session, boolean topic) { return null; } } @Override protected MessageListenerContainer createListenerContainer() throws Exception { SimpleMessageListenerContainer answer; ReplyToType type = endpoint.getReplyToType(); if (type == null) { // use exclusive by default for reply queues type = ReplyToType.Exclusive; } if (ReplyToType.Exclusive == type) { answer = new ExclusiveQueueMessageListenerContainer(endpoint); log.debug("Using exclusive queue: {} as reply listener: {}", endpoint.getReplyTo(), answer); } else { throw new IllegalArgumentException("ReplyToType " + type + " is not supported for reply queues"); } answer.setMessageListener(this); answer.setConcurrentConsumers(endpoint.getReplyToConcurrentConsumers()); answer.setDestinationCreationStrategy(new DestinationResolverDelegate(endpoint.getDestinationCreationStrategy())); answer.setDestinationName(endpoint.getReplyTo()); String clientId = endpoint.getClientId(); if (clientId != null) { clientId += ".CamelReplyManager"; answer.setClientId(clientId); } return answer; } }
DestinationResolverDelegate
java
quarkusio__quarkus
extensions/quartz/deployment/src/test/java/io/quarkus/quartz/test/InvalidMisfirePolicyTest.java
{ "start": 306, "end": 1114 }
class ____ { @RegisterExtension static final QuarkusUnitTest test = new QuarkusUnitTest() .setExpectedException(IllegalArgumentException.class) .withApplicationRoot((jar) -> jar .addClasses(MisfirePolicyTest.Jobs.class) .addAsResource(new StringAsset( "quarkus.quartz.misfire-policy.\"simple_invalid_misfire_policy\"=cron-trigger-do-nothing\n" + "quarkus.quartz.misfire-policy.\"cron_invalid_misfire_policy\"=simple-trigger-reschedule-now-with-existing-repeat-count\n"), "application.properties")); @Test public void shouldFailWhenInvalidMisfirePolicyConfiguration() { Assertions.fail(); } static
InvalidMisfirePolicyTest
java
apache__flink
flink-table/flink-sql-parser/src/main/java/org/apache/flink/sql/parser/ddl/SqlAlterTableOptions.java
{ "start": 1442, "end": 2922 }
class ____ extends SqlAlterTable { private final SqlNodeList propertyList; public SqlAlterTableOptions( SqlParserPos pos, SqlIdentifier tableName, SqlNodeList propertyList, boolean ifTableExists) { this(pos, tableName, null, propertyList, ifTableExists); } public SqlAlterTableOptions( SqlParserPos pos, SqlIdentifier tableName, SqlNodeList partitionSpec, SqlNodeList propertyList) { this(pos, tableName, partitionSpec, propertyList, false); } public SqlAlterTableOptions( SqlParserPos pos, SqlIdentifier tableName, SqlNodeList partitionSpec, SqlNodeList propertyList, boolean ifTableExists) { super(pos, tableName, partitionSpec, ifTableExists); this.propertyList = requireNonNull(propertyList, "propertyList should not be null"); } @Override public List<SqlNode> getOperandList() { return ImmutableNullableList.of(tableIdentifier, propertyList); } public Map<String, String> getProperties() { return SqlParseUtils.extractMap(propertyList); } @Override public void unparseAlterOperation(SqlWriter writer, int leftPrec, int rightPrec) { super.unparseAlterOperation(writer, leftPrec, rightPrec); SqlUnparseUtils.unparseSetOptions(propertyList, writer, leftPrec, rightPrec); } }
SqlAlterTableOptions
java
netty__netty
codec-http/src/test/java/io/netty/handler/codec/http/ReadOnlyHttpHeadersTest.java
{ "start": 1706, "end": 6771 }
class ____ { @Test public void getValue() { ReadOnlyHttpHeaders headers = new ReadOnlyHttpHeaders(true, ACCEPT, APPLICATION_JSON); assertFalse(headers.isEmpty()); assertEquals(1, headers.size()); assertTrue(APPLICATION_JSON.contentEquals(headers.get(ACCEPT))); assertTrue(headers.contains(ACCEPT)); assertNull(headers.get(CONTENT_LENGTH)); assertFalse(headers.contains(CONTENT_LENGTH)); } @Test public void charSequenceIterator() { ReadOnlyHttpHeaders headers = new ReadOnlyHttpHeaders(true, ACCEPT, APPLICATION_JSON, CONTENT_LENGTH, ZERO, CONNECTION, CLOSE); assertFalse(headers.isEmpty()); assertEquals(3, headers.size()); Iterator<Entry<CharSequence, CharSequence>> itr = headers.iteratorCharSequence(); assertTrue(itr.hasNext()); Entry<CharSequence, CharSequence> next = itr.next(); assertTrue(ACCEPT.contentEqualsIgnoreCase(next.getKey())); assertTrue(APPLICATION_JSON.contentEqualsIgnoreCase(next.getValue())); assertTrue(itr.hasNext()); next = itr.next(); assertTrue(CONTENT_LENGTH.contentEqualsIgnoreCase(next.getKey())); assertTrue(ZERO.contentEqualsIgnoreCase(next.getValue())); assertTrue(itr.hasNext()); next = itr.next(); assertTrue(CONNECTION.contentEqualsIgnoreCase(next.getKey())); assertTrue(CLOSE.contentEqualsIgnoreCase(next.getValue())); assertFalse(itr.hasNext()); } @Test public void stringIterator() { ReadOnlyHttpHeaders headers = new ReadOnlyHttpHeaders(true, ACCEPT, APPLICATION_JSON, CONTENT_LENGTH, ZERO, CONNECTION, CLOSE); assertFalse(headers.isEmpty()); assertEquals(3, headers.size()); assert3ParisEquals(headers.iterator()); } @Test public void entries() { ReadOnlyHttpHeaders headers = new ReadOnlyHttpHeaders(true, ACCEPT, APPLICATION_JSON, CONTENT_LENGTH, ZERO, CONNECTION, CLOSE); assertFalse(headers.isEmpty()); assertEquals(3, headers.size()); assert3ParisEquals(headers.entries().iterator()); } @Test public void names() { ReadOnlyHttpHeaders headers = new ReadOnlyHttpHeaders(true, ACCEPT, APPLICATION_JSON, CONTENT_LENGTH, ZERO, CONNECTION, CLOSE); assertFalse(headers.isEmpty()); assertEquals(3, headers.size()); Set<String> names = headers.names(); assertEquals(3, names.size()); assertTrue(names.contains(ACCEPT.toString())); assertTrue(names.contains(CONTENT_LENGTH.toString())); assertTrue(names.contains(CONNECTION.toString())); } @Test public void getAll() { ReadOnlyHttpHeaders headers = new ReadOnlyHttpHeaders(false, ACCEPT, APPLICATION_JSON, CONTENT_LENGTH, ZERO, ACCEPT, APPLICATION_OCTET_STREAM); assertFalse(headers.isEmpty()); assertEquals(3, headers.size()); List<String> names = headers.getAll(ACCEPT); assertEquals(2, names.size()); assertTrue(APPLICATION_JSON.contentEqualsIgnoreCase(names.get(0))); assertTrue(APPLICATION_OCTET_STREAM.contentEqualsIgnoreCase(names.get(1))); } @Test public void validateNamesFail() { assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() { new ReadOnlyHttpHeaders(true, ACCEPT, APPLICATION_JSON, AsciiString.cached(" ")); } }); } @Test public void emptyHeaderName() { assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() { new ReadOnlyHttpHeaders(true, ACCEPT, APPLICATION_JSON, AsciiString.cached(" "), ZERO); } }); } @Test public void headerWithoutValue() { assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() { new ReadOnlyHttpHeaders(false, ACCEPT, APPLICATION_JSON, CONTENT_LENGTH); } }); } private static void assert3ParisEquals(Iterator<Entry<String, String>> itr) { assertTrue(itr.hasNext()); Entry<String, String> next = itr.next(); assertTrue(ACCEPT.contentEqualsIgnoreCase(next.getKey())); assertTrue(APPLICATION_JSON.contentEqualsIgnoreCase(next.getValue())); assertTrue(itr.hasNext()); next = itr.next(); assertTrue(CONTENT_LENGTH.contentEqualsIgnoreCase(next.getKey())); assertTrue(ZERO.contentEqualsIgnoreCase(next.getValue())); assertTrue(itr.hasNext()); next = itr.next(); assertTrue(CONNECTION.contentEqualsIgnoreCase(next.getKey())); assertTrue(CLOSE.contentEqualsIgnoreCase(next.getValue())); assertFalse(itr.hasNext()); } }
ReadOnlyHttpHeadersTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/TimerAndErrorHandlerIssueTest.java
{ "start": 1070, "end": 1901 }
class ____ extends ContextTestSupport { @Test public void testTimerAndErrorHandler() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(2); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { onException(RuntimeCamelException.class).handled(true); errorHandler(defaultErrorHandler()); String executionTriggerUri = "timer:executionTimer" + "?fixedRate=true" + "&daemon=true" + "&delay=0" + "&period=10"; from(executionTriggerUri).to("mock:result"); } }; } }
TimerAndErrorHandlerIssueTest