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
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/util/TestResourceCalculatorProcessTree.java
{ "start": 1179, "end": 2647 }
class ____ extends ResourceCalculatorProcessTree { public EmptyProcessTree(String pid) { super(pid); } public void updateProcessTree() { } public String getProcessTreeDump() { return "Empty tree for testing"; } public long getRssMemorySize(int age) { return 0; } @SuppressWarnings("deprecation") public long getCumulativeRssmem(int age) { return 0; } public long getVirtualMemorySize(int age) { return 0; } @SuppressWarnings("deprecation") public long getCumulativeVmem(int age) { return 0; } public long getCumulativeCpuTime() { return 0; } @Override public float getCpuUsagePercent() { return UNAVAILABLE; } public boolean checkPidPgrpidForMatch() { return false; } } @Test void testCreateInstance() { ResourceCalculatorProcessTree tree; tree = ResourceCalculatorProcessTree.getResourceCalculatorProcessTree("1", EmptyProcessTree.class, new Configuration()); assertNotNull(tree); assertThat(tree).isInstanceOf(EmptyProcessTree.class); } @Test void testCreatedInstanceConfigured() { ResourceCalculatorProcessTree tree; Configuration conf = new Configuration(); tree = ResourceCalculatorProcessTree.getResourceCalculatorProcessTree("1", EmptyProcessTree.class, conf); assertNotNull(tree); assertThat(tree).isInstanceOf(EmptyProcessTree.class); } }
EmptyProcessTree
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/metadata/IndexNameExpressionResolver.java
{ "start": 119199, "end": 119686 }
class ____ collect the system access relevant code. The helper methods provide the following functionalities: * - determining the access to a system index abstraction * - verifying the access to system abstractions and adding the necessary warnings * - determining the access to a system index based on its name * WARNING: we have observed differences in how the access is determined. For now this behaviour is documented and preserved. */ public static final
we
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/resource/bitmap/ByteBufferBitmapImageDecoderResourceDecoder.java
{ "start": 583, "end": 1198 }
class ____ implements ResourceDecoder<ByteBuffer, Bitmap> { private final BitmapImageDecoderResourceDecoder wrapped = new BitmapImageDecoderResourceDecoder(); @Override public boolean handles(@NonNull ByteBuffer source, @NonNull Options options) throws IOException { return true; } @Override public Resource<Bitmap> decode( @NonNull ByteBuffer buffer, int width, int height, @NonNull Options options) throws IOException { Source source = ImageDecoder.createSource(buffer); return wrapped.decode(source, width, height, options); } }
ByteBufferBitmapImageDecoderResourceDecoder
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/unix/DomainSocketWatcher.java
{ "start": 4379, "end": 4894 }
class ____ { final DomainSocket socket; final Handler handler; Entry(DomainSocket socket, Handler handler) { this.socket = socket; this.handler = handler; } DomainSocket getDomainSocket() { return socket; } Handler getHandler() { return handler; } } /** * The FdSet is a set of file descriptors that gets passed to poll(2). * It contains a native memory segment, so that we don't have to copy * in the poll0 function. */ private static
Entry
java
google__guava
android/guava-tests/test/com/google/common/base/PackageSanityTests.java
{ "start": 898, "end": 1112 }
class ____ extends AbstractPackageSanityTests { public PackageSanityTests() { // package private classes like FunctionalEquivalence are tested through the public API. publicApiOnly(); } }
PackageSanityTests
java
apache__camel
components/camel-pulsar/src/test/java/org/apache/camel/component/pulsar/integration/PulsarProducerInIT.java
{ "start": 1620, "end": 4593 }
class ____ extends PulsarITSupport { private static final String TOPIC_URI = "persistent://public/default/camel-producer-topic"; private static final String PRODUCER = "camel-producer"; @Produce("direct:start") private ProducerTemplate producerTemplate; @Produce("direct:start1") private ProducerTemplate producerTemplate1; @EndpointInject("pulsar:" + TOPIC_URI + "?numberOfConsumers=1&subscriptionType=Exclusive" + "&subscriptionName=camel-subscription&consumerQueueSize=1" + "&consumerName=camel-consumer" + "&producerName=" + PRODUCER) private Endpoint from; @EndpointInject("pulsar:" + TOPIC_URI + "1?numberOfConsumers=1&subscriptionType=Exclusive" + "&subscriptionName=camel-subscription&consumerQueueSize=1" + "&batchingEnabled=false" + "&chunkingEnabled=true" + "&consumerName=camel-consumer" + "&producerName=" + PRODUCER) private Endpoint from1; @EndpointInject("mock:result") private MockEndpoint to; @EndpointInject("mock:result1") private MockEndpoint to1; @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").to(from); from(from).to(to); from("direct:start1").to(from1); from(from1).to(to1); } }; } @Override protected void bindToRegistry(Registry registry) throws Exception { registerPulsarBeans(registry); } private void registerPulsarBeans(Registry registry) throws PulsarClientException { PulsarClient pulsarClient = givenPulsarClient(); registerPulsarBeans(registry, pulsarClient, context); } private PulsarClient givenPulsarClient() throws PulsarClientException { return new ClientBuilderImpl().serviceUrl(getPulsarBrokerUrl()).ioThreads(1).listenerThreads(1).build(); } @Test public void testAMessageToRouteIsSentAndThenConsumed() throws Exception { to.expectedMessageCount(3); producerTemplate.sendBody("Hello "); producerTemplate.sendBody("World "); producerTemplate.sendBody(10); MockEndpoint.assertIsSatisfied(10, TimeUnit.SECONDS, to); } @Test public void testLargeMessageWithChunkingDisabled() { Throwable e = assertThrows(CamelExecutionException.class, () -> producerTemplate.sendBody(new byte[10 * 1024 * 1024])); assertTrue(ExceptionUtils.getThrowableList(e).stream().anyMatch(ex -> ex instanceof PulsarClientException)); } @Test public void testLargeMessageWithChunkingEnabled() throws Exception { to1.expectedMessageCount(1); producerTemplate1.sendBody(new byte[10 * 1024 * 1024]); MockEndpoint.assertIsSatisfied(10, TimeUnit.SECONDS, to1); } }
PulsarProducerInIT
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/CachingDatabaseInformationImpl.java
{ "start": 1355, "end": 5062 }
class ____ extends DatabaseInformationImpl { private final Map<Namespace.Name, NamespaceCacheEntry> namespaceCacheEntries = new HashMap<>(); public CachingDatabaseInformationImpl( ServiceRegistry serviceRegistry, JdbcEnvironment jdbcEnvironment, SqlStringGenerationContext context, DdlTransactionIsolator ddlTransactionIsolator, SchemaManagementTool tool) throws SQLException { super( serviceRegistry, jdbcEnvironment, context, ddlTransactionIsolator, tool ); } @Override public @Nullable TableInformation locateTableInformation(QualifiedTableName tableName) { final var namespace = new Namespace.Name( tableName.getCatalogName(), tableName.getSchemaName() ); final var entry = namespaceCacheEntries.computeIfAbsent( namespace, k -> new NamespaceCacheEntry() ); NameSpaceTablesInformation nameSpaceTablesInformation = entry.tableInformation; if ( nameSpaceTablesInformation == null ) { nameSpaceTablesInformation = extractor.getTables( namespace.catalog(), namespace.schema() ); entry.tableInformation = nameSpaceTablesInformation; } return nameSpaceTablesInformation.getTableInformation( tableName.getTableName().getText() ); } @Override public @Nullable PrimaryKeyInformation locatePrimaryKeyInformation(QualifiedTableName tableName) { final var namespace = new Namespace.Name( tableName.getCatalogName(), tableName.getSchemaName() ); final var entry = namespaceCacheEntries.computeIfAbsent( namespace, k -> new NamespaceCacheEntry() ); NameSpacePrimaryKeysInformation nameSpaceTablesInformation = entry.primaryKeysInformation; if ( nameSpaceTablesInformation == null ) { nameSpaceTablesInformation = extractor.getPrimaryKeys( namespace.catalog(), namespace.schema() ); entry.primaryKeysInformation = nameSpaceTablesInformation; } return nameSpaceTablesInformation.getPrimaryKeyInformation( tableName.getTableName().getText() ); } @Override public Iterable<ForeignKeyInformation> locateForeignKeyInformation(QualifiedTableName tableName) { final var namespace = new Namespace.Name( tableName.getCatalogName(), tableName.getSchemaName() ); final var entry = namespaceCacheEntries.computeIfAbsent( namespace, k -> new NamespaceCacheEntry() ); NameSpaceForeignKeysInformation nameSpaceTablesInformation = entry.foreignKeysInformation; if ( nameSpaceTablesInformation == null ) { nameSpaceTablesInformation = extractor.getForeignKeys( namespace.catalog(), namespace.schema() ); entry.foreignKeysInformation = nameSpaceTablesInformation; } final List<ForeignKeyInformation> foreignKeysInformation = nameSpaceTablesInformation.getForeignKeysInformation( tableName.getTableName().getText() ); return foreignKeysInformation == null ? Collections.emptyList() : foreignKeysInformation; } @Override public Iterable<IndexInformation> locateIndexesInformation(QualifiedTableName tableName) { final var namespace = new Namespace.Name( tableName.getCatalogName(), tableName.getSchemaName() ); final var entry = namespaceCacheEntries.computeIfAbsent( namespace, k -> new NamespaceCacheEntry() ); NameSpaceIndexesInformation nameSpaceTablesInformation = entry.indexesInformation; if ( nameSpaceTablesInformation == null ) { nameSpaceTablesInformation = extractor.getIndexes( namespace.catalog(), namespace.schema() ); entry.indexesInformation = nameSpaceTablesInformation; } final List<IndexInformation> indexesInformation = nameSpaceTablesInformation.getIndexesInformation( tableName.getTableName().getText() ); return indexesInformation == null ? Collections.emptyList() : indexesInformation; } @Override public boolean isCaching() { return true; } private static
CachingDatabaseInformationImpl
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/input/BaseTestLineRecordReaderBZip2.java
{ "start": 11559, "end": 15251 }
class ____ { private final BaseLineRecordReaderHelper reader; private final long numBlocks; private final long[] countsIfSplitAtBlocks; private final long fileSize; private final long totalRecords; private final List<Long> nextBlockOffsets; RecordCountAssert( Path path, long[] countsIfSplitAtBlocks) throws IOException { this.reader = newReader(path); this.countsIfSplitAtBlocks = countsIfSplitAtBlocks; this.fileSize = getFileSize(path); this.totalRecords = Arrays.stream(countsIfSplitAtBlocks).sum(); this.numBlocks = countsIfSplitAtBlocks.length; this.nextBlockOffsets = BZip2Utils.getNextBlockMarkerOffsets(path, conf); assertEquals(numBlocks, nextBlockOffsets.size() + 1); } private void assertSingleSplit() throws IOException { assertEquals(totalRecords, reader.countRecords(0, fileSize)); } private void assertSplittingAtBlocks() throws IOException { assertSplits(getSplitsAtBlocks()); } private void assertSplittingJustAfterSecondBlockStarts() throws IOException { if (numBlocks <= 1) { return; } long recordsInFirstTwoBlocks = countsIfSplitAtBlocks[0] + countsIfSplitAtBlocks[1]; long remainingRecords = totalRecords - recordsInFirstTwoBlocks; long firstSplitSize = nextBlockOffsets.get(0) + 1; assertEquals( recordsInFirstTwoBlocks, reader.countRecords(0, firstSplitSize)); assertEquals( remainingRecords, reader.countRecords(firstSplitSize, fileSize - firstSplitSize)); } private void assertSplittingEachBlockRangeInThreeParts() throws IOException { for (SplitRange splitRange : getSplitsAtBlocks()) { long[] expectedNumRecordsPerPart = new long[] { splitRange.expectedNumRecords, 0, 0 }; List<SplitRange> parts = splitRange.divide(expectedNumRecordsPerPart); assertSplits(parts); } } private void assertSplitsAroundBlockStartOffsets() throws IOException { for (SplitRange split : getSplitsAtBlocks()) { assertSplit(split.withLength(1)); if (split.start > 0) { assertSplit(split.moveBy(-2).withLength(3)); assertSplit(split.moveBy(-2).withLength(2).withExpectedNumRecords(0)); assertSplit(split.moveBy(-1).withLength(2)); assertSplit(split.moveBy(-1).withLength(1).withExpectedNumRecords(0)); } assertSplit(split.moveBy(1).withLength(1).withExpectedNumRecords(0)); assertSplit(split.moveBy(2).withLength(1).withExpectedNumRecords(0)); } } private List<SplitRange> getSplitsAtBlocks() { List<SplitRange> splits = new ArrayList<>(); for (int i = 0; i < numBlocks; i++) { String name = "Block" + i; long start = i == 0 ? 0 : nextBlockOffsets.get(i - 1); long end = i == numBlocks - 1 ? fileSize : nextBlockOffsets.get(i); long length = end - start; long expectedNumRecords = countsIfSplitAtBlocks[i]; splits.add(new SplitRange(name, start, length, expectedNumRecords)); } return splits; } private void assertSplits(Iterable<SplitRange> splitRanges) throws IOException { for (SplitRange splitRange : splitRanges) { assertSplit(splitRange); } } private void assertSplit(SplitRange splitRange) throws IOException { String message = splitRange.toString(); long actual = reader.countRecords(splitRange.start, splitRange.length); assertEquals(splitRange.expectedNumRecords, actual, message); } } private static
RecordCountAssert
java
bumptech__glide
library/src/main/java/com/bumptech/glide/GlideBuilder.java
{ "start": 26477, "end": 26612 }
class ____ implements Experiment {} /** See {@link #setOverrideGlideThreadPriority(boolean)}. */ public static final
LogRequestOrigins
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/CustomJobEndNotifier.java
{ "start": 1367, "end": 1726 }
class ____ can choose how you want to make the * notification itself. For example you can choose to use a custom * HTTP library, or do a delegation token authentication, maybe set a * custom SSL context on the connection, etc. This means you still have to set * the {@link MRJobConfig#MR_JOB_END_NOTIFICATION_URL} property * in the Job's conf. */ public
you
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/orderupdates/OrderUpdatesTest.java
{ "start": 2350, "end": 2939 }
class ____ { @Id @GeneratedValue private Long id; private String name; @OneToMany(mappedBy = "parent", cascade = { REMOVE }, fetch = FetchType.LAZY) private Collection<Child> children = new LinkedList<>(); public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public void addChild(Child child) { children.add( child ); child.setParent( this ); } public void removeChild(Child child) { children.remove( child ); child.setParent( null ); } } @Entity(name = "Chil;d") @IdClass(Key.class) public static
Parent
java
quarkusio__quarkus
independent-projects/qute/core/src/test/java/io/quarkus/qute/IfSectionTest.java
{ "start": 15716, "end": 15776 }
enum ____ { NEW, ACCEPTED } }
ContentStatus
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KafkaEndpointBuilderFactory.java
{ "start": 221724, "end": 223949 }
interface ____ { /** * Kafka (camel-kafka) * Send and receive messages to/from an Apache Kafka broker. * * Category: messaging * Since: 2.13 * Maven coordinates: org.apache.camel:camel-kafka * * @return the dsl builder for the headers' name. */ default KafkaHeaderNameBuilder kafka() { return KafkaHeaderNameBuilder.INSTANCE; } /** * Kafka (camel-kafka) * Send and receive messages to/from an Apache Kafka broker. * * Category: messaging * Since: 2.13 * Maven coordinates: org.apache.camel:camel-kafka * * Syntax: <code>kafka:topic</code> * * Path parameter: topic (required) * Name of the topic to use. On the consumer you can use comma to * separate multiple topics. A producer can only send a message to a * single topic. * * @param path topic * @return the dsl builder */ default KafkaEndpointBuilder kafka(String path) { return KafkaEndpointBuilderFactory.endpointBuilder("kafka", path); } /** * Kafka (camel-kafka) * Send and receive messages to/from an Apache Kafka broker. * * Category: messaging * Since: 2.13 * Maven coordinates: org.apache.camel:camel-kafka * * Syntax: <code>kafka:topic</code> * * Path parameter: topic (required) * Name of the topic to use. On the consumer you can use comma to * separate multiple topics. A producer can only send a message to a * single topic. * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path topic * @return the dsl builder */ default KafkaEndpointBuilder kafka(String componentName, String path) { return KafkaEndpointBuilderFactory.endpointBuilder(componentName, path); } } /** * The builder of headers' name for the Kafka component. */ public static
KafkaBuilders
java
junit-team__junit5
junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/descriptor/ClassTemplateInvocationTestDescriptor.java
{ "start": 1900, "end": 7249 }
class ____ extends JupiterTestDescriptor implements TestClassAware, ResourceLockAware { public static final String SEGMENT_TYPE = "class-template-invocation"; private final ClassTemplateTestDescriptor parent; private @Nullable ClassTemplateInvocationContext invocationContext; private final int index; public ClassTemplateInvocationTestDescriptor(UniqueId uniqueId, ClassTemplateTestDescriptor parent, ClassTemplateInvocationContext invocationContext, int index, @Nullable TestSource source, JupiterConfiguration configuration) { super(uniqueId, invocationContext.getDisplayName(index), source, configuration); this.parent = parent; this.invocationContext = invocationContext; this.index = index; } public int getIndex() { return index; } // --- JupiterTestDescriptor ----------------------------------------------- @Override protected ClassTemplateInvocationTestDescriptor withUniqueId(UnaryOperator<UniqueId> uniqueIdTransformer) { return new ClassTemplateInvocationTestDescriptor(uniqueIdTransformer.apply(getUniqueId()), parent, requiredInvocationContext(), this.index, getSource().orElse(null), this.configuration); } // --- TestDescriptor ------------------------------------------------------ @Override public Type getType() { return Type.CONTAINER; } @Override public String getLegacyReportingName() { return getTestClass().getName() + "[" + index + "]"; } // --- TestClassAware ------------------------------------------------------ @Override public Class<?> getTestClass() { return parent.getTestClass(); } @Override public List<Class<?>> getEnclosingTestClasses() { return parent.getEnclosingTestClasses(); } // --- ResourceLockAware --------------------------------------------------- @Override public ExclusiveResourceCollector getExclusiveResourceCollector() { return parent.getExclusiveResourceCollector(); } @Override public Function<ResourceLocksProvider, Set<ResourceLocksProvider.Lock>> getResourceLocksProviderEvaluator() { return parent.getResourceLocksProviderEvaluator(); } // --- Node ---------------------------------------------------------------- @Override public JupiterEngineExecutionContext prepare(JupiterEngineExecutionContext context) { MutableExtensionRegistry registry = context.getExtensionRegistry(); List<Extension> additionalExtensions = requiredInvocationContext().getAdditionalExtensions(); if (!additionalExtensions.isEmpty()) { MutableExtensionRegistry childRegistry = createRegistryFrom(registry, Stream.empty()); additionalExtensions.forEach( extension -> childRegistry.registerExtension(extension, requiredInvocationContext())); registry = childRegistry; } ExtensionContext extensionContext = new ClassTemplateInvocationExtensionContext(context.getExtensionContext(), context.getExecutionListener(), this, context.getConfiguration(), registry, context.getLauncherStoreFacade()); ThrowableCollector throwableCollector = createThrowableCollector(); throwableCollector.execute(() -> requiredInvocationContext().prepareInvocation(extensionContext)); return context.extend() // .withExtensionRegistry(registry) // .withExtensionContext(extensionContext) // .withThrowableCollector(throwableCollector) // .build(); } @Override public SkipResult shouldBeSkipped(JupiterEngineExecutionContext context) { context.getThrowableCollector().assertEmpty(); return SkipResult.doNotSkip(); } @Override public JupiterEngineExecutionContext before(JupiterEngineExecutionContext context) throws Exception { invokeBeforeCallbacks(BeforeClassTemplateInvocationCallback.class, context, BeforeClassTemplateInvocationCallback::beforeClassTemplateInvocation); context.getThrowableCollector().assertEmpty(); return context; } @Override public JupiterEngineExecutionContext execute(JupiterEngineExecutionContext context, DynamicTestExecutor dynamicTestExecutor) throws Exception { Visitor visitor = context.getExecutionListener()::dynamicTestRegistered; getChildren().forEach(child -> child.accept(visitor)); return context; } @Override public void after(JupiterEngineExecutionContext context) throws Exception { ThrowableCollector throwableCollector = context.getThrowableCollector(); Throwable previousThrowable = throwableCollector.getThrowable(); invokeAfterCallbacks(AfterClassTemplateInvocationCallback.class, context, AfterClassTemplateInvocationCallback::afterClassTemplateInvocation); // If the previous Throwable was not null when this method was called, // that means an exception was already thrown either before or during // the execution of this Node. If an exception was already thrown, any // later exceptions were added as suppressed exceptions to that original // exception unless a more severe exception occurred in the meantime. if (previousThrowable != throwableCollector.getThrowable()) { throwableCollector.assertEmpty(); } } @Override public void cleanUp(JupiterEngineExecutionContext context) throws Exception { // forget invocationContext so it can be garbage collected this.invocationContext = null; super.cleanUp(context); } private ClassTemplateInvocationContext requiredInvocationContext() { return requireNonNull(this.invocationContext); } }
ClassTemplateInvocationTestDescriptor
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/services/xml/Location.java
{ "start": 859, "end": 1954 }
interface ____ { /** * Return the line number where the current event ends, * returns -1 if none is available. * @return the current line number */ int getLineNumber(); /** * Return the column number where the current event ends, * returns -1 if none is available. * @return the current column number */ int getColumnNumber(); /** * Return the byte or character offset into the input source this location * is pointing to. If the input source is a file or a byte stream then * this is the byte offset into that stream, but if the input source is * a character media then the offset is the character offset. * Returns -1 if there is no offset available. * @return the current offset */ int getCharacterOffset(); /** * Returns the public ID of the XML * @return the public ID, or null if not available */ String getPublicId(); /** * Returns the system ID of the XML * @return the system ID, or null if not available */ String getSystemId(); }
Location
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/beans/BeanGenerator.java
{ "start": 1313, "end": 1566 }
class ____ extends AbstractClassGenerator { private static final Source SOURCE = new Source(BeanGenerator.class.getName()); private static final BeanGeneratorKey KEY_FACTORY = (BeanGeneratorKey)KeyFactory.create(BeanGeneratorKey.class);
BeanGenerator
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/EntityMappingType.java
{ "start": 14745, "end": 21249 }
interface ____ { void consume(String tableExpression, Supplier<Consumer<SelectableConsumer>> tableKeyColumnVisitationSupplier); } // Customer <- DomesticCustomer <- OtherCustomer @Deprecated(forRemoval = true) default Object[] extractConcreteTypeStateValues( Map<AttributeMapping, DomainResultAssembler> assemblerMapping, RowProcessingState rowProcessingState) { // todo (6.0) : getNumberOfAttributeMappings() needs to be fixed for this to work - bad walking of hierarchy final var values = new Object[ getNumberOfAttributeMappings() ]; forEachAttributeMapping( attribute -> { final DomainResultAssembler<?> assembler = assemblerMapping.get( attribute ); final Object value; if ( assembler == null ) { value = UNFETCHED_PROPERTY; } else { value = assembler.assemble( rowProcessingState ); } values[attribute.getStateArrayPosition()] = value; } ); return values; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Loading /** * Access to performing natural-id database selection. This is per-entity in the hierarchy */ NaturalIdLoader<?> getNaturalIdLoader(); /** * Access to performing multi-value natural-id database selection. This is per-entity in the hierarchy */ MultiNaturalIdLoader<?> getMultiNaturalIdLoader(); /** * Load an instance of the persistent class, by a unique key other * than the primary key. */ Object loadByUniqueKey(String propertyName, Object uniqueKey, SharedSessionContractImplementor session); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Loadable @Override default boolean isAffectedByEnabledFilters(LoadQueryInfluencers influencers, boolean onlyApplyForLoadByKeyFilters) { return getEntityPersister().isAffectedByEnabledFilters( influencers, onlyApplyForLoadByKeyFilters ); } @Override default boolean isAffectedByEntityGraph(LoadQueryInfluencers influencers) { return getEntityPersister().isAffectedByEntityGraph( influencers ); } @Override default boolean isAffectedByEnabledFetchProfiles(LoadQueryInfluencers influencers) { return getEntityPersister().isAffectedByEnabledFetchProfiles( influencers ); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // SQM handling default SqmMultiTableMutationStrategy getSqmMultiTableMutationStrategy(){ return getEntityPersister().getSqmMultiTableMutationStrategy(); } default SqmMultiTableInsertStrategy getSqmMultiTableInsertStrategy() { return getEntityPersister().getSqmMultiTableInsertStrategy(); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // SQL AST generation @Override default String getSqlAliasStem() { return getEntityPersister().getSqlAliasStem(); } @Override default TableGroup createRootTableGroup( boolean canUseInnerJoins, NavigablePath navigablePath, String explicitSourceAlias, SqlAliasBase explicitSqlAliasBase, Supplier<Consumer<Predicate>> additionalPredicateCollectorAccess, SqlAstCreationState creationState) { return getEntityPersister().createRootTableGroup( canUseInnerJoins, navigablePath, explicitSourceAlias, explicitSqlAliasBase, additionalPredicateCollectorAccess, creationState ); } default TableReference createPrimaryTableReference( SqlAliasBase sqlAliasBase, SqlAstCreationState creationState) { throw new UnsupportedMappingException( "Entity mapping does not support primary TableReference creation [" + getClass().getName() + " : " + getEntityName() + "]" ); } default TableReferenceJoin createTableReferenceJoin( String joinTableExpression, SqlAliasBase sqlAliasBase, TableReference lhs, SqlAstCreationState creationState) { throw new UnsupportedMappingException( "Entity mapping does not support primary TableReference join creation [" + getClass().getName() + " : " + getEntityName() + "]" ); } @Override default JavaType<?> getMappedJavaType() { return getEntityPersister().getMappedJavaType(); } @Override default int getNumberOfFetchables() { return getEntityPersister().getNumberOfFetchables(); } @Override default Fetchable getFetchable(int position) { return getEntityPersister().getFetchable( position ); } @Override default void applyDiscriminator( Consumer<Predicate> predicateConsumer, String alias, TableGroup tableGroup, SqlAstCreationState creationState) { getEntityPersister().applyDiscriminator( predicateConsumer, alias, tableGroup, creationState ); } @Override default void applyFilterRestrictions( Consumer<Predicate> predicateConsumer, TableGroup tableGroup, boolean useQualifier, Map<String, Filter> enabledFilters, boolean onlyApplyLoadByKeyFilters, SqlAstCreationState creationState) { getEntityPersister().applyFilterRestrictions( predicateConsumer, tableGroup, useQualifier, enabledFilters, onlyApplyLoadByKeyFilters, creationState ); } @Override default void applyBaseRestrictions( Consumer<Predicate> predicateConsumer, TableGroup tableGroup, boolean useQualifier, Map<String, Filter> enabledFilters, boolean onlyApplyLoadByKeyFilters, Set<String> treatAsDeclarations, SqlAstCreationState creationState) { getEntityPersister().applyBaseRestrictions( predicateConsumer, tableGroup, useQualifier, enabledFilters, onlyApplyLoadByKeyFilters, treatAsDeclarations, creationState ); } @Override default boolean hasWhereRestrictions() { return getEntityPersister().hasWhereRestrictions(); } @Override default void applyWhereRestrictions( Consumer<Predicate> predicateConsumer, TableGroup tableGroup, boolean useQualifier, SqlAstCreationState creationState) { getEntityPersister().applyWhereRestrictions( predicateConsumer, tableGroup, useQualifier, creationState ); } /** * Safety-net. */ // todo (6.0) : look to remove need for this. at the very least, move it to an SPI contract @Internal EntityPersister getEntityPersister(); /** * @deprecated See {@link Contributable#getContributor()} */ @Deprecated default String getContributor() { // todo (6.0) : needed for the HHH-14470 half related to HHH-14469 return "orm"; } @Override default String getPartName() { return getEntityName(); } @Override default String getRootPathName() { return getEntityName(); } }
ConstraintOrderedTableConsumer
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/TopicMetadataFetcher.java
{ "start": 2028, "end": 7447 }
class ____ { private final Logger log; private final ConsumerNetworkClient client; private final ExponentialBackoff retryBackoff; public TopicMetadataFetcher(LogContext logContext, ConsumerNetworkClient client, long retryBackoffMs, long retryBackoffMaxMs) { this.log = logContext.logger(getClass()); this.client = client; this.retryBackoff = new ExponentialBackoff(retryBackoffMs, CommonClientConfigs.RETRY_BACKOFF_EXP_BASE, retryBackoffMaxMs, CommonClientConfigs.RETRY_BACKOFF_JITTER); } /** * Fetches the {@link PartitionInfo partition information} for the given topic in the cluster, or {@code null}. * * @param timer Timer bounding how long this method can block * @return The {@link List list} of {@link PartitionInfo partition information}, or {@code null} if the topic is * unknown */ public List<PartitionInfo> getTopicMetadata(String topic, boolean allowAutoTopicCreation, Timer timer) { MetadataRequest.Builder request = new MetadataRequest.Builder(Collections.singletonList(topic), allowAutoTopicCreation); Map<String, List<PartitionInfo>> topicMetadata = getTopicMetadata(request, timer); return topicMetadata.get(topic); } /** * Fetches the {@link PartitionInfo partition information} for all topics in the cluster. * * @param timer Timer bounding how long this method can block * @return The map of topics with their {@link PartitionInfo partition information} */ public Map<String, List<PartitionInfo>> getAllTopicMetadata(Timer timer) { MetadataRequest.Builder request = MetadataRequest.Builder.allTopics(); return getTopicMetadata(request, timer); } /** * Get metadata for all topics present in Kafka cluster. * * @param request The MetadataRequest to send * @param timer Timer bounding how long this method can block * @return The map of topics with their partition information */ private Map<String, List<PartitionInfo>> getTopicMetadata(MetadataRequest.Builder request, Timer timer) { // Save the round trip if no topics are requested. if (!request.isAllTopics() && request.emptyTopicList()) return Collections.emptyMap(); long attempts = 0L; do { RequestFuture<ClientResponse> future = sendMetadataRequest(request); client.poll(future, timer); if (future.failed() && !future.isRetriable()) throw future.exception(); if (future.succeeded()) { MetadataResponse response = (MetadataResponse) future.value().responseBody(); Cluster cluster = response.buildCluster(); Set<String> unauthorizedTopics = cluster.unauthorizedTopics(); if (!unauthorizedTopics.isEmpty()) throw new TopicAuthorizationException(unauthorizedTopics); boolean shouldRetry = false; Map<String, Errors> errors = response.errors(); if (!errors.isEmpty()) { // if there were errors, we need to check whether they were fatal or whether // we should just retry log.debug("Topic metadata fetch included errors: {}", errors); for (Map.Entry<String, Errors> errorEntry : errors.entrySet()) { String topic = errorEntry.getKey(); Errors error = errorEntry.getValue(); if (error == Errors.INVALID_TOPIC_EXCEPTION) throw new InvalidTopicException("Topic '" + topic + "' is invalid"); else if (error == Errors.UNKNOWN_TOPIC_OR_PARTITION) // if a requested topic is unknown, we just continue and let it be absent // in the returned map continue; else if (error.exception() instanceof RetriableException) shouldRetry = true; else throw new KafkaException("Unexpected error fetching metadata for topic " + topic, error.exception()); } } if (!shouldRetry) { HashMap<String, List<PartitionInfo>> topicsPartitionInfos = new HashMap<>(); for (String topic : cluster.topics()) topicsPartitionInfos.put(topic, cluster.partitionsForTopic(topic)); return topicsPartitionInfos; } } timer.sleep(retryBackoff.backoff(attempts++)); } while (timer.notExpired()); throw new TimeoutException("Timeout expired while fetching topic metadata"); } /** * Send Metadata Request to the least loaded node in Kafka cluster asynchronously * @return A future that indicates result of sent metadata request */ private RequestFuture<ClientResponse> sendMetadataRequest(MetadataRequest.Builder request) { final Node node = client.leastLoadedNode(); if (node == null) return RequestFuture.noBrokersAvailable(); else return client.send(node, request); } }
TopicMetadataFetcher
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/IntFloatConversion.java
{ "start": 1800, "end": 2848 }
class ____ extends BugChecker implements MethodInvocationTreeMatcher { /** * int to float conversions aren't always problematic, this specific issue is that there are float * and double overloads, and when passing an int the float will be resolved in situations where * double precision may be desired. */ private static final Matcher<ExpressionTree> MATCHER = MethodMatchers.staticMethod() .onClass("java.lang.Math") .named("scalb") .withParameters("float", "int"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return NO_MATCH; } Tree arg = tree.getArguments().getFirst(); if (!getType(arg).hasTag(TypeTag.INT)) { return NO_MATCH; } TargetType targetType = targetType(state); if (targetType == null || !targetType.type().hasTag(TypeTag.DOUBLE)) { return NO_MATCH; } return describeMatch(arg, prefixWith(arg, "(double) ")); } }
IntFloatConversion
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilter.java
{ "start": 11472, "end": 11852 }
class ____ extends ThrowableAnalyzer { @Override protected void initExtractorMap() { super.initExtractorMap(); registerExtractor(ServletException.class, (throwable) -> { ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class); return ((ServletException) throwable).getRootCause(); }); } } private static final
DefaultThrowableAnalyzer
java
quarkusio__quarkus
extensions/micrometer/runtime/src/main/java/io/quarkus/micrometer/runtime/config/KafkaConfigGroup.java
{ "start": 448, "end": 666 }
interface ____ on the classpath * and either this value is true, or this value is unset and * {@code quarkus.micrometer.binder-enabled-default} is true. */ @Override Optional<Boolean> enabled(); }
is
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/ResolvableType.java
{ "start": 58127, "end": 58563 }
interface ____ extends Serializable { /** * Return the source of the resolver (used for hashCode and equals). */ Object getSource(); /** * Resolve the specified variable. * @param variable the variable to resolve * @return the resolved variable, or {@code null} if not found */ @Nullable ResolvableType resolveVariable(TypeVariable<?> variable); } @SuppressWarnings("serial") private static
VariableResolver
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/metadata/FlinkMetadata.java
{ "start": 1633, "end": 1762 }
class ____ { /** Metadata about the interval of given column from a specified relational expression. */ public
FlinkMetadata
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/buffer/BufferCompressionTest.java
{ "start": 1823, "end": 11254 }
class ____ { private static final int BUFFER_SIZE = 4 * 1024 * 1024; private static final int NUM_LONGS = BUFFER_SIZE / 8; private final boolean compressToOriginalBuffer; private final boolean decompressToOriginalBuffer; private final BufferCompressor compressor; private final BufferDecompressor decompressor; private final Buffer bufferToCompress; @Parameters( name = "isDirect = {0}, codec = {1}, compressToOriginal = {2}, decompressToOriginal = {3}") public static Collection<Object[]> parameters() { return Arrays.asList( new Object[][] { {true, CompressionCodec.LZ4, true, false}, {true, CompressionCodec.LZ4, false, true}, {true, CompressionCodec.LZ4, false, false}, {false, CompressionCodec.LZ4, true, false}, {false, CompressionCodec.LZ4, false, true}, {false, CompressionCodec.LZ4, false, false}, {true, CompressionCodec.ZSTD, true, false}, {true, CompressionCodec.ZSTD, false, true}, {true, CompressionCodec.ZSTD, false, false}, {false, CompressionCodec.ZSTD, true, false}, {false, CompressionCodec.ZSTD, false, true}, {false, CompressionCodec.ZSTD, false, false}, {true, CompressionCodec.LZO, true, false}, {true, CompressionCodec.LZO, false, true}, {true, CompressionCodec.LZO, false, false}, {false, CompressionCodec.LZO, true, false}, {false, CompressionCodec.LZO, false, true}, {false, CompressionCodec.LZO, false, false} }); } public BufferCompressionTest( boolean isDirect, CompressionCodec compressionCodec, boolean compressToOriginalBuffer, boolean decompressToOriginalBuffer) { this.compressToOriginalBuffer = compressToOriginalBuffer; this.decompressToOriginalBuffer = decompressToOriginalBuffer; this.compressor = new BufferCompressor(BUFFER_SIZE, compressionCodec); this.decompressor = new BufferDecompressor(BUFFER_SIZE, compressionCodec); this.bufferToCompress = createBufferAndFillWithLongValues(isDirect); } @TestTemplate void testCompressAndDecompressNetWorkBuffer() { Buffer compressedBuffer = compress(compressor, bufferToCompress, compressToOriginalBuffer); assertThat(compressedBuffer.isCompressed()).isTrue(); Buffer decompressedBuffer = decompress(decompressor, compressedBuffer, decompressToOriginalBuffer); assertThat(decompressedBuffer.isCompressed()).isFalse(); verifyDecompressionResult(decompressedBuffer, 0, NUM_LONGS); } @TestTemplate void testCompressAndDecompressReadOnlySlicedNetworkBuffer() { int offset = NUM_LONGS / 4 * 8; int length = NUM_LONGS / 2 * 8; Buffer readOnlySlicedBuffer = bufferToCompress.readOnlySlice(offset, length); Buffer compressedBuffer = compress(compressor, readOnlySlicedBuffer, compressToOriginalBuffer); assertThat(compressedBuffer.isCompressed()).isTrue(); Buffer decompressedBuffer = decompress(decompressor, compressedBuffer, decompressToOriginalBuffer); assertThat(decompressedBuffer.isCompressed()).isFalse(); verifyDecompressionResult(decompressedBuffer, NUM_LONGS / 4, NUM_LONGS / 2); } @TestTemplate void testCompressEmptyBuffer() { assertThatThrownBy( () -> compress( compressor, bufferToCompress.readOnlySlice(0, 0), compressToOriginalBuffer)) .isInstanceOf(IllegalArgumentException.class); } @TestTemplate void testDecompressEmptyBuffer() { Buffer readOnlySlicedBuffer = bufferToCompress.readOnlySlice(0, 0); readOnlySlicedBuffer.setCompressed(true); assertThatThrownBy( () -> decompress( decompressor, readOnlySlicedBuffer, decompressToOriginalBuffer)) .isInstanceOf(IllegalArgumentException.class); } @TestTemplate void testCompressBufferWithNonZeroReadOffset() { bufferToCompress.setReaderIndex(1); assertThatThrownBy(() -> compress(compressor, bufferToCompress, compressToOriginalBuffer)) .isInstanceOf(IllegalArgumentException.class); } @TestTemplate void testDecompressBufferWithNonZeroReadOffset() { bufferToCompress.setReaderIndex(1); bufferToCompress.setCompressed(true); assertThatThrownBy( () -> decompress( decompressor, bufferToCompress, decompressToOriginalBuffer)) .isInstanceOf(IllegalArgumentException.class); } @TestTemplate void testCompressNull() { assertThatThrownBy(() -> compress(compressor, null, compressToOriginalBuffer)) .isInstanceOf(IllegalArgumentException.class); } @TestTemplate void testDecompressNull() { assertThatThrownBy(() -> decompress(decompressor, null, decompressToOriginalBuffer)) .isInstanceOf(IllegalArgumentException.class); } @TestTemplate void testCompressCompressedBuffer() { bufferToCompress.setCompressed(true); assertThatThrownBy(() -> compress(compressor, bufferToCompress, compressToOriginalBuffer)) .isInstanceOf(IllegalArgumentException.class); } @TestTemplate void testDecompressUncompressedBuffer() { assertThatThrownBy( () -> decompress( decompressor, bufferToCompress, decompressToOriginalBuffer)) .isInstanceOf(IllegalArgumentException.class); } @TestTemplate void testCompressEvent() { assertThatThrownBy( () -> compress( compressor, EventSerializer.toBuffer( EndOfPartitionEvent.INSTANCE, false), compressToOriginalBuffer)) .isInstanceOf(IllegalArgumentException.class); } @TestTemplate void testDecompressEvent() { assertThatThrownBy( () -> decompress( decompressor, EventSerializer.toBuffer( EndOfPartitionEvent.INSTANCE, false), decompressToOriginalBuffer)) .isInstanceOf(IllegalArgumentException.class); } @TestTemplate void testDataSizeGrowsAfterCompression() { int numBytes = 1; Buffer readOnlySlicedBuffer = bufferToCompress.readOnlySlice(BUFFER_SIZE / 2, numBytes); Buffer compressedBuffer = compress(compressor, readOnlySlicedBuffer, compressToOriginalBuffer); assertThat(compressedBuffer.isCompressed()).isFalse(); assertThat(compressedBuffer).isEqualTo(readOnlySlicedBuffer); assertThat(compressedBuffer.readableBytes()).isEqualTo(numBytes); } private static Buffer createBufferAndFillWithLongValues(boolean isDirect) { MemorySegment segment; if (isDirect) { segment = MemorySegmentFactory.allocateUnpooledSegment(BUFFER_SIZE); } else { segment = MemorySegmentFactory.allocateUnpooledOffHeapMemory(BUFFER_SIZE); } for (int i = 0; i < NUM_LONGS; ++i) { segment.putLongLittleEndian(8 * i, i); } NetworkBuffer buffer = new NetworkBuffer(segment, FreeingBufferRecycler.INSTANCE); buffer.setSize(8 * NUM_LONGS); return buffer; } private static void verifyDecompressionResult(Buffer buffer, long start, int numLongs) { ByteBuffer byteBuffer = buffer.getNioBufferReadable().order(ByteOrder.LITTLE_ENDIAN); for (int i = 0; i < numLongs; ++i) { assertThat(byteBuffer.getLong()).isEqualTo(start + i); } } private static Buffer compress( BufferCompressor compressor, Buffer buffer, boolean compressToOriginalBuffer) { if (compressToOriginalBuffer) { return compressor.compressToOriginalBuffer(buffer); } return compressor.compressToIntermediateBuffer(buffer); } private static Buffer decompress( BufferDecompressor decompressor, Buffer buffer, boolean decompressToOriginalBuffer) { if (decompressToOriginalBuffer) { return decompressor.decompressToOriginalBuffer(buffer); } return decompressor.decompressToIntermediateBuffer(buffer); } }
BufferCompressionTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/EnabledIfTests.java
{ "start": 3892, "end": 4043 }
class ____ { @Bean Boolean booleanFalseBean() { return Boolean.FALSE; } @Bean String stringFalseBean() { return "false"; } } }
Config
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/ExecutionTest.java
{ "start": 2687, "end": 14765 }
class ____ { @RegisterExtension static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE = TestingUtils.defaultExecutorExtension(); @RegisterExtension static final TestingComponentMainThreadExecutor.Extension MAIN_EXECUTOR_RESOURCE = new TestingComponentMainThreadExecutor.Extension(); private final TestingComponentMainThreadExecutor testMainThreadUtil = MAIN_EXECUTOR_RESOURCE.getComponentMainThreadTestExecutor(); /** * Checks that the {@link Execution} termination future is only completed after the assigned * slot has been released. * * <p>NOTE: This test only fails spuriously without the fix of this commit. Thus, one has to * execute this test multiple times to see the failure. */ @Test void testTerminationFutureIsCompletedAfterSlotRelease() throws Exception { final JobVertex jobVertex = createNoOpJobVertex(); final JobVertexID jobVertexId = jobVertex.getID(); final TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.createWithLimitedAmountOfPhysicalSlots(1); final SchedulerBase scheduler = new DefaultSchedulerBuilder( JobGraphTestUtils.streamingJobGraph(jobVertex), ComponentMainThreadExecutorServiceAdapter.forMainThread(), EXECUTOR_RESOURCE.getExecutor()) .setExecutionSlotAllocatorFactory( SchedulerTestingUtils.newSlotSharingExecutionSlotAllocatorFactory( physicalSlotProvider)) .build(); ExecutionJobVertex executionJobVertex = scheduler.getExecutionJobVertex(jobVertexId); ExecutionVertex executionVertex = executionJobVertex.getTaskVertices()[0]; scheduler.startScheduling(); Execution currentExecutionAttempt = executionVertex.getCurrentExecutionAttempt(); CompletableFuture<? extends PhysicalSlot> returnedSlotFuture = physicalSlotProvider.getFirstResponseOrFail(); CompletableFuture<?> terminationFuture = executionVertex.cancel(); currentExecutionAttempt.completeCancelling(); CompletableFuture<Boolean> restartFuture = terminationFuture.thenApply( ignored -> { assertThat(returnedSlotFuture).isDone(); return true; }); // check if the returned slot future was completed first restartFuture.get(); } /** * Tests that the task restore state is nulled after the {@link Execution} has been deployed. * See FLINK-9693. */ @Test void testTaskRestoreStateIsNulledAfterDeployment() throws Exception { final JobVertex jobVertex = createNoOpJobVertex(); final JobVertexID jobVertexId = jobVertex.getID(); final SchedulerBase scheduler = new DefaultSchedulerBuilder( JobGraphTestUtils.streamingJobGraph(jobVertex), testMainThreadUtil.getMainThreadExecutor(), EXECUTOR_RESOURCE.getExecutor()) .setExecutionSlotAllocatorFactory( SchedulerTestingUtils.newSlotSharingExecutionSlotAllocatorFactory( TestingPhysicalSlotProvider .createWithLimitedAmountOfPhysicalSlots(1))) .build(); ExecutionJobVertex executionJobVertex = scheduler.getExecutionJobVertex(jobVertexId); ExecutionVertex executionVertex = executionJobVertex.getTaskVertices()[0]; final Execution execution = executionVertex.getCurrentExecutionAttempt(); final JobManagerTaskRestore taskRestoreState = new JobManagerTaskRestore(1L, new TaskStateSnapshot()); execution.setInitialState(taskRestoreState); assertThat(execution.getTaskRestore()).isNotNull(); // schedule the execution vertex and wait for its deployment testMainThreadUtil.execute(scheduler::startScheduling); // After the execution has been deployed, the task restore state should be nulled. while (execution.getTaskRestore() != null) { // Using busy waiting because there is no `future` that would indicate the completion // of the deployment and I want to keep production code clean. Thread.sleep(10); } } @Test void testCanceledExecutionReturnsSlot() throws Exception { final JobVertex jobVertex = createNoOpJobVertex(); final JobVertexID jobVertexId = jobVertex.getID(); final SimpleAckingTaskManagerGateway taskManagerGateway = new SimpleAckingTaskManagerGateway(); TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.create( (resourceProfile) -> CompletableFuture.completedFuture( TestingPhysicalSlot.builder() .withTaskManagerGateway(taskManagerGateway) .build())); final SchedulerBase scheduler = new DefaultSchedulerBuilder( JobGraphTestUtils.streamingJobGraph(jobVertex), testMainThreadUtil.getMainThreadExecutor(), EXECUTOR_RESOURCE.getExecutor()) .setExecutionSlotAllocatorFactory( SchedulerTestingUtils.newSlotSharingExecutionSlotAllocatorFactory( physicalSlotProvider)) .build(); ExecutionJobVertex executionJobVertex = scheduler.getExecutionJobVertex(jobVertexId); ExecutionVertex executionVertex = executionJobVertex.getTaskVertices()[0]; final Execution execution = executionVertex.getCurrentExecutionAttempt(); taskManagerGateway.setCancelConsumer( executionAttemptID -> { if (execution.getAttemptId().equals(executionAttemptID)) { execution.completeCancelling(); } }); testMainThreadUtil.execute(scheduler::startScheduling); // cancel the execution in case we could schedule the execution testMainThreadUtil.execute(execution::cancel); assertThat(physicalSlotProvider.getRequests().keySet()) .isEqualTo(physicalSlotProvider.getCancellations().keySet()); } /** Tests that a slot release will atomically release the assigned {@link Execution}. */ @Test void testSlotReleaseAtomicallyReleasesExecution() throws Exception { final JobVertex jobVertex = createNoOpJobVertex(); final TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.createWithLimitedAmountOfPhysicalSlots(1); final SchedulerBase scheduler = new DefaultSchedulerBuilder( JobGraphTestUtils.streamingJobGraph(jobVertex), testMainThreadUtil.getMainThreadExecutor(), EXECUTOR_RESOURCE.getExecutor()) .setExecutionSlotAllocatorFactory( SchedulerTestingUtils.newSlotSharingExecutionSlotAllocatorFactory( physicalSlotProvider)) .build(); final Execution execution = scheduler .getExecutionJobVertex(jobVertex.getID()) .getTaskVertices()[0] .getCurrentExecutionAttempt(); testMainThreadUtil.execute(scheduler::startScheduling); // wait until the slot has been requested physicalSlotProvider.awaitAllSlotRequests(); TestingPhysicalSlot physicalSlot = physicalSlotProvider.getFirstResponseOrFail().get(); testMainThreadUtil.execute( () -> { assertThat(execution.getAssignedAllocationID()) .isEqualTo(physicalSlot.getAllocationId()); physicalSlot.releasePayload(new FlinkException("Test exception")); assertThat(execution.getReleaseFuture()).isDone(); }); } @Test void testExecutionCancelledDuringTaskRestoreOffload() { final CountDownLatch offloadLatch = new CountDownLatch(1); final Execution cancelledExecution = testMainThreadUtil.execute( () -> { final ConditionalLatchBlockingBlobWriter blobWriter = new ConditionalLatchBlockingBlobWriter(offloadLatch); final JobVertex jobVertex = createNoOpJobVertex(); final JobGraph jobGraph = JobGraphTestUtils.streamingJobGraph(jobVertex); final ExecutionGraph executionGraph = TestingDefaultExecutionGraphBuilder.newBuilder() .setJobGraph(jobGraph) .setBlobWriter(blobWriter) .build(EXECUTOR_RESOURCE.getExecutor()); executionGraph.start(testMainThreadUtil.getMainThreadExecutor()); final ExecutionJobVertex executionJobVertex = executionGraph.getJobVertex(jobVertex.getID()); final ExecutionVertex executionVertex = executionJobVertex.getTaskVertices()[0]; final Execution execution = executionVertex.getCurrentExecutionAttempt(); final JobManagerTaskRestore taskRestoreState = new JobManagerTaskRestore(1L, new TaskStateSnapshot()); execution.setInitialState(taskRestoreState); execution.tryAssignResource( new TestingLogicalSlotBuilder().createTestingLogicalSlot()); execution.transitionState(ExecutionState.SCHEDULED); blobWriter.enableBlocking(); execution.deploy(); execution.cancel(); return execution; }); offloadLatch.countDown(); cancelledExecution .getTddCreationDuringDeployFuture() .handle( (result, exception) -> { assertThat(exception) .isNotNull() .describedAs("Expected IllegalStateException to be thrown"); final Throwable rootCause = exception.getCause(); assertThat(rootCause).isInstanceOf(IllegalStateException.class); assertThat(rootCause.getMessage()) .contains("execution state has switched"); assertThat(rootCause.getMessage()) .contains("during task restore offload"); return null; }) .join(); } /** * Custom BlobWriter that conditionally blocks putPermanent calls on a latch to simulate slow * offloading. */ private static
ExecutionTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/EnablementTests.java
{ "start": 673, "end": 1853 }
class ____ { @Test public void verifyMapping(DomainModelScope scope) { scope.withHierarchy( TheEntity.class, (descriptor) -> { { final Property property = descriptor.getProperty( "thing1" ); final BasicValue valueMapping = (BasicValue) property.getValue(); final ConverterDescriptor converterDescriptor = valueMapping.getJpaAttributeConverterDescriptor(); assertThat( converterDescriptor ).isNotNull(); assertThat( converterDescriptor.getAttributeConverterClass() ).isEqualTo( Thing1Converter.class ); assertThat( converterDescriptor.getDomainValueResolvedType().getErasedType() ).isEqualTo( Thing1.class ); } { final Property property = descriptor.getProperty( "thing2" ); final BasicValue valueMapping = (BasicValue) property.getValue(); final ConverterDescriptor converterDescriptor = valueMapping.getJpaAttributeConverterDescriptor(); assertThat( converterDescriptor ).isNotNull(); assertThat( converterDescriptor.getAttributeConverterClass() ).isEqualTo( Thing2Converter.class ); assertThat( converterDescriptor.getDomainValueResolvedType().getErasedType() ).isEqualTo( Thing2.class ); } } ); } }
EnablementTests
java
apache__camel
components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/MessageCorrelator.java
{ "start": 2810, "end": 3696 }
class ____ { private final Exchange exchange; private final CountDownLatch latch = new CountDownLatch(1); private final MessagePredicate messageCriteria; private Message replyMessage; MessageCorrelationRule(Exchange exchange, MessagePredicate messageCriteria) { this.exchange = exchange; this.messageCriteria = messageCriteria; } public void setReplyMessage(Message message) { this.replyMessage = message; } public Message getReplyMessage() { return replyMessage; } public CountDownLatch getLatch() { return latch; } public Exchange getExchange() { return exchange; } public MessagePredicate getMessageCriteria() { return messageCriteria; } } }
MessageCorrelationRule
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/converters/ZonedDateTimeParamConverter.java
{ "start": 155, "end": 779 }
class ____ extends TemporalParamConverter<ZonedDateTime> { // this can be called by generated code public ZonedDateTimeParamConverter() { super(DateTimeFormatter.ISO_ZONED_DATE_TIME); } public ZonedDateTimeParamConverter(DateTimeFormatter formatter) { super(formatter); } @Override protected ZonedDateTime convert(String value) { return ZonedDateTime.parse(value); } @Override protected ZonedDateTime convert(String value, DateTimeFormatter formatter) { return ZonedDateTime.parse(value, formatter); } public static
ZonedDateTimeParamConverter
java
apache__hadoop
hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/EchoUserResolver.java
{ "start": 1100, "end": 1803 }
class ____ implements UserResolver { public static final Logger LOG = LoggerFactory.getLogger(Gridmix.class); public EchoUserResolver() { LOG.info(" Current user resolver is EchoUserResolver "); } public synchronized boolean setTargetUsers(URI userdesc, Configuration conf) throws IOException { return false; } public synchronized UserGroupInformation getTargetUgi( UserGroupInformation ugi) { return ugi; } /** * {@inheritDoc} * <br><br> * Since {@link EchoUserResolver} simply returns the user's name passed as * the argument, it doesn't need a target list of users. */ public boolean needsTargetUsersList() { return false; } }
EchoUserResolver
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractSegments.java
{ "start": 1453, "end": 8939 }
class ____<S extends Segment> implements Segments<S> { private static final Logger log = LoggerFactory.getLogger(AbstractSegments.class); final TreeMap<Long, S> segments = new TreeMap<>(); final String name; private final long retentionPeriod; private final long segmentInterval; private final SimpleDateFormat formatter; Position position; AbstractSegments(final String name, final long retentionPeriod, final long segmentInterval) { this.name = name; this.segmentInterval = segmentInterval; this.retentionPeriod = retentionPeriod; // Create a date formatter. Formatted timestamps are used as segment name suffixes this.formatter = new SimpleDateFormat("yyyyMMddHHmm"); this.formatter.setTimeZone(new SimpleTimeZone(0, "UTC")); } public void setPosition(final Position position) { this.position = position; } @Override public long segmentId(final long timestamp) { return timestamp / segmentInterval; } @Override public String segmentName(final long segmentId) { // (1) previous format used - as a separator so if this changes in the future // then we should use something different. // (2) previous format used : as a separator (which did break KafkaStreams on Windows OS) // so if this changes in the future then we should use something different. return name + "." + segmentId * segmentInterval; } @Override public S segmentForTimestamp(final long timestamp) { return segments.get(segmentId(timestamp)); } @Override public S getOrCreateSegmentIfLive(final long segmentId, final StateStoreContext context, final long streamTime) { final long minLiveTimestamp = streamTime - retentionPeriod; final long minLiveSegment = segmentId(minLiveTimestamp); if (segmentId >= minLiveSegment) { // The segment is live. get it, ensure it's open, and return it. return getOrCreateSegment(segmentId, context); } else { return null; } } @Override public void openExisting(final StateStoreContext context, final long streamTime) { try { final File dir = new File(context.stateDir(), name); if (dir.exists()) { final String[] list = dir.list(); if (list != null) { Arrays.stream(list) .map(segment -> segmentIdFromSegmentName(segment, dir)) .sorted() // open segments in the id order .filter(segmentId -> segmentId >= 0) .forEach(segmentId -> getOrCreateSegment(segmentId, context)); } } else { if (!dir.mkdir()) { throw new ProcessorStateException(String.format("dir %s doesn't exist and cannot be created for segments %s", dir, name)); } } } catch (final Exception ex) { // ignore } cleanupExpiredSegments(streamTime); } @Override public List<S> segments(final long timeFrom, final long timeTo, final boolean forward) { final List<S> result = new ArrayList<>(); final NavigableMap<Long, S> segmentsInRange; if (forward) { segmentsInRange = segments.subMap( segmentId(timeFrom), true, segmentId(timeTo), true ); } else { segmentsInRange = segments.subMap( segmentId(timeFrom), true, segmentId(timeTo), true ).descendingMap(); } for (final S segment : segmentsInRange.values()) { if (segment.isOpen()) { result.add(segment); } } return result; } @Override public List<S> allSegments(final boolean forward) { final List<S> result = new ArrayList<>(); final Collection<S> values; if (forward) { values = segments.values(); } else { values = segments.descendingMap().values(); } for (final S segment : values) { if (segment.isOpen()) { result.add(segment); } } return result; } @Override public void flush() { for (final S segment : segments.values()) { segment.flush(); } } @Override public void close() { for (final S segment : segments.values()) { segment.close(); } segments.clear(); } protected void cleanupExpiredSegments(final long streamTime) { final long minLiveSegment = segmentId(streamTime - retentionPeriod); final Iterator<Map.Entry<Long, S>> toRemove = segments.headMap(minLiveSegment, false).entrySet().iterator(); while (toRemove.hasNext()) { final Map.Entry<Long, S> next = toRemove.next(); toRemove.remove(); final S segment = next.getValue(); segment.close(); try { segment.destroy(); } catch (final IOException e) { log.error("Error destroying {}", segment, e); } } } private long segmentIdFromSegmentName(final String segmentName, final File parent) { final int segmentSeparatorIndex = name.length(); final char segmentSeparator = segmentName.charAt(segmentSeparatorIndex); final String segmentIdString = segmentName.substring(segmentSeparatorIndex + 1); final long segmentId; // old style segment name with date if (segmentSeparator == '-') { try { segmentId = formatter.parse(segmentIdString).getTime() / segmentInterval; } catch (final ParseException e) { log.warn("Unable to parse segmentName {} to a date. This segment will be skipped", segmentName); return -1L; } renameSegmentFile(parent, segmentName, segmentId); } else { // for both new formats (with : or .) parse segment ID identically try { segmentId = Long.parseLong(segmentIdString) / segmentInterval; } catch (final NumberFormatException e) { throw new ProcessorStateException("Unable to parse segment id as long from segmentName: " + segmentName, e); } // intermediate segment name with : breaks KafkaStreams on Windows OS -> rename segment file to new name with . if (segmentSeparator == ':') { renameSegmentFile(parent, segmentName, segmentId); } } return segmentId; } private void renameSegmentFile(final File parent, final String segmentName, final long segmentId) { final File newName = new File(parent, segmentName(segmentId)); final File oldName = new File(parent, segmentName); if (!oldName.renameTo(newName)) { throw new ProcessorStateException("Unable to rename old style segment from: " + oldName + " to new name: " + newName); } } }
AbstractSegments
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/rules/logical/PushProjectIntoTableSourceScanRuleTest.java
{ "start": 2769, "end": 19659 }
class ____ extends TableTestBase { @RegisterExtension private final SharedObjectsExtension sharedObjects = SharedObjectsExtension.create(); private final BatchTableTestUtil util = batchTestUtil(TableConfig.getDefault()); @BeforeEach public void setup() { util.buildBatchProgram(FlinkBatchProgram.DEFAULT_REWRITE()); CalciteConfig calciteConfig = TableConfigUtils.getCalciteConfig(util.tableEnv().getConfig()); calciteConfig .getBatchProgram() .get() .addLast( "rules", FlinkHepRuleSetProgramBuilder.<BatchOptimizeContext>newBuilder() .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE()) .setHepMatchOrder(HepMatchOrder.BOTTOM_UP) .add(RuleSets.ofList(PushProjectIntoTableSourceScanRule.INSTANCE)) .build()); String ddl1 = "CREATE TABLE MyTable (\n" + " a int,\n" + " b bigint,\n" + " c string\n" + ") WITH (\n" + " 'connector' = 'values',\n" + " 'bounded' = 'true'\n" + ")"; util.tableEnv().executeSql(ddl1); String ddl2 = "CREATE TABLE VirtualTable (\n" + " a int,\n" + " b bigint,\n" + " c string,\n" + " d as a + 1\n" + ") WITH (\n" + " 'connector' = 'values',\n" + " 'bounded' = 'true'\n" + ")"; util.tableEnv().executeSql(ddl2); String ddl3 = "CREATE TABLE NestedTable (\n" + " id int,\n" + " deepNested row<nested1 row<name string, `value` int>, nested2 row<num int, flag boolean>>,\n" + " nested row<name string, `value` int>,\n" + " `deepNestedWith.` row<`.value` int, nested row<name string, `.value` int>>,\n" + " name string,\n" + " testMap Map<string, string>\n" + ") WITH (\n" + " 'connector' = 'values',\n" + " 'nested-projection-supported' = 'true'," + " 'bounded' = 'true'\n" + ")"; util.tableEnv().executeSql(ddl3); String ddl4 = "CREATE TABLE MetadataTable(\n" + " id int,\n" + " deepNested row<nested1 row<name string, `value` int>, nested2 row<num int, flag boolean>>,\n" + " metadata_1 int metadata,\n" + " metadata_2 string metadata,\n" + " metadata_3 as cast(metadata_1 as bigint)\n" + ") WITH (" + " 'connector' = 'values'," + " 'nested-projection-supported' = 'true'," + " 'bounded' = 'true',\n" + " 'readable-metadata' = 'metadata_1:INT, metadata_2:STRING, metadata_3:BIGINT'" + ")"; util.tableEnv().executeSql(ddl4); String ddl5 = "CREATE TABLE UpsertTable(" + " id int,\n" + " deepNested row<nested1 row<name string, `value` int>, nested2 row<num int, flag boolean>>,\n" + " metadata_1 int metadata,\n" + " metadata_2 string metadata,\n" + " PRIMARY KEY(id, deepNested) NOT ENFORCED" + ") WITH (" + " 'connector' = 'values'," + " 'nested-projection-supported' = 'true'," + " 'bounded' = 'false',\n" + " 'changelod-mode' = 'I,UB,D'," + " 'readable-metadata' = 'metadata_1:INT, metadata_2:STRING, metadata_3:BIGINT'" + ")"; util.tableEnv().executeSql(ddl5); String ddl6 = "CREATE TABLE NestedItemTable (\n" + " `ID` INT,\n" + " `Timestamp` TIMESTAMP(3),\n" + " `Result` ROW<\n" + " `Mid` ROW<" + " `data_arr` ROW<`value` BIGINT> ARRAY,\n" + " `data_map` MAP<STRING, ROW<`value` BIGINT>>" + " >" + " >,\n" + " WATERMARK FOR `Timestamp` AS `Timestamp`\n" + ") WITH (\n" + " 'connector' = 'values',\n" + " 'nested-projection-supported' = 'true'," + " 'bounded' = 'true'\n" + ")"; util.tableEnv().executeSql(ddl6); String ddl7 = "CREATE TABLE ItemTable (\n" + " `ID` INT,\n" + " `Timestamp` TIMESTAMP(3),\n" + " `Result` ROW<\n" + " `data_arr` ROW<`value` BIGINT> ARRAY,\n" + " `data_map` MAP<STRING, ROW<`value` BIGINT>>>,\n" + " `outer_array` ARRAY<INT>,\n" + " `outer_map` MAP<STRING, STRING>,\n" + " `chart` ROW<" + " `result` ARRAY<ROW<`meta` ROW<" + " `symbol` STRING NOT NULL> NOT NULL> NOT NULL>" + " NOT NULL>,\n" + " WATERMARK FOR `Timestamp` AS `Timestamp`\n" + ") WITH (\n" + " 'connector' = 'values',\n" + " 'bounded' = 'true'\n" + ")"; util.tableEnv().executeSql(ddl7); } @Test void testSimpleProject() { util.verifyRelPlan("SELECT a, c FROM MyTable"); } @Test void testSimpleProjectWithVirtualColumn() { util.verifyRelPlan("SELECT a, d FROM VirtualTable"); } @Test void testCannotProject() { util.verifyRelPlan("SELECT a, c, b + 1 FROM MyTable"); } @Test void testCannotProjectWithVirtualColumn() { util.verifyRelPlan("SELECT a, c, d, b + 1 FROM VirtualTable"); } @Test void testProjectWithUdf() { util.verifyRelPlan("SELECT a, TRIM(c) FROM MyTable"); } @Test void testProjectWithUdfWithVirtualColumn() { util.addTemporarySystemFunction("my_udf", Func0$.MODULE$); util.verifyRelPlan("SELECT a, my_udf(d) FROM VirtualTable"); } @Test void testProjectWithoutInputRef() { // Regression by: CALCITE-4220, // the constant project was removed, // so that the rule can not be matched. util.verifyRelPlan("SELECT COUNT(1) FROM MyTable"); } @Test void testProjectWithMapType() { String sqlQuery = "SELECT id, testMap['e']\n" + "FROM NestedTable"; util.verifyRelPlan(sqlQuery); } @Test void testNestedProject() { String sqlQuery = "SELECT id,\n" + " deepNested.nested1.name AS nestedName,\n" + " nested.`value` AS nestedValue,\n" + " deepNested.nested2.flag AS nestedFlag,\n" + " deepNested.nested2.num AS nestedNum\n" + "FROM NestedTable"; util.verifyRelPlan(sqlQuery); } @Test void testComplicatedNestedProject() { String sqlQuery = "SELECT id," + " deepNested.nested1.name AS nestedName,\n" + " (`deepNestedWith.`.`.value` + `deepNestedWith.`.nested.`.value`) AS nestedSum\n" + "FROM NestedTable"; util.verifyRelPlan(sqlQuery); } @Test void testProjectWithDuplicateMetadataKey() { String sqlQuery = "SELECT id, metadata_3, metadata_1 FROM MetadataTable"; util.verifyRelPlan(sqlQuery); } @Test void testNestProjectWithMetadata() { String sqlQuery = "SELECT id," + " deepNested.nested1 AS nested1,\n" + " deepNested.nested1.`value` + deepNested.nested2.num + metadata_1 as results\n" + "FROM MetadataTable"; util.verifyRelPlan(sqlQuery); } @Test void testNestProjectWithUpsertSource() { String sqlQuery = "SELECT id," + " deepNested.nested1 AS nested1,\n" + " deepNested.nested1.`value` + deepNested.nested2.num + metadata_1 as results\n" + "FROM MetadataTable"; util.verifyRelPlan(sqlQuery); } @Test void testNestedProjectFieldAccessWithITEM() { util.verifyRelPlan( "SELECT " + "`Result`.`Mid`.data_arr[ID].`value`, " + "`Result`.`Mid`.data_map['item'].`value` " + "FROM NestedItemTable"); } @Test void testNestedProjectFieldAccessWithITEMWithConstantIndex() { util.verifyRelPlan( "SELECT " + "`Result`.`Mid`.data_arr[2].`value`, " + "`Result`.`Mid`.data_arr " + "FROM NestedItemTable"); } @Test void testNestedProjectFieldAccessWithNestedArrayAndRows() { util.verifyRelPlan("SELECT `chart`.`result`[1].`meta`.`symbol` FROM ItemTable"); } @Test void testNestedProjectFieldAccessWithITEMContainsTopLevelAccess() { util.verifyRelPlan( "SELECT " + "`Result`.`Mid`.data_arr[2].`value`, " + "`Result`.`Mid`.data_arr[ID].`value`, " + "`Result`.`Mid`.data_map['item'].`value`, " + "`Result`.`Mid` " + "FROM NestedItemTable"); } @Test void testProjectFieldAccessWithITEM() { util.verifyRelPlan( "SELECT " + "`Result`.data_arr[ID].`value`, " + "`Result`.data_map['item'].`value`, " + "`outer_array`[1], " + "`outer_array`[ID], " + "`outer_map`['item'] " + "FROM ItemTable"); } @Test void testMetadataProjectionWithoutProjectionPushDownWhenSupported() { final SharedReference<List<String>> appliedKeys = sharedObjects.add(new ArrayList<>()); final TableDescriptor sourceDescriptor = TableFactoryHarness.newBuilder() .schema(NoPushDownSource.SCHEMA) .source(new NoPushDownSource(true, appliedKeys)) .build(); util.tableEnv().createTable("T1", sourceDescriptor); util.verifyRelPlan("SELECT m1, metadata FROM T1"); assertThat(appliedKeys.get()).contains("m1", "m2"); } @Test void testMetadataProjectionWithoutProjectionPushDownWhenNotSupported() { final SharedReference<List<String>> appliedKeys = sharedObjects.add(new ArrayList<>()); final TableDescriptor sourceDescriptor = TableFactoryHarness.newBuilder() .schema(NoPushDownSource.SCHEMA) .source(new NoPushDownSource(false, appliedKeys)) .build(); util.tableEnv().createTable("T2", sourceDescriptor); util.verifyRelPlan("SELECT m1, metadata FROM T2"); assertThat(appliedKeys.get()).contains("m1", "m2", "m3"); } @Test void testMetadataProjectionWithoutProjectionPushDownWhenSupportedAndNoneSelected() { final SharedReference<List<String>> appliedKeys = sharedObjects.add(new ArrayList<>()); final TableDescriptor sourceDescriptor = TableFactoryHarness.newBuilder() .schema(NoPushDownSource.SCHEMA) .source(new NoPushDownSource(true, appliedKeys)) .build(); util.tableEnv().createTable("T3", sourceDescriptor); util.verifyRelPlan("SELECT 1 FROM T3"); // Because we turned off the project merge in the sql2rel phase, the source node will see // the original unmerged project with all columns selected in this rule test assertThat(appliedKeys.get()).hasSize(3); } @Test void testMetadataProjectionWithoutProjectionPushDownWhenNotSupportedAndNoneSelected() { final SharedReference<List<String>> appliedKeys = sharedObjects.add(new ArrayList<>()); final TableDescriptor sourceDescriptor = TableFactoryHarness.newBuilder() .schema(NoPushDownSource.SCHEMA) .source(new NoPushDownSource(false, appliedKeys)) .build(); util.tableEnv().createTable("T4", sourceDescriptor); util.verifyRelPlan("SELECT 1 FROM T4"); assertThat(appliedKeys.get()).contains("m1", "m2", "m3"); } @Test void testProjectionIncludingOnlyMetadata() { replaceProgramWithProjectMergeRule(); final AtomicReference<DataType> appliedProjectionDataType = new AtomicReference<>(null); final AtomicReference<DataType> appliedMetadataDataType = new AtomicReference<>(null); final TableDescriptor sourceDescriptor = TableFactoryHarness.newBuilder() .schema(PushDownSource.SCHEMA) .source( new PushDownSource( appliedProjectionDataType, appliedMetadataDataType)) .build(); util.tableEnv().createTable("T5", sourceDescriptor); util.verifyRelPlan("SELECT metadata FROM T5"); assertThat(appliedProjectionDataType.get()).isNotNull(); assertThat(appliedMetadataDataType.get()).isNotNull(); assertThat(DataType.getFieldNames(appliedProjectionDataType.get())).isEmpty(); assertThat(DataType.getFieldNames(appliedMetadataDataType.get())) .containsExactly("metadata"); } private void replaceProgramWithProjectMergeRule() { FlinkChainedProgram programs = new FlinkChainedProgram<BatchOptimizeContext>(); programs.addLast( "rules", FlinkHepRuleSetProgramBuilder.<BatchOptimizeContext>newBuilder() .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE()) .setHepMatchOrder(HepMatchOrder.BOTTOM_UP) .add( RuleSets.ofList( CoreRules.PROJECT_MERGE, PushProjectIntoTableSourceScanRule.INSTANCE)) .build()); util.replaceBatchProgram(programs); } @Test void testProjectionWithMetadataAndPhysicalFields() { replaceProgramWithProjectMergeRule(); final AtomicReference<DataType> appliedProjectionDataType = new AtomicReference<>(null); final AtomicReference<DataType> appliedMetadataDataType = new AtomicReference<>(null); final TableDescriptor sourceDescriptor = TableFactoryHarness.newBuilder() .schema(PushDownSource.SCHEMA) .source( new PushDownSource( appliedProjectionDataType, appliedMetadataDataType)) .build(); util.tableEnv().createTable("T5", sourceDescriptor); util.verifyRelPlan("SELECT metadata, f1 FROM T5"); assertThat(appliedProjectionDataType.get()).isNotNull(); assertThat(appliedMetadataDataType.get()).isNotNull(); assertThat(DataType.getFieldNames(appliedProjectionDataType.get())).containsExactly("f1"); assertThat(DataType.getFieldNames(appliedMetadataDataType.get())) .isEqualTo(Arrays.asList("f1", "metadata")); } // --------------------------------------------------------------------------------------------- /** Source which supports metadata but not {@link SupportsProjectionPushDown}. */ private static
PushProjectIntoTableSourceScanRuleTest
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/XdsClientMetricReporterImplTest.java
{ "start": 2743, "end": 17265 }
class ____ { private static final String target = "test-target"; private static final String authority = "test-authority"; private static final String server = "trafficdirector.googleapis.com"; private static final String resourceTypeUrl = "resourceTypeUrl.googleapis.com/envoy.config.cluster.v3.Cluster"; @Rule public final MockitoRule mocks = MockitoJUnit.rule(); @Mock private XdsClient mockXdsClient; @Captor private ArgumentCaptor<BatchCallback> gaugeBatchCallbackCaptor; private MetricRecorder mockMetricRecorder = mock(MetricRecorder.class, delegatesTo(new MetricRecorderImpl())); private BatchRecorder mockBatchRecorder = mock(BatchRecorder.class, delegatesTo(new BatchRecorderImpl())); private XdsClientMetricReporterImpl reporter; @Before public void setUp() { reporter = new XdsClientMetricReporterImpl(mockMetricRecorder, target); } @Test public void reportResourceUpdates() { reporter.reportResourceUpdates(10, 5, server, resourceTypeUrl); verify(mockMetricRecorder).addLongCounter( eqMetricInstrumentName("grpc.xds_client.resource_updates_valid"), eq((long) 10), eq(Lists.newArrayList(target, server, resourceTypeUrl)), eq(Lists.newArrayList())); verify(mockMetricRecorder).addLongCounter( eqMetricInstrumentName("grpc.xds_client.resource_updates_invalid"), eq((long) 5), eq(Lists.newArrayList(target, server, resourceTypeUrl)), eq(Lists.newArrayList())); } @Test public void reportServerFailure() { reporter.reportServerFailure(1, server); verify(mockMetricRecorder).addLongCounter( eqMetricInstrumentName("grpc.xds_client.server_failure"), eq((long) 1), eq(Lists.newArrayList(target, server)), eq(Lists.newArrayList())); } @Test public void setXdsClient_reportMetrics() throws Exception { SettableFuture<Void> future = SettableFuture.create(); future.set(null); when(mockXdsClient.getSubscribedResourcesMetadataSnapshot()).thenReturn(Futures.immediateFuture( ImmutableMap.of())); when(mockXdsClient.reportServerConnections(any(ServerConnectionCallback.class))) .thenReturn(future); reporter.setXdsClient(mockXdsClient); verify(mockMetricRecorder).registerBatchCallback(gaugeBatchCallbackCaptor.capture(), eqMetricInstrumentName("grpc.xds_client.connected"), eqMetricInstrumentName("grpc.xds_client.resources")); gaugeBatchCallbackCaptor.getValue().accept(mockBatchRecorder); verify(mockXdsClient).reportServerConnections(any(ServerConnectionCallback.class)); } @Test public void setXdsClient_reportCallbackMetrics_resourceCountsFails() { TestlogHandler testLogHandler = new TestlogHandler(); Logger logger = Logger.getLogger(XdsClientMetricReporterImpl.class.getName()); logger.addHandler(testLogHandler); // For reporting resource counts connections, return a normally completed future SettableFuture<Void> future = SettableFuture.create(); future.set(null); when(mockXdsClient.getSubscribedResourcesMetadataSnapshot()).thenReturn(Futures.immediateFuture( ImmutableMap.of())); // Create a future that will throw an exception SettableFuture<Void> serverConnectionsFeature = SettableFuture.create(); serverConnectionsFeature.setException(new Exception("test")); when(mockXdsClient.reportServerConnections(any())).thenReturn(serverConnectionsFeature); reporter.setXdsClient(mockXdsClient); verify(mockMetricRecorder) .registerBatchCallback(gaugeBatchCallbackCaptor.capture(), any(), any()); gaugeBatchCallbackCaptor.getValue().accept(mockBatchRecorder); // Verify that the xdsClient methods were called // verify(mockXdsClient).reportResourceCounts(any()); verify(mockXdsClient).reportServerConnections(any()); assertThat(testLogHandler.getLogs().size()).isEqualTo(1); assertThat(testLogHandler.getLogs().get(0).getLevel()).isEqualTo(Level.WARNING); assertThat(testLogHandler.getLogs().get(0).getMessage()).isEqualTo( "Failed to report gauge metrics"); logger.removeHandler(testLogHandler); } @Test public void metricGauges() { SettableFuture<Void> future = SettableFuture.create(); future.set(null); when(mockXdsClient.getSubscribedResourcesMetadataSnapshot()) .thenReturn(Futures.immediateFuture(ImmutableMap.of())); when(mockXdsClient.reportServerConnections(any(ServerConnectionCallback.class))) .thenReturn(future); reporter.setXdsClient(mockXdsClient); verify(mockMetricRecorder).registerBatchCallback(gaugeBatchCallbackCaptor.capture(), eqMetricInstrumentName("grpc.xds_client.connected"), eqMetricInstrumentName("grpc.xds_client.resources")); BatchCallback gaugeBatchCallback = gaugeBatchCallbackCaptor.getValue(); InOrder inOrder = inOrder(mockBatchRecorder); // Trigger the internal call to reportCallbackMetrics() gaugeBatchCallback.accept(mockBatchRecorder); ArgumentCaptor<ServerConnectionCallback> serverConnectionCallbackCaptor = ArgumentCaptor.forClass(ServerConnectionCallback.class); // verify(mockXdsClient).reportResourceCounts(resourceCallbackCaptor.capture()); verify(mockXdsClient).reportServerConnections(serverConnectionCallbackCaptor.capture()); // Get the captured callback MetricReporterCallback callback = (MetricReporterCallback) serverConnectionCallbackCaptor.getValue(); // Verify that reportResourceCounts and reportServerConnections were called // with the captured callback callback.reportResourceCountGauge(10, "MrPotatoHead", "acked", resourceTypeUrl); inOrder.verify(mockBatchRecorder) .recordLongGauge(eqMetricInstrumentName("grpc.xds_client.resources"), eq(10L), any(), any()); callback.reportServerConnectionGauge(true, "xdsServer"); inOrder.verify(mockBatchRecorder) .recordLongGauge(eqMetricInstrumentName("grpc.xds_client.connected"), eq(1L), any(), any()); inOrder.verifyNoMoreInteractions(); } @Test public void metricReporterCallback() { MetricReporterCallback callback = new MetricReporterCallback(mockBatchRecorder, target); callback.reportServerConnectionGauge(true, server); verify(mockBatchRecorder, times(1)).recordLongGauge( eqMetricInstrumentName("grpc.xds_client.connected"), eq(1L), eq(Lists.newArrayList(target, server)), eq(Lists.newArrayList())); String cacheState = "requested"; callback.reportResourceCountGauge(10, authority, cacheState, resourceTypeUrl); verify(mockBatchRecorder, times(1)).recordLongGauge( eqMetricInstrumentName("grpc.xds_client.resources"), eq(10L), eq(Arrays.asList(target, authority, cacheState, resourceTypeUrl)), eq(Collections.emptyList())); } @Test public void reportCallbackMetrics_computeAndReportResourceCounts() { Map<XdsResourceType<?>, Map<String, ResourceMetadata>> metadataByType = new HashMap<>(); XdsResourceType<?> listenerResource = XdsListenerResource.getInstance(); XdsResourceType<?> routeConfigResource = XdsRouteConfigureResource.getInstance(); XdsResourceType<?> clusterResource = XdsClusterResource.getInstance(); Any rawListener = Any.pack(Listener.newBuilder().setName("listener.googleapis.com").build()); long nanosLastUpdate = 1577923199_606042047L; Map<String, ResourceMetadata> ldsResourceMetadataMap = new HashMap<>(); ldsResourceMetadataMap.put("xdstp://authority1", ResourceMetadata.newResourceMetadataRequested()); ResourceMetadata ackedLdsResource = ResourceMetadata.newResourceMetadataAcked(rawListener, "42", nanosLastUpdate); ldsResourceMetadataMap.put("resource2", ackedLdsResource); ldsResourceMetadataMap.put("resource3", ResourceMetadata.newResourceMetadataAcked(rawListener, "43", nanosLastUpdate)); ldsResourceMetadataMap.put("xdstp:/no_authority", ResourceMetadata.newResourceMetadataNacked(ackedLdsResource, "44", nanosLastUpdate, "nacked after previous ack", true)); Map<String, ResourceMetadata> rdsResourceMetadataMap = new HashMap<>(); ResourceMetadata requestedRdsResourceMetadata = ResourceMetadata.newResourceMetadataRequested(); rdsResourceMetadataMap.put("xdstp://authority5", ResourceMetadata.newResourceMetadataNacked(requestedRdsResourceMetadata, "24", nanosLastUpdate, "nacked after request", false)); rdsResourceMetadataMap.put("xdstp://authority6", ResourceMetadata.newResourceMetadataDoesNotExist()); Map<String, ResourceMetadata> cdsResourceMetadataMap = new HashMap<>(); cdsResourceMetadataMap.put("xdstp://authority7", ResourceMetadata.newResourceMetadataUnknown()); metadataByType.put(listenerResource, ldsResourceMetadataMap); metadataByType.put(routeConfigResource, rdsResourceMetadataMap); metadataByType.put(clusterResource, cdsResourceMetadataMap); SettableFuture<Void> reportServerConnectionsCompleted = SettableFuture.create(); reportServerConnectionsCompleted.set(null); when(mockXdsClient.reportServerConnections(any(MetricReporterCallback.class))) .thenReturn(reportServerConnectionsCompleted); ListenableFuture<Map<XdsResourceType<?>, Map<String, ResourceMetadata>>> getResourceMetadataCompleted = Futures.immediateFuture(metadataByType); when(mockXdsClient.getSubscribedResourcesMetadataSnapshot()) .thenReturn(getResourceMetadataCompleted); reporter.reportCallbackMetrics(mockBatchRecorder, mockXdsClient); // LDS resource requested verify(mockBatchRecorder).recordLongGauge(eqMetricInstrumentName("grpc.xds_client.resources"), eq(1L), eq(Arrays.asList(target, "authority1", "requested", listenerResource.typeUrl())), any()); // LDS resources acked // authority = #old, for non-xdstp resource names verify(mockBatchRecorder).recordLongGauge(eqMetricInstrumentName("grpc.xds_client.resources"), eq(2L), eq(Arrays.asList(target, "#old", "acked", listenerResource.typeUrl())), any()); // LDS resource nacked but cached // "" for missing authority in the resource name verify(mockBatchRecorder).recordLongGauge(eqMetricInstrumentName("grpc.xds_client.resources"), eq(1L), eq(Arrays.asList(target, "", "nacked_but_cached", listenerResource.typeUrl())), any()); // RDS resource nacked verify(mockBatchRecorder).recordLongGauge(eqMetricInstrumentName("grpc.xds_client.resources"), eq(1L), eq(Arrays.asList(target, "authority5", "nacked", routeConfigResource.typeUrl())), any()); // RDS resource does not exist verify(mockBatchRecorder).recordLongGauge(eqMetricInstrumentName("grpc.xds_client.resources"), eq(1L), eq(Arrays.asList(target, "authority6", "does_not_exist", routeConfigResource.typeUrl())), any()); // CDS resource unknown verify(mockBatchRecorder).recordLongGauge(eqMetricInstrumentName("grpc.xds_client.resources"), eq(1L), eq(Arrays.asList(target, "authority7", "unknown", clusterResource.typeUrl())), any()); verifyNoMoreInteractions(mockBatchRecorder); } @Test public void reportCallbackMetrics_computeAndReportResourceCounts_emptyResources() { Map<XdsResourceType<?>, Map<String, ResourceMetadata>> metadataByType = new HashMap<>(); XdsResourceType<?> listenerResource = XdsListenerResource.getInstance(); metadataByType.put(listenerResource, Collections.emptyMap()); SettableFuture<Void> reportServerConnectionsCompleted = SettableFuture.create(); reportServerConnectionsCompleted.set(null); when(mockXdsClient.reportServerConnections(any(MetricReporterCallback.class))) .thenReturn(reportServerConnectionsCompleted); ListenableFuture<Map<XdsResourceType<?>, Map<String, ResourceMetadata>>> getResourceMetadataCompleted = Futures.immediateFuture(metadataByType); when(mockXdsClient.getSubscribedResourcesMetadataSnapshot()) .thenReturn(getResourceMetadataCompleted); reporter.reportCallbackMetrics(mockBatchRecorder, mockXdsClient); // Verify that reportResourceCountGauge is never called verifyNoInteractions(mockBatchRecorder); } @Test public void reportCallbackMetrics_computeAndReportResourceCounts_nullMetadata() { TestlogHandler testLogHandler = new TestlogHandler(); Logger logger = Logger.getLogger(XdsClientMetricReporterImpl.class.getName()); logger.addHandler(testLogHandler); SettableFuture<Void> reportServerConnectionsCompleted = SettableFuture.create(); reportServerConnectionsCompleted.set(null); when(mockXdsClient.reportServerConnections(any(MetricReporterCallback.class))) .thenReturn(reportServerConnectionsCompleted); ListenableFuture<Map<XdsResourceType<?>, Map<String, ResourceMetadata>>> getResourceMetadataCompleted = Futures.immediateFailedFuture( new Exception("Error generating metadata snapshot")); when(mockXdsClient.getSubscribedResourcesMetadataSnapshot()) .thenReturn(getResourceMetadataCompleted); reporter.reportCallbackMetrics(mockBatchRecorder, mockXdsClient); assertThat(testLogHandler.getLogs().size()).isEqualTo(1); assertThat(testLogHandler.getLogs().get(0).getLevel()).isEqualTo(Level.WARNING); assertThat(testLogHandler.getLogs().get(0).getMessage()).isEqualTo( "Failed to report gauge metrics"); logger.removeHandler(testLogHandler); } @Test public void close_closesGaugeRegistration() { MetricSink.Registration mockRegistration = mock(MetricSink.Registration.class); when(mockMetricRecorder.registerBatchCallback(any(MetricRecorder.BatchCallback.class), eqMetricInstrumentName("grpc.xds_client.connected"), eqMetricInstrumentName("grpc.xds_client.resources"))).thenReturn(mockRegistration); // Sets XdsClient and register the gauges reporter.setXdsClient(mockXdsClient); // Closes registered gauges reporter.close(); verify(mockRegistration, times(1)).close(); } @SuppressWarnings("TypeParameterUnusedInFormals") private <T extends MetricInstrument> T eqMetricInstrumentName(String name) { return argThat(new ArgumentMatcher<T>() { @Override public boolean matches(T instrument) { return instrument.getName().equals(name); } }); } static
XdsClientMetricReporterImplTest
java
quarkusio__quarkus
test-framework/vertx/src/main/java/io/quarkus/test/vertx/DefaultUniAsserter.java
{ "start": 318, "end": 6280 }
class ____ implements UnwrappableUniAsserter { private final ConcurrentMap<String, Object> data; // A Uni used to chain the various operations together and allow us to subscribe to the result Uni<?> execution; public DefaultUniAsserter() { this.execution = Uni.createFrom().item(new Object()); this.data = new ConcurrentHashMap<>(); } @Override public Uni<?> asUni() { return execution; } @SuppressWarnings("unchecked") @Override public <T> UniAsserter assertThat(Supplier<Uni<T>> uni, Consumer<T> asserter) { execution = uniFromSupplier(uni) .onItem() .invoke(new Consumer<Object>() { @Override public void accept(Object o) { asserter.accept((T) o); } }); return this; } @Override public <T> UniAsserter execute(Supplier<Uni<T>> uni) { execution = uniFromSupplier(uni); return this; } @Override public UniAsserter execute(Runnable c) { execution = execution.onItem().invoke(c); return this; } @Override public <T> UniAsserter assertEquals(Supplier<Uni<T>> uni, T t) { execution = uniFromSupplier(uni) .onItem() .invoke(new Consumer<Object>() { @Override public void accept(Object o) { Assertions.assertEquals(t, o); } }); return this; } @Override public <T> UniAsserter assertSame(Supplier<Uni<T>> uni, T t) { execution = uniFromSupplier(uni) .onItem() .invoke(new Consumer<Object>() { @Override public void accept(Object o) { Assertions.assertSame(t, o); } }); return this; } @Override public <T> UniAsserter assertNull(Supplier<Uni<T>> uni) { execution = uniFromSupplier(uni).onItem().invoke(Assertions::assertNull); return this; } @SuppressWarnings({ "rawtypes", "unchecked" }) private <T> Uni<T> uniFromSupplier(Supplier<Uni<T>> uni) { return execution.onItem() .transformToUni((Function) new Function<Object, Uni<T>>() { @Override public Uni<T> apply(Object o) { return uni.get(); } }); } @Override public <T> UniAsserter assertNotEquals(Supplier<Uni<T>> uni, T t) { execution = uniFromSupplier(uni) .onItem() .invoke(new Consumer<Object>() { @Override public void accept(Object o) { Assertions.assertNotEquals(t, o); } }); return this; } @Override public <T> UniAsserter assertNotSame(Supplier<Uni<T>> uni, T t) { execution = uniFromSupplier(uni) .onItem() .invoke(new Consumer<Object>() { @Override public void accept(Object o) { Assertions.assertNotSame(t, o); } }); return this; } @Override public <T> UniAsserter assertNotNull(Supplier<Uni<T>> uni) { execution = uniFromSupplier(uni).onItem().invoke(Assertions::assertNotNull); return this; } @SuppressWarnings("unchecked") @Override public <T> UniAsserter surroundWith(Function<Uni<T>, Uni<T>> uni) { execution = uni.apply((Uni<T>) execution); return this; } @Override public UniAsserter assertFalse(Supplier<Uni<Boolean>> uni) { execution = uniFromSupplier(uni).onItem().invoke(Assertions::assertFalse); return this; } @Override public UniAsserter assertTrue(Supplier<Uni<Boolean>> uni) { execution = uniFromSupplier(uni).onItem().invoke(Assertions::assertTrue); return this; } @Override public UniAsserter fail() { execution = execution.onItem().invoke(v -> Assertions.fail()); return this; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public <T> UniAsserter assertFailedWith(Supplier<Uni<T>> uni, Consumer<Throwable> c) { execution = execution.onItem() .transformToUni((Function) new Function<Object, Uni<T>>() { @Override public Uni<T> apply(Object obj) { return uni.get().onItemOrFailure().transformToUni((o, t) -> { if (t == null) { return Uni.createFrom().failure(() -> Assertions.fail("Uni did not contain a failure.")); } else { return Uni.createFrom().item(() -> { c.accept(t); return null; }); } }); } }); return this; } @Override public <T> UniAsserter assertFailedWith(Supplier<Uni<T>> uni, Class<? extends Throwable> c) { return assertFailedWith(uni, t -> { if (!c.isInstance(t)) { Assertions.fail(String.format("Uni failure type '%s' was not of the expected type '%s'.", t.getClass().getName(), c.getName())); } }); } @Override public Object getData(String key) { return data.get(key); } @Override public Object putData(String key, Object value) { return data.put(key, value); } @Override public void clearData() { data.clear(); } }
DefaultUniAsserter
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/db2/DB2SelectTest_6.java
{ "start": 1037, "end": 2702 }
class ____ extends DB2Test { public void test_0() throws Exception { String sql = "SELECT all id FROM DSN81010.EMP;"; DB2StatementParser parser = new DB2StatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); DB2SchemaStatVisitor visitor = new DB2SchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(1, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("DSN81010.EMP"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "last_name"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "first_name"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "full_name"))); assertEquals("SELECT ALL id" + "\nFROM DSN81010.EMP;", // SQLUtils.toSQLString(stmt, JdbcConstants.DB2)); assertEquals("select all id" + "\nfrom DSN81010.EMP;", // SQLUtils.toSQLString(stmt, JdbcConstants.DB2, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); } }
DB2SelectTest_6
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_isBetween_Test.java
{ "start": 820, "end": 1285 }
class ____ extends AbstractLocalDateTimeAssertBaseTest { @Override protected LocalDateTimeAssert invoke_api_method() { return assertions.isBetween(YESTERDAY, TOMORROW); } @Override protected void verify_internal_effects() { verify(getComparables(assertions)).assertIsBetween(getInfo(assertions), getActual(assertions), YESTERDAY, TOMORROW, true, true); } }
LocalDateTimeAssert_isBetween_Test
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/TestS3AAWSCredentialsProvider.java
{ "start": 15513, "end": 16023 }
class ____ extends AbstractProvider { @SuppressWarnings("unused") public ConstructorFailureProvider() { throw new NullPointerException("oops"); } } @Test public void testAWSExceptionTranslation() throws Throwable { IOException ex = expectProviderInstantiationFailure( AWSExceptionRaisingFactory.class, AWSExceptionRaisingFactory.NO_AUTH); if (!(ex instanceof AccessDeniedException)) { throw ex; } } protected static
ConstructorFailureProvider
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/entities/Department.java
{ "start": 454, "end": 788 }
class ____ implements Serializable { private Long id; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_DEPT") @jakarta.persistence.SequenceGenerator( name = "SEQ_DEPT", sequenceName = "my_sequence" ) public Long getId() { return id; } public void setId(Long long1) { id = long1; } }
Department
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/ValuesRestoreTest.java
{ "start": 1207, "end": 1511 }
class ____ extends RestoreTestBase { public ValuesRestoreTest() { super(StreamExecValues.class, AfterRestoreSource.NO_RESTORE); } @Override public List<TableTestProgram> programs() { return Collections.singletonList(ValuesTestPrograms.VALUES_TEST); } }
ValuesRestoreTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/lock/internal/TransactSQLLockingSupport.java
{ "start": 842, "end": 3244 }
class ____ extends LockingSupportParameterized { public static final LockingSupport SQL_SERVER = new TransactSQLLockingSupport( PessimisticLockStyle.TABLE_HINT, LockTimeoutType.CONNECTION, LockTimeoutType.QUERY, LockTimeoutType.QUERY, RowLockStrategy.TABLE, OuterJoinLockingType.IDENTIFIED, SQLServerImpl.IMPL ); public static final LockingSupport SYBASE = new TransactSQLLockingSupport( PessimisticLockStyle.TABLE_HINT, LockTimeoutType.CONNECTION, LockTimeoutType.QUERY, LockTimeoutType.NONE, RowLockStrategy.TABLE, OuterJoinLockingType.IDENTIFIED, SybaseImpl.IMPL ); public static final LockingSupport SYBASE_ASE = new TransactSQLLockingSupport( PessimisticLockStyle.TABLE_HINT, LockTimeoutType.CONNECTION, LockTimeoutType.NONE, LockTimeoutType.NONE, RowLockStrategy.TABLE, OuterJoinLockingType.IDENTIFIED, SybaseImpl.IMPL ); public static final LockingSupport SYBASE_LEGACY = new TransactSQLLockingSupport( PessimisticLockStyle.TABLE_HINT, LockTimeoutType.CONNECTION, LockTimeoutType.NONE, LockTimeoutType.NONE, RowLockStrategy.TABLE, OuterJoinLockingType.IDENTIFIED, SybaseImpl.IMPL ); public static LockingSupport forSybaseAnywhere(DatabaseVersion version) { return new TransactSQLLockingSupport( version.isBefore( 10 ) ? PessimisticLockStyle.TABLE_HINT : PessimisticLockStyle.CLAUSE, LockTimeoutType.CONNECTION, LockTimeoutType.NONE, LockTimeoutType.NONE, version.isSameOrAfter( 10 ) ? RowLockStrategy.COLUMN : RowLockStrategy.TABLE, OuterJoinLockingType.IDENTIFIED, SybaseImpl.IMPL ); } private final ConnectionLockTimeoutStrategy connectionLockTimeoutStrategy; public TransactSQLLockingSupport( PessimisticLockStyle pessimisticLockStyle, LockTimeoutType wait, LockTimeoutType noWait, LockTimeoutType skipLocked, RowLockStrategy rowLockStrategy, OuterJoinLockingType outerJoinLockingType, ConnectionLockTimeoutStrategy connectionLockTimeoutStrategy) { super( pessimisticLockStyle, rowLockStrategy, wait, noWait, skipLocked, outerJoinLockingType ); this.connectionLockTimeoutStrategy = connectionLockTimeoutStrategy; } @Override public ConnectionLockTimeoutStrategy getConnectionLockTimeoutStrategy() { return connectionLockTimeoutStrategy; } public static
TransactSQLLockingSupport
java
google__guava
android/guava/src/com/google/common/collect/FilteredEntryMultimap.java
{ "start": 5284, "end": 6797 }
class ____ extends ViewCachingAbstractMap<K, Collection<V>> { @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override public void clear() { FilteredEntryMultimap.this.clear(); } @Override public @Nullable Collection<V> get(@Nullable Object key) { Collection<V> result = unfiltered.asMap().get(key); if (result == null) { return null; } @SuppressWarnings("unchecked") // key is equal to a K, if not a K itself K k = (K) key; result = filterCollection(result, new ValuePredicate(k)); return result.isEmpty() ? null : result; } @Override public @Nullable Collection<V> remove(@Nullable Object key) { Collection<V> collection = unfiltered.asMap().get(key); if (collection == null) { return null; } @SuppressWarnings("unchecked") // it's definitely equal to a K K k = (K) key; List<V> result = new ArrayList<>(); Iterator<V> itr = collection.iterator(); while (itr.hasNext()) { V v = itr.next(); if (satisfies(k, v)) { itr.remove(); result.add(v); } } if (result.isEmpty()) { return null; } else if (unfiltered instanceof SetMultimap) { return unmodifiableSet(new LinkedHashSet<>(result)); } else { return unmodifiableList(result); } } @Override Set<K> createKeySet() { @WeakOuter final
AsMap
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/InterfaceWithImplTest.java
{ "start": 1147, "end": 1447 }
interface ____ { @GET @Produces(MediaType.TEXT_PLAIN) @Path("/greeting/{name}") String greeting(String name); @GET @Produces(MediaType.TEXT_PLAIN) @Path("/greeting2/{name}") String greeting2(String name); } public static
Greeting
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/selection/qualifier/handwritten/Reverse.java
{ "start": 255, "end": 410 }
class ____ { public String reverse( String in ) { StringBuilder b = new StringBuilder(in); return b.reverse().toString(); } }
Reverse
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/TypeParameterShadowingTest.java
{ "start": 1011, "end": 1512 }
class ____ { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(TypeParameterShadowing.class, getClass()); private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(TypeParameterShadowing.class, getClass()); @Test public void singleLevel() { compilationHelper .addSourceLines( "Test.java", """ package foo.bar;
TypeParameterShadowingTest
java
elastic__elasticsearch
build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/release/ExtractCurrentVersionsTaskTests.java
{ "start": 999, "end": 1581 }
class ____ { public static final Version V_1 = def(1); public static final Version V_2 = def(2); public static final Version V_3 = def(3); // ignore fields with no or more than one int public static final Version REF = V_3; public static final Version COMPUTED = compute(100, 200); }"""); FieldIdExtractor extractor = new FieldIdExtractor(); unit.walk(FieldDeclaration.class, extractor); assertThat(extractor.highestVersionId(), is(3)); } }
Version
java
junit-team__junit5
junit-platform-reporting/src/main/java/org/junit/platform/reporting/open/xml/GitInfoCollector.java
{ "start": 3891, "end": 5826 }
class ____ { private final Path workingDir; ProcessExecutor(Path workingDir) { this.workingDir = workingDir; } Optional<String> exec(String... args) { Process process = startProcess(args); try (Reader out = newBufferedReader(process.getInputStream()); Reader err = newBufferedReader(process.getErrorStream())) { StringBuilder output = new StringBuilder(); readAllChars(out, (chars, numChars) -> output.append(chars, 0, numChars)); readAllChars(err, (__, ___) -> { // ignore }); boolean terminated = process.waitFor(10, TimeUnit.SECONDS); return terminated && process.exitValue() == 0 ? Optional.of(trimAtEnd(output)) : Optional.empty(); } catch (InterruptedException e) { throw ExceptionUtils.throwAsUncheckedException(e); } catch (IOException ignore) { return Optional.empty(); } finally { process.destroyForcibly(); } } private static BufferedReader newBufferedReader(InputStream stream) { return new BufferedReader(new InputStreamReader(stream, Charset.defaultCharset())); } private Process startProcess(String[] command) { Process process; try { process = new ProcessBuilder().directory(workingDir.toFile()).command(command).start(); } catch (IOException e) { throw new UncheckedIOException("Failed to start process", e); } return process; } private static void readAllChars(Reader reader, BiConsumer<char[], Integer> consumer) throws IOException { char[] buffer = new char[1024]; int numChars; while ((numChars = reader.read(buffer)) != -1) { consumer.accept(buffer, numChars); } } private static String trimAtEnd(StringBuilder value) { int endIndex = value.length(); for (int i = value.length() - 1; i >= 0; i--) { if (Character.isWhitespace(value.charAt(i))) { endIndex--; break; } } return value.substring(0, endIndex); } }
ProcessExecutor
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-cache/src/main/java/smoketest/cache/SampleCacheApplication.java
{ "start": 977, "end": 1155 }
class ____ { public static void main(String[] args) { new SpringApplicationBuilder().sources(SampleCacheApplication.class).profiles("app").run(args); } }
SampleCacheApplication
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/DatafeedRunner.java
{ "start": 2875, "end": 19258 }
class ____ { private static final Logger logger = LogManager.getLogger(DatafeedRunner.class); private final Client client; private final ClusterService clusterService; private final ThreadPool threadPool; private final LongSupplier currentTimeSupplier; private final AnomalyDetectionAuditor auditor; // Use allocationId as key instead of datafeed id private final ConcurrentMap<Long, Holder> runningDatafeedsOnThisNode = new ConcurrentHashMap<>(); private final DatafeedJobBuilder datafeedJobBuilder; private final TaskRunner taskRunner = new TaskRunner(); private final AutodetectProcessManager autodetectProcessManager; private final DatafeedContextProvider datafeedContextProvider; public DatafeedRunner( ThreadPool threadPool, Client client, ClusterService clusterService, DatafeedJobBuilder datafeedJobBuilder, LongSupplier currentTimeSupplier, AnomalyDetectionAuditor auditor, AutodetectProcessManager autodetectProcessManager, DatafeedContextProvider datafeedContextProvider ) { this.client = Objects.requireNonNull(client); this.clusterService = Objects.requireNonNull(clusterService); this.threadPool = Objects.requireNonNull(threadPool); this.currentTimeSupplier = Objects.requireNonNull(currentTimeSupplier); this.auditor = Objects.requireNonNull(auditor); this.datafeedJobBuilder = Objects.requireNonNull(datafeedJobBuilder); this.autodetectProcessManager = Objects.requireNonNull(autodetectProcessManager); this.datafeedContextProvider = Objects.requireNonNull(datafeedContextProvider); clusterService.addListener(taskRunner); } public void run(TransportStartDatafeedAction.DatafeedTask task, Consumer<Exception> finishHandler) { ActionListener<DatafeedJob> datafeedJobHandler = ActionListener.wrap(datafeedJob -> { String jobId = datafeedJob.getJobId(); Holder holder = new Holder( task, task.getDatafeedId(), datafeedJob, new ProblemTracker(auditor, jobId, datafeedJob.numberOfSearchesIn24Hours()), finishHandler ); StoppedOrIsolated stoppedOrIsolated = task.executeIfNotStoppedOrIsolated( () -> runningDatafeedsOnThisNode.put(task.getAllocationId(), holder) ); if (stoppedOrIsolated == StoppedOrIsolated.NEITHER) { task.updatePersistentTaskState(DatafeedState.STARTED, new ActionListener<>() { @Override public void onResponse(PersistentTask<?> persistentTask) { taskRunner.runWhenJobIsOpened(task, jobId); } @Override public void onFailure(Exception e) { if (ExceptionsHelper.unwrapCause(e) instanceof ResourceNotFoundException) { // The task was stopped in the meantime, no need to do anything logger.info("[{}] Aborting as datafeed has been stopped", task.getDatafeedId()); runningDatafeedsOnThisNode.remove(task.getAllocationId()); finishHandler.accept(null); } else { finishHandler.accept(e); } } }); } else { logger.info( "[{}] Datafeed has been {} before running", task.getDatafeedId(), stoppedOrIsolated.toString().toLowerCase(Locale.ROOT) ); finishHandler.accept(null); } }, finishHandler); ActionListener<DatafeedContext> datafeedContextListener = ActionListener.wrap(datafeedContext -> { StoppedOrIsolated stoppedOrIsolated = task.getStoppedOrIsolated(); if (stoppedOrIsolated == StoppedOrIsolated.NEITHER) { datafeedJobBuilder.build(task, datafeedContext, datafeedJobHandler); } else { logger.info( "[{}] Datafeed has been {} while building context", task.getDatafeedId(), stoppedOrIsolated.toString().toLowerCase(Locale.ROOT) ); finishHandler.accept(null); } }, finishHandler); datafeedContextProvider.buildDatafeedContext(task.getDatafeedId(), datafeedContextListener); } public void stopDatafeed(TransportStartDatafeedAction.DatafeedTask task, String reason, TimeValue timeout) { logger.info("[{}] attempt to stop datafeed [{}] [{}]", reason, task.getDatafeedId(), task.getAllocationId()); Holder holder = runningDatafeedsOnThisNode.remove(task.getAllocationId()); if (holder != null) { holder.stop(reason, timeout, null); } } /** * This is used when the license expires. */ public void stopAllDatafeedsOnThisNode(String reason) { int numDatafeeds = runningDatafeedsOnThisNode.size(); if (numDatafeeds != 0) { logger.info("Closing [{}] datafeeds, because [{}]", numDatafeeds, reason); for (Holder holder : runningDatafeedsOnThisNode.values()) { holder.stop(reason, TimeValue.timeValueSeconds(20), null); } } } /** * This is used before the JVM is killed. It differs from {@link #stopAllDatafeedsOnThisNode} in that it * leaves the datafeed tasks in the "started" state, so that they get restarted on a different node. It * differs from {@link #vacateAllDatafeedsOnThisNode} in that it does not proactively relocate the persistent * tasks. With this method the assumption is that the JVM is going to be killed almost immediately, whereas * {@link #vacateAllDatafeedsOnThisNode} is used with more graceful shutdowns. */ public void prepareForImmediateShutdown() { Iterator<Holder> iter = runningDatafeedsOnThisNode.values().iterator(); while (iter.hasNext()) { iter.next().setNodeIsShuttingDown(); iter.remove(); } } public void isolateDatafeed(TransportStartDatafeedAction.DatafeedTask task) { // This calls get() rather than remove() because we expect that the persistent task will // be removed shortly afterwards and that operation needs to be able to find the holder Holder holder = runningDatafeedsOnThisNode.get(task.getAllocationId()); if (holder != null) { holder.isolateDatafeed(); } } /** * Like {@link #prepareForImmediateShutdown} this is used when the node is * going to shut down. However, the difference is that in this case it's going to be a * graceful shutdown, which could take a lot longer than the second or two expected in the * case where {@link #prepareForImmediateShutdown} is called. Therefore, * in this case we actively ask for the datafeed persistent tasks to be unassigned, so that * they can restart on a different node as soon as <em>their</em> corresponding job has * persisted its state. This means the small jobs can potentially restart sooner than if * nothing relocated until <em>all</em> graceful shutdown activities on the node were * complete. */ public void vacateAllDatafeedsOnThisNode(String reason) { for (Holder holder : runningDatafeedsOnThisNode.values()) { if (holder.isIsolated() == false) { holder.vacateNode(reason); } } } public boolean finishedLookBack(TransportStartDatafeedAction.DatafeedTask task) { Holder holder = runningDatafeedsOnThisNode.get(task.getAllocationId()); return holder != null && holder.isLookbackFinished(); } public SearchInterval getSearchInterval(TransportStartDatafeedAction.DatafeedTask task) { Holder holder = runningDatafeedsOnThisNode.get(task.getAllocationId()); return holder == null ? null : holder.datafeedJob.getSearchInterval(); } // Important: Holder must be created and assigned to DatafeedTask before setting state to started, // otherwise if a stop datafeed call is made immediately after the start datafeed call we could cancel // the DatafeedTask without stopping datafeed, which causes the datafeed to keep on running. private void innerRun(Holder holder, long startTime, Long endTime) { holder.cancellable = Scheduler.wrapAsCancellable( threadPool.executor(MachineLearning.DATAFEED_THREAD_POOL_NAME).submit(new AbstractRunnable() { @Override public void onFailure(Exception e) { logger.error("Failed lookback import for job [" + holder.datafeedJob.getJobId() + "]", e); holder.stop("general_lookback_failure", TimeValue.timeValueSeconds(20), e); } @Override protected void doRun() { Long next = null; try { next = holder.executeLookBack(startTime, endTime); } catch (DatafeedJob.ExtractionProblemException e) { if (endTime == null) { next = e.nextDelayInMsSinceEpoch; } holder.problemTracker.reportExtractionProblem(e); } catch (DatafeedJob.AnalysisProblemException e) { if (endTime == null) { next = e.nextDelayInMsSinceEpoch; } holder.problemTracker.reportAnalysisProblem(e); if (e.shouldStop) { holder.stop("lookback_analysis_error", TimeValue.timeValueSeconds(20), e); return; } } catch (DatafeedJob.EmptyDataCountException e) { if (endTime == null) { holder.problemTracker.reportEmptyDataCount(); next = e.nextDelayInMsSinceEpoch; } else { // Notify that a lookback-only run found no data String lookbackNoDataMsg = Messages.getMessage(Messages.JOB_AUDIT_DATAFEED_LOOKBACK_NO_DATA); logger.warn("[{}] {}", holder.datafeedJob.getJobId(), lookbackNoDataMsg); auditor.warning(holder.datafeedJob.getJobId(), lookbackNoDataMsg); } } catch (Exception e) { logger.error("Failed lookback import for job [" + holder.datafeedJob.getJobId() + "]", e); holder.stop("general_lookback_failure", TimeValue.timeValueSeconds(20), e); return; } holder.finishedLookback(true); if (holder.isIsolated() == false) { if (next != null) { doDatafeedRealtime(next, holder.datafeedJob.getJobId(), holder); } else { holder.stop("no_realtime", TimeValue.timeValueSeconds(20), null); holder.problemTracker.finishReport(); } } } }) ); } void doDatafeedRealtime(long delayInMsSinceEpoch, String jobId, Holder holder) { if (holder.isRunning() && holder.isIsolated() == false) { TimeValue delay = computeNextDelay(delayInMsSinceEpoch); logger.debug("Waiting [{}] before executing next realtime import for job [{}]", delay, jobId); holder.cancellable = threadPool.schedule(new AbstractRunnable() { @Override public void onFailure(Exception e) { logger.error("Unexpected datafeed failure for job [" + jobId + "] stopping...", e); holder.stop("general_realtime_error", TimeValue.timeValueSeconds(20), e); } @Override protected void doRun() { long nextDelayInMsSinceEpoch; try { nextDelayInMsSinceEpoch = holder.executeRealTime(); holder.problemTracker.reportNonEmptyDataCount(); } catch (DatafeedJob.ExtractionProblemException e) { nextDelayInMsSinceEpoch = e.nextDelayInMsSinceEpoch; holder.problemTracker.reportExtractionProblem(e); } catch (DatafeedJob.AnalysisProblemException e) { nextDelayInMsSinceEpoch = e.nextDelayInMsSinceEpoch; holder.problemTracker.reportAnalysisProblem(e); if (e.shouldStop) { holder.stop("realtime_analysis_error", TimeValue.timeValueSeconds(20), e); return; } } catch (DatafeedJob.EmptyDataCountException e) { int emptyDataCount = holder.problemTracker.reportEmptyDataCount(); if (e.haveEverSeenData == false && holder.shouldStopAfterEmptyData(emptyDataCount)) { String noDataMessage = "Datafeed for [" + jobId + "] has seen no data in [" + emptyDataCount + "] attempts, and never seen any data previously, so stopping..."; logger.warn(noDataMessage); // In this case we auto-close the job, as though a lookback-only datafeed stopped holder.stop("no_data", TimeValue.timeValueSeconds(20), e, true, noDataMessage); return; } nextDelayInMsSinceEpoch = e.nextDelayInMsSinceEpoch; } catch (Exception e) { logger.error("Unexpected datafeed failure for job [" + jobId + "] stopping...", e); holder.stop("general_realtime_error", TimeValue.timeValueSeconds(20), e); return; } holder.problemTracker.finishReport(); if (nextDelayInMsSinceEpoch >= 0) { doDatafeedRealtime(nextDelayInMsSinceEpoch, jobId, holder); } } }, delay, threadPool.executor(MachineLearning.DATAFEED_THREAD_POOL_NAME)); } } /** * Returns <code>null</code> if the datafeed is not running on this node. */ private String getJobIdIfDatafeedRunningOnThisNode(TransportStartDatafeedAction.DatafeedTask task) { Holder holder = runningDatafeedsOnThisNode.get(task.getAllocationId()); if (holder == null) { return null; } return holder.getJobId(); } private static JobState getJobState(PersistentTasksCustomMetadata tasks, String jobId) { return MlTasks.getJobStateModifiedForReassignments(jobId, tasks); } private boolean jobHasOpenAutodetectCommunicator(PersistentTasksCustomMetadata tasks, String jobId) { PersistentTasksCustomMetadata.PersistentTask<?> jobTask = MlTasks.getJobTask(jobId, tasks); if (jobTask == null) { return false; } JobTaskState state = (JobTaskState) jobTask.getState(); if (state == null || state.isStatusStale(jobTask)) { return false; } return autodetectProcessManager.hasOpenAutodetectCommunicator(jobTask.getAllocationId()); } private TimeValue computeNextDelay(long next) { return new TimeValue(Math.max(1, next - currentTimeSupplier.getAsLong())); } /** * Visible for testing */ boolean isRunning(TransportStartDatafeedAction.DatafeedTask task) { return runningDatafeedsOnThisNode.containsKey(task.getAllocationId()); } public
DatafeedRunner
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/generics/inheritance/JobDaoClient.java
{ "start": 103, "end": 237 }
class ____ extends DaoClient<Job> { public JobDaoClient(Dao<Job> constructorDao) { super(constructorDao); } }
JobDaoClient
java
netty__netty
testsuite-autobahn/src/main/java/io/netty/testsuite/autobahn/AutobahnServerInitializer.java
{ "start": 924, "end": 1330 }
class ____ extends ChannelInitializer<SocketChannel> { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("handler", new AutobahnServerHandler()); } }
AutobahnServerInitializer
java
spring-projects__spring-boot
module/spring-boot-http-codec/src/main/java/org/springframework/boot/http/codec/CodecCustomizer.java
{ "start": 744, "end": 948 }
interface ____ can be used to customize codecs configuration for an HTTP * client and/or server with a {@link CodecConfigurer}. * * @author Brian Clozel * @since 4.0.0 */ @FunctionalInterface public
that
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/scalar/ToTimestampLtzFunction.java
{ "start": 3130, "end": 5348 }
class ____ extends BuiltInScalarFunction { private static final int DEFAULT_PRECISION = 3; public ToTimestampLtzFunction(SpecializedFunction.SpecializedContext context) { super(BuiltInFunctionDefinitions.TO_TIMESTAMP_LTZ, context); } public @Nullable TimestampData eval(Number epoch, Integer precision) { if (epoch == null || precision == null) { return null; } if (epoch instanceof Float || epoch instanceof Double) { return DateTimeUtils.toTimestampData(epoch.doubleValue(), precision); } return DateTimeUtils.toTimestampData(epoch.longValue(), precision); } public @Nullable TimestampData eval(DecimalData epoch, Integer precision) { if (epoch == null || precision == null) { return null; } return DateTimeUtils.toTimestampData(epoch, precision); } public @Nullable TimestampData eval(Number epoch) { return eval(epoch, DEFAULT_PRECISION); } public @Nullable TimestampData eval(DecimalData epoch) { return eval(epoch, DEFAULT_PRECISION); } public @Nullable TimestampData eval(StringData timestamp) { if (timestamp == null) { return null; } return parseTimestampData(timestamp.toString()); } public @Nullable TimestampData eval(StringData timestamp, StringData format) { if (timestamp == null || format == null) { return null; } return parseTimestampData(timestamp.toString(), format.toString()); } public @Nullable TimestampData eval( StringData dateStr, StringData format, StringData timezone) { if (dateStr == null || format == null || timezone == null) { return null; } TimestampData ts = parseTimestampData(dateStr.toString(), format.toString()); if (ts == null) { return null; } try { ZonedDateTime zoneDate = ts.toLocalDateTime().atZone(ZoneId.of(timezone.toString())); return TimestampData.fromInstant(zoneDate.toInstant()); } catch (DateTimeException e) { return null; } } }
ToTimestampLtzFunction
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java
{ "start": 1765, "end": 7339 }
class ____ extends ESTestCase { public static final SearchExecutionContext MOCK_CONTEXT = createMockSearchExecutionContext(true); public static final SearchExecutionContext MOCK_CONTEXT_DISALLOW_EXPENSIVE = createMockSearchExecutionContext(false); protected SearchExecutionContext randomMockContext() { return randomFrom(MOCK_CONTEXT, MOCK_CONTEXT_DISALLOW_EXPENSIVE); } private static SearchExecutionContext createMockSearchExecutionContext(boolean allowExpensiveQueries) { SearchExecutionContext searchExecutionContext = mock(SearchExecutionContext.class); when(searchExecutionContext.allowExpensiveQueries()).thenReturn(allowExpensiveQueries); when(searchExecutionContext.isSourceEnabled()).thenReturn(true); SearchLookup searchLookup = mock(SearchLookup.class); when(searchExecutionContext.lookup()).thenReturn(searchLookup); when(searchExecutionContext.indexVersionCreated()).thenReturn(IndexVersion.current()); return searchExecutionContext; } public static List<?> fetchSourceValue(MappedFieldType fieldType, Object sourceValue) throws IOException { return fetchSourceValue(fieldType, sourceValue, null); } public static List<?> fetchSourceValue(MappedFieldType fieldType, Object sourceValue, String format) throws IOException { String field = fieldType.name(); SearchExecutionContext searchExecutionContext = mock(SearchExecutionContext.class); when(searchExecutionContext.getIndexSettings()).thenReturn(IndexSettingsModule.newIndexSettings("test", Settings.EMPTY)); when(searchExecutionContext.isSourceEnabled()).thenReturn(true); when(searchExecutionContext.sourcePath(field)).thenReturn(Set.of(field)); ValueFetcher fetcher = fieldType.valueFetcher(searchExecutionContext, format); Source source = Source.fromMap(Collections.singletonMap(field, sourceValue), randomFrom(XContentType.values())); return fetcher.fetchValues(source, -1, new ArrayList<>()); } public static List<?> fetchSourceValues(MappedFieldType fieldType, Object... values) throws IOException { String field = fieldType.name(); SearchExecutionContext searchExecutionContext = mock(SearchExecutionContext.class); when(searchExecutionContext.getIndexSettings()).thenReturn(IndexSettingsModule.newIndexSettings("test", Settings.EMPTY)); when(searchExecutionContext.isSourceEnabled()).thenReturn(true); when(searchExecutionContext.sourcePath(field)).thenReturn(Set.of(field)); ValueFetcher fetcher = fieldType.valueFetcher(searchExecutionContext, null); Source source = Source.fromMap(Collections.singletonMap(field, List.of(values)), randomFrom(XContentType.values())); return fetcher.fetchValues(source, -1, new ArrayList<>()); } public static List<?> fetchStoredValue(MappedFieldType fieldType, List<Object> storedValues, String format) throws IOException { String field = fieldType.name(); SearchExecutionContext searchExecutionContext = mock(SearchExecutionContext.class); SearchLookup searchLookup = mock(SearchLookup.class); LeafSearchLookup leafSearchLookup = mock(LeafSearchLookup.class); LeafStoredFieldsLookup leafStoredFieldsLookup = mock(LeafStoredFieldsLookup.class); FieldLookup fieldLookup = mock(FieldLookup.class); when(searchExecutionContext.lookup()).thenReturn(searchLookup); when(searchLookup.getLeafSearchLookup(null)).thenReturn(leafSearchLookup); when(leafSearchLookup.fields()).thenReturn(leafStoredFieldsLookup); when(leafStoredFieldsLookup.get(field)).thenReturn(fieldLookup); when(fieldLookup.getValues()).thenReturn(storedValues); ValueFetcher fetcher = fieldType.valueFetcher(searchExecutionContext, format); fetcher.setNextReader(null); return fetcher.fetchValues(null, -1, new ArrayList<>()); } public void testFieldHasValue() { MappedFieldType fieldType = getMappedFieldType(); FieldInfos fieldInfos = new FieldInfos(new FieldInfo[] { getFieldInfoWithName("field") }); assertTrue(fieldType.fieldHasValue(fieldInfos)); } public void testFieldHasValueWithEmptyFieldInfos() { MappedFieldType fieldType = getMappedFieldType(); assertFalse(fieldType.fieldHasValue(FieldInfos.EMPTY)); } public MappedFieldType getMappedFieldType() { return new MappedFieldType("field", IndexType.NONE, false, Collections.emptyMap()) { @Override public ValueFetcher valueFetcher(SearchExecutionContext context, String format) { return null; } @Override public String typeName() { return null; } @Override public Query termQuery(Object value, SearchExecutionContext context) { return null; } }; } public FieldInfo getFieldInfoWithName(String name) { return new FieldInfo( name, 1, randomBoolean(), randomBoolean(), randomBoolean(), IndexOptions.NONE, DocValuesType.NONE, DocValuesSkipIndexType.NONE, -1, new HashMap<>(), 1, 1, 1, 1, VectorEncoding.BYTE, VectorSimilarityFunction.COSINE, randomBoolean(), false ); } }
FieldTypeTestCase
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/GroupingValue.java
{ "start": 997, "end": 2031 }
class ____ extends AbstractDTOBase { private String value; private String key; private String label; private GroupingValue[] groupings; // TODO the description is vague about this!!! private GroupingValue[] dategroupings; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public GroupingValue[] getGroupings() { return groupings; } public void setGroupings(GroupingValue[] groupings) { this.groupings = groupings; } public GroupingValue[] getDategroupings() { return dategroupings; } public void setDategroupings(GroupingValue[] dategroupings) { this.dategroupings = dategroupings; } }
GroupingValue
java
spring-projects__spring-boot
module/spring-boot-webmvc-test/src/test/java/org/springframework/boot/webmvc/test/autoconfigure/WebMvcTypeExcludeFilterTests.java
{ "start": 7425, "end": 7496 }
class ____ { } @WebMvcTest(Controller1.class) static
WithNoControllers
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/transform/transforms/TransformHealthTests.java
{ "start": 484, "end": 1268 }
class ____ extends AbstractWireSerializingTestCase<TransformHealth> { public static TransformHealth randomTransformHealth() { return new TransformHealth( randomFrom(HealthStatus.values()), randomBoolean() ? null : randomList(1, 10, TransformHealthIssueTests::randomTransformHealthIssue) ); } @Override protected Writeable.Reader<TransformHealth> instanceReader() { return TransformHealth::new; } @Override protected TransformHealth createTestInstance() { return randomTransformHealth(); } @Override protected TransformHealth mutateInstance(TransformHealth instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } }
TransformHealthTests
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/tvf/operator/UnalignedWindowTableFunctionOperator.java
{ "start": 4067, "end": 13810 }
class ____ extends WindowTableFunctionOperatorBase implements Triggerable<RowData, TimeWindow> { private static final long serialVersionUID = 1L; private static final String LATE_ELEMENTS_DROPPED_METRIC_NAME = "numLateRecordsDropped"; private static final String LATE_ELEMENTS_DROPPED_RATE_METRIC_NAME = "lateRecordsDroppedRate"; private static final String WATERMARK_LATENCY_METRIC_NAME = "watermarkLatency"; private final Trigger<TimeWindow> trigger; private final TypeSerializer<RowData> inputSerializer; private final TypeSerializer<TimeWindow> windowSerializer; private transient InternalTimerService<TimeWindow> internalTimerService; // a counter to tag the order of all input streams when entering the operator private transient ValueState<Long> counterState; private transient InternalMapState<RowData, TimeWindow, Long, RowData> windowState; private transient TriggerContextImpl triggerContext; private transient MergingWindowProcessFunction<RowData, TimeWindow> windowFunction; private transient NamespaceAggsHandleFunctionBase<TimeWindow> windowAggregator; // ------------------------------------------------------------------------ // Metrics // ------------------------------------------------------------------------ private transient Counter numLateRecordsDropped; private transient Meter lateRecordsDroppedRate; private transient Gauge<Long> watermarkLatency; public UnalignedWindowTableFunctionOperator( GroupWindowAssigner<TimeWindow> windowAssigner, TypeSerializer<TimeWindow> windowSerializer, TypeSerializer<RowData> inputSerializer, int rowtimeIndex, ZoneId shiftTimeZone) { super(windowAssigner, rowtimeIndex, shiftTimeZone); this.trigger = createTrigger(windowAssigner); this.windowSerializer = checkNotNull(windowSerializer); this.inputSerializer = checkNotNull(inputSerializer); } @Override public void open() throws Exception { super.open(); internalTimerService = getInternalTimerService("session-window-tvf-timers", windowSerializer, this); triggerContext = new TriggerContextImpl(); triggerContext.open(); ValueStateDescriptor<Long> counterStateDescriptor = new ValueStateDescriptor<>("session-window-tvf-counter", LongSerializer.INSTANCE); counterState = getRuntimeContext().getState(counterStateDescriptor); MapStateDescriptor<Long, RowData> windowStateDescriptor = new MapStateDescriptor<>( "session-window-tvf-acc", LongSerializer.INSTANCE, inputSerializer); windowState = (InternalMapState<RowData, TimeWindow, Long, RowData>) getOrCreateKeyedState(windowSerializer, windowStateDescriptor); windowAggregator = new DummyWindowAggregator(); windowAggregator.open( new PerWindowStateDataViewStore( getKeyedStateBackend(), windowSerializer, getRuntimeContext())); WindowContextImpl windowContext = new WindowContextImpl(); windowFunction = new MergingWindowProcessFunction<>( (MergingWindowAssigner<TimeWindow>) windowAssigner, windowAggregator, windowSerializer, 0); windowFunction.open(windowContext); this.numLateRecordsDropped = metrics.counter(LATE_ELEMENTS_DROPPED_METRIC_NAME); this.lateRecordsDroppedRate = metrics.meter( LATE_ELEMENTS_DROPPED_RATE_METRIC_NAME, new MeterView(numLateRecordsDropped)); this.watermarkLatency = metrics.gauge( WATERMARK_LATENCY_METRIC_NAME, () -> { long watermark = internalTimerService.currentWatermark(); if (watermark < 0) { return 0L; } else { return internalTimerService.currentProcessingTime() - watermark; } }); } @Override public void close() throws Exception { super.close(); if (windowAggregator != null) { windowAggregator.close(); } } @Override public void processElement(StreamRecord<RowData> element) throws Exception { RowData inputRow = element.getValue(); long timestamp; if (windowAssigner.isEventTime()) { if (inputRow.isNullAt(rowtimeIndex)) { // null timestamp would be dropped numNullRowTimeRecordsDropped.inc(); return; } timestamp = inputRow.getTimestamp(rowtimeIndex, 3).getMillisecond(); } else { timestamp = getProcessingTimeService().getCurrentProcessingTime(); } // no matter if order exceeds the Long.MAX_VALUE Long order = counterState.value(); if (null == order) { order = 0L; } counterState.update(order + 1); timestamp = TimeWindowUtil.toUtcTimestampMills(timestamp, shiftTimeZone); // the windows which the input row should be placed into Collection<TimeWindow> affectedWindows = windowFunction.assignStateNamespace(inputRow, timestamp); boolean isElementDropped = true; for (TimeWindow window : affectedWindows) { isElementDropped = false; windowState.setCurrentNamespace(window); windowState.put(order, inputRow); } // the actual window which the input row is belongs to Collection<TimeWindow> actualWindows = windowFunction.assignActualWindows(inputRow, timestamp); Preconditions.checkArgument( (affectedWindows.isEmpty() && actualWindows.isEmpty()) || (!affectedWindows.isEmpty() && !actualWindows.isEmpty())); for (TimeWindow window : actualWindows) { triggerContext.setWindow(window); boolean triggerResult = triggerContext.onElement(inputRow, timestamp); if (triggerResult) { emitWindowResult(window); } // clear up state registerCleanupTimer(window); } if (isElementDropped) { // markEvent will increase numLateRecordsDropped lateRecordsDroppedRate.markEvent(); } } private void registerCleanupTimer(TimeWindow window) { long cleanupTime = getCleanupTime(window); if (cleanupTime == Long.MAX_VALUE) { // no need to clean up because we didn't set one return; } if (windowAssigner.isEventTime()) { triggerContext.registerEventTimeTimer(cleanupTime); } else { triggerContext.registerProcessingTimeTimer(cleanupTime); } } private void emitWindowResult(TimeWindow window) throws Exception { TimeWindow stateWindow = windowFunction.getStateWindow(window); windowState.setCurrentNamespace(stateWindow); Iterator<Map.Entry<Long, RowData>> iterator = windowState.iterator(); // build a sorted map TreeMap<Long, RowData> sortedMap = new TreeMap<>(); while (iterator.hasNext()) { Map.Entry<Long, RowData> entry = iterator.next(); sortedMap.put(entry.getKey(), entry.getValue()); } // emit the sorted map for (Map.Entry<Long, RowData> entry : sortedMap.entrySet()) { collect(entry.getValue(), Collections.singletonList(window)); } } @Override public void onEventTime(InternalTimer<RowData, TimeWindow> timer) throws Exception { triggerContext.setWindow(timer.getNamespace()); if (triggerContext.onEventTime(timer.getTimestamp())) { // fire emitWindowResult(triggerContext.window); } if (windowAssigner.isEventTime()) { windowFunction.cleanWindowIfNeeded(triggerContext.window, timer.getTimestamp()); } } @Override public void onProcessingTime(InternalTimer<RowData, TimeWindow> timer) throws Exception { triggerContext.setWindow(timer.getNamespace()); if (triggerContext.onProcessingTime(timer.getTimestamp())) { // fire emitWindowResult(triggerContext.window); } if (!windowAssigner.isEventTime()) { windowFunction.cleanWindowIfNeeded(triggerContext.window, timer.getTimestamp()); } } /** * In case this leads to a value greated than {@link Long#MAX_VALUE} then a cleanup time of * {@link Long#MAX_VALUE} is returned. */ private long getCleanupTime(TimeWindow window) { // In case this leads to a value greater than Long.MAX_VALUE, then a cleanup // time of Long.MAX_VALUE is returned. long cleanupTime = Math.max(0, window.maxTimestamp()); cleanupTime = cleanupTime >= window.maxTimestamp() ? cleanupTime : Long.MAX_VALUE; return toEpochMillsForTimer(cleanupTime, shiftTimeZone); } private static Trigger<TimeWindow> createTrigger( GroupWindowAssigner<TimeWindow> windowAssigner) { if (windowAssigner.isEventTime()) { return EventTimeTriggers.afterEndOfWindow(); } else { return ProcessingTimeTriggers.afterEndOfWindow(); } } private
UnalignedWindowTableFunctionOperator
java
alibaba__druid
core/src/test/java/com/alibaba/druid/DbTestCase.java
{ "start": 355, "end": 1436 }
class ____ extends TestCase { protected DruidDataSource dataSource; protected final String resource; public DbTestCase(String resource) { this.resource = resource; } protected void setUp() throws Exception { this.dataSource = createDataSourceFromResource(resource); } static DruidDataSource createDataSourceFromResource(String resource) throws IOException { Properties properties = new Properties(); InputStream configStream = null; try { configStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); properties.load(configStream); } finally { JdbcUtils.close(configStream); } DruidDataSource dataSource = new DruidDataSource(); dataSource.configFromPropeties(properties); return dataSource; } protected void tearDown() throws Exception { dataSource.close(); } public Connection getConnection() throws SQLException { return dataSource.getConnection(); } }
DbTestCase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/component/StructComponentManyToManyMappedByTest.java
{ "start": 3710, "end": 4142 }
class ____ { private String name; @ManyToMany(mappedBy = "booksInSeries") private Set<Book> books; public Author() { } public Author(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Book> getBooks() { return books; } public void setBooks(Set<Book> books) { this.books = books; } } }
Author
java
apache__camel
components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaTcpWithIoOutProcessorExceptionTest.java
{ "start": 1093, "end": 2339 }
class ____ extends BaseMinaTest { @Test public void testExceptionThrownInProcessor() { String body = "Hello World"; Object result = template.requestBody(String.format("mina:tcp://localhost:%1$s?textline=true&sync=true", getPort()), body); // The exception should be passed to the client assertNotNull(result, "the result should not be null"); assertEquals("java.lang.IllegalArgumentException: Forced exception", result, "result is IllegalArgumentException"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // use no delay for fast unit testing errorHandler(defaultErrorHandler().maximumRedeliveries(2)); fromF("mina:tcp://localhost:%1$s?textline=true&sync=true", getPort()).process(e -> { assertEquals("Hello World", e.getIn().getBody(String.class)); // simulate a problem processing the input to see if we can handle it properly throw new IllegalArgumentException("Forced exception"); }); } }; } }
MinaTcpWithIoOutProcessorExceptionTest
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/service/NacosServerStateService.java
{ "start": 938, "end": 1421 }
class ____ { /** * Get current server states. * * @return server states key-value map. */ public Map<String, String> getServerState() { Map<String, String> serverState = new HashMap<>(4); for (ModuleState each : ModuleStateHolder.getInstance().getAllModuleStates()) { each.getStates().forEach((s, o) -> serverState.put(s, null == o ? null : o.toString())); } return serverState; } }
NacosServerStateService
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/introspect/BasicClassIntrospector.java
{ "start": 283, "end": 9715 }
class ____ extends ClassIntrospector implements java.io.Serializable { private static final long serialVersionUID = 3L; private final static Class<?> CLS_OBJECT = Object.class; private final static Class<?> CLS_STRING = String.class; private final static Class<?> CLS_NUMBER = Number.class; private final static Class<?> CLS_JSON_NODE = JsonNode.class; /* We keep a small set of pre-constructed descriptions to use for * common non-structured values, such as Numbers and Strings. * This is strictly performance optimization to reduce what is * usually one-time cost, but seems useful for some cases considering * simplicity. */ private final static AnnotatedClass OBJECT_AC = new AnnotatedClass(CLS_OBJECT); private final static AnnotatedClass STRING_AC = new AnnotatedClass(CLS_STRING); private final static AnnotatedClass BOOLEAN_AC = new AnnotatedClass(Boolean.TYPE); private final static AnnotatedClass INT_AC = new AnnotatedClass(Integer.TYPE); private final static AnnotatedClass LONG_AC = new AnnotatedClass(Long.TYPE); private final static AnnotatedClass NUMBER_AC = new AnnotatedClass(CLS_NUMBER); /* /********************************************************************** /* Configuration /********************************************************************** */ protected final MixInResolver _mixInResolver; protected final MapperConfig<?> _config; /* /********************************************************************** /* State /********************************************************************** */ /** * Reuse fully-resolved annotations during a single operation */ protected HashMap<JavaType, AnnotatedClass> _resolvedFullAnnotations; // 15-Oct-2019, tatu: No measurable benefit from trying to reuse direct // annotation access. // protected HashMap<JavaType, AnnotatedClass> _resolvedDirectAnnotations; /** * Reuse full bean descriptions for serialization during a single operation */ protected HashMap<JavaType, BasicBeanDescription> _resolvedSerBeanDescs; /** * Reuse full bean descriptions for serialization during a single operation */ protected HashMap<JavaType, BasicBeanDescription> _resolvedDeserBeanDescs; /* /********************************************************************** /* Life cycle /********************************************************************** */ public BasicClassIntrospector() { _config = null; _mixInResolver = null; } protected BasicClassIntrospector(MapperConfig<?> config) { _config = Objects.requireNonNull(config, "Cannot pass null `config`"); _mixInResolver = config; } @Override public BasicClassIntrospector forMapper() { // 14-Oct-2019, tatu: no per-mapper caching used, so just return as-is return this; } @Override public BasicClassIntrospector forOperation(MapperConfig<?> config) { return new BasicClassIntrospector(config); } /* /********************************************************************** /* Factory method impls: annotation resolution /********************************************************************** */ @Override public AnnotatedClass introspectClassAnnotations(JavaType type) { AnnotatedClass ac = _findStdTypeDef(type); if (ac != null) { //System.err.println(" AC.introspectClassAnnotations "+type.getRawClass().getSimpleName()+" -> std-def"); return ac; } if (_resolvedFullAnnotations == null) { _resolvedFullAnnotations = new HashMap<>(); } else { ac = _resolvedFullAnnotations.get(type); if (ac != null) { //System.err.println(" AC.introspectClassAnnotations "+type.getRawClass().getSimpleName()+" -> CACHED"); return ac; } } //System.err.println(" AC.introspectClassAnnotations "+type.getRawClass().getSimpleName()+" -> resolve"); ac = _resolveAnnotatedClass(type); _resolvedFullAnnotations.put(type, ac); return ac; } @Override public AnnotatedClass introspectDirectClassAnnotations(JavaType type) { AnnotatedClass ac = _findStdTypeDef(type); return (ac != null) ? ac : _resolveAnnotatedWithoutSuperTypes(type); } protected AnnotatedClass _resolveAnnotatedClass(JavaType type) { return AnnotatedClassResolver.resolve(_config, type, _mixInResolver); } protected AnnotatedClass _resolveAnnotatedWithoutSuperTypes(JavaType type) { return AnnotatedClassResolver.resolveWithoutSuperTypes(_config, type, _mixInResolver); } /* /********************************************************************** /* Factory method impls: bean introspection /********************************************************************** */ @Override public BasicBeanDescription introspectForSerialization(JavaType type, AnnotatedClass classDef) { // minor optimization: for some JDK types do minimal introspection BasicBeanDescription desc = _findStdTypeDesc(type); if (desc == null) { // As per [databind#550], skip full introspection for some of standard // structured types as well desc = _findStdJdkCollectionDesc(type); if (desc == null) { if (_resolvedSerBeanDescs == null) { _resolvedSerBeanDescs = new HashMap<>(); } else { desc = _resolvedSerBeanDescs.get(type); if (desc != null) { return desc; } } desc = BasicBeanDescription.forSerialization(collectProperties(type, classDef, true, "set")); _resolvedSerBeanDescs.put(type, desc); } } return desc; } @Override public BasicBeanDescription introspectForDeserialization(JavaType type, AnnotatedClass classDef) { // minor optimization: for some JDK types do minimal introspection BasicBeanDescription desc = _findStdTypeDesc(type); if (desc == null) { // As per [databind#550], skip full introspection for some of standard // structured types as well desc = _findStdJdkCollectionDesc(type); if (desc == null) { if (_resolvedDeserBeanDescs == null) { _resolvedDeserBeanDescs = new HashMap<>(); } else { desc = _resolvedDeserBeanDescs.get(type); if (desc != null) { return desc; } } desc = BasicBeanDescription.forDeserialization(collectProperties(type, classDef, false, "set")); _resolvedDeserBeanDescs.put(type, desc); } } return desc; } @Override public BasicBeanDescription introspectForDeserializationWithBuilder(JavaType type, BeanDescription valueTypeDesc) { // no std JDK types with Builders, so: return BasicBeanDescription.forDeserialization(collectPropertiesWithBuilder(type, introspectClassAnnotations(type), valueTypeDesc, false)); } @Override public BasicBeanDescription introspectForCreation(JavaType type, AnnotatedClass classDef) { BasicBeanDescription desc = _findStdTypeDesc(type); if (desc == null) { // As per [databind#550], skip full introspection for some of standard // structured types as well desc = _findStdJdkCollectionDesc(type); if (desc == null) { desc = BasicBeanDescription.forDeserialization(collectProperties(type, classDef, false, "set")); } } return desc; } /* /********************************************************************** /* Overridable helper methods /********************************************************************** */ protected POJOPropertiesCollector collectProperties(JavaType type, AnnotatedClass classDef, boolean forSerialization, String mutatorPrefix) { final AccessorNamingStrategy accNaming = type.isRecordType() ? _config.getAccessorNaming().forRecord(_config, classDef) : _config.getAccessorNaming().forPOJO(_config, classDef); return constructPropertyCollector(type, classDef, forSerialization, accNaming); } protected POJOPropertiesCollector collectPropertiesWithBuilder(JavaType type, AnnotatedClass builderClassDef, BeanDescription valueTypeDesc, boolean forSerialization) { final AccessorNamingStrategy accNaming = _config.getAccessorNaming().forBuilder(_config, builderClassDef, valueTypeDesc); return constructPropertyCollector(type, builderClassDef, forSerialization, accNaming); } /** * Overridable method called for creating {@link POJOPropertiesCollector} instance * to use; override is needed if a custom sub-
BasicClassIntrospector
java
elastic__elasticsearch
build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/VersionPropertiesLoader.java
{ "start": 767, "end": 2748 }
class ____ { static Properties loadBuildSrcVersion(File input, ProviderFactory providerFactory) throws IOException { Properties props = new Properties(); try (InputStream is = new FileInputStream(input)) { props.load(is); } loadBuildSrcVersion(props, providerFactory); return props; } protected static void loadBuildSrcVersion(Properties loadedProps, ProviderFactory providers) { String elasticsearch = loadedProps.getProperty("elasticsearch"); if (elasticsearch == null) { throw new IllegalStateException("Elasticsearch version is missing from properties."); } if (elasticsearch.matches("[0-9]+\\.[0-9]+\\.[0-9]+") == false) { throw new IllegalStateException( "Expected elasticsearch version to be numbers only of the form X.Y.Z but it was: " + elasticsearch ); } String qualifier = providers.systemProperty("build.version_qualifier") .getOrElse(""); if (qualifier.isEmpty() == false) { if (qualifier.matches("(alpha|beta|rc)\\d+") == false) { throw new IllegalStateException("Invalid qualifier: " + qualifier); } elasticsearch += "-" + qualifier; } final String buildSnapshotSystemProperty = providers.systemProperty("build.snapshot") .getOrElse("true"); switch (buildSnapshotSystemProperty) { case "true": elasticsearch += "-SNAPSHOT"; break; case "false": // do nothing break; default: throw new IllegalArgumentException( "build.snapshot was set to [" + buildSnapshotSystemProperty + "] but can only be unset or [true|false]"); } loadedProps.put("elasticsearch", elasticsearch); } }
VersionPropertiesLoader
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/typeinfo/Types.java
{ "start": 2362, "end": 2619 }
class ____ access to the type information of the most common types for which Flink has * built-in serializers and comparators. * * <p>In many cases, Flink tries to analyze generic signatures of functions to determine return * types automatically. This
gives
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/condition/MatchPredicateTest.java
{ "start": 924, "end": 4836 }
class ____ implements WithAssertions { private Jedi yoda; @BeforeEach public void setup() { yoda = new Jedi("Yoda", "Green"); } @Test void should_match_predicate() { assertThat(yoda).matches(x -> x.lightSaberColor.equals("Green")); } @Test void should_match_predicate_with_description_() { assertThat(yoda).matches(x -> x.lightSaberColor.equals("Green"), "has green light saber"); } @Test void should_fail_if_object_does_not_match_predicate() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(yoda).matches(x -> x.lightSaberColor.equals("Red"))) .withMessage(format("%n" + "Expecting actual:%n" + " Yoda the Jedi%n" + "to match given predicate.%n" + "%n" + "You can use 'matches(Predicate p, String description)' to have a better error message%n" + "For example:%n" + " assertThat(player).matches(p -> p.isRookie(), \"is rookie\");%n" + "will give an error message looking like:%n" + "%n" + "Expecting actual:%n" + " player%n" + "to match 'is rookie' predicate")); } @Test void should_fail_if_object_does_not_match_predicate_and_use_predicate_description_in_error_message() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(yoda).as("check light saber") .matches(x -> x.lightSaberColor.equals("Red"), "has red light saber")) .withMessage(format("[check light saber] %n" + "Expecting actual:%n" + " Yoda the Jedi%n" + "to match 'has red light saber' predicate.")); } @Test void should_fail_if_given_predicate_is_null() { assertThatNullPointerException().isThrownBy(() -> assertThat(yoda).matches(null)) .withMessage(predicateIsNull()); } @Test void should_fail_if_given_predicate_with_description_is_null() { assertThatNullPointerException().isThrownBy(() -> assertThat(yoda).matches(null, "whatever ...")) .withMessage(predicateIsNull()); } @Test void should_fail_if_given_predicate_description_is_null() { assertThatNullPointerException().isThrownBy(() -> assertThat(yoda).matches(x -> x.lightSaberColor.equals("Green"), null)) .withMessage("The predicate description must not be null"); } }
MatchPredicateTest
java
processing__processing4
java/src/processing/mode/java/tweak/TweakClient.java
{ "start": 890, "end": 3156 }
class ____ { private DatagramSocket socket; private InetAddress address; private boolean initialized; private int sketchPort; static final int VAR_INT = 0; static final int VAR_FLOAT = 1; static final int SHUTDOWN = 0xffffffff; public TweakClient(int sketchPort) { this.sketchPort = sketchPort; try { socket = new DatagramSocket(); // only local sketch is allowed address = InetAddress.getByName("127.0.0.1"); initialized = true; } catch (SocketException e) { initialized = false; } catch (UnknownHostException e) { socket.close(); initialized = false; } catch (SecurityException e) { socket.close(); initialized = false; } } public void shutdown() { if (initialized) { // send shutdown to the sketch sendShutdown(); initialized = false; } } public boolean sendInt(int index, int val) { if (initialized) { try { byte[] buf = new byte[12]; ByteBuffer bb = ByteBuffer.wrap(buf); bb.putInt(0, VAR_INT); bb.putInt(4, index); bb.putInt(8, val); DatagramPacket packet = new DatagramPacket(buf, buf.length, address, sketchPort); socket.send(packet); return true; } catch (Exception e) { } } return false; } public boolean sendFloat(int index, float val) { if (initialized) { try { byte[] buf = new byte[12]; ByteBuffer bb = ByteBuffer.wrap(buf); bb.putInt(0, VAR_FLOAT); bb.putInt(4, index); bb.putFloat(8, val); socket.send(new DatagramPacket(buf, buf.length, address, sketchPort)); return true; } catch (Exception e) { } } return false; } public boolean sendShutdown() { if (initialized) { try { byte[] buf = new byte[12]; ByteBuffer bb = ByteBuffer.wrap(buf); bb.putInt(0, SHUTDOWN); socket.send(new DatagramPacket(buf, buf.length, address, sketchPort)); return true; } catch (Exception e) { } } return false; } static public String getServerCode(int listenPort, boolean hasInts, boolean hasFloats) { String serverCode = ""+ "
TweakClient
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/type/LobUnfetchedPropertyTest.java
{ "start": 1951, "end": 5019 }
class ____ { @AfterEach void tearDown(SessionFactoryScope factoryScope) { factoryScope.dropData(); } @Test public void testBlob(SessionFactoryScope scope) throws SQLException { final int id = scope.fromTransaction( s -> { FileBlob file = new FileBlob(); file.setBlob( getLobHelper().createBlob( "TEST CASE".getBytes() ) ); // merge transient entity file = (FileBlob) s.merge( file ); return file.getId(); } ); scope.inTransaction( s -> { FileBlob file = s.get( FileBlob.class, id ); assertFalse( Hibernate.isPropertyInitialized( file, "blob" ) ); Blob blob = file.getBlob(); try { assertArrayEquals( "TEST CASE".getBytes(), blob.getBytes( 1, (int) file.getBlob().length() ) ); } catch (SQLException ex) { fail( "could not determine Lob length" ); } }); } @Test @SkipForDialect( dialectClass = FirebirdDialect.class, reason = "Driver cannot determine clob length" ) public void testClob(SessionFactoryScope scope) throws SQLException { final int id = scope.fromTransaction( s -> { FileClob file = new FileClob(); file.setClob( getLobHelper().createClob( "TEST CASE" ) ); // merge transient entity file = (FileClob) s.merge( file ); return file.getId(); } ); scope.inTransaction( s -> { FileClob file = s.get( FileClob.class, id ); assertFalse( Hibernate.isPropertyInitialized( file, "clob" ) ); Clob clob = file.getClob(); try { final char[] chars = new char[(int) file.getClob().length()]; clob.getCharacterStream().read( chars ); assertArrayEquals( "TEST CASE".toCharArray(), chars ); } catch (SQLException ex ) { fail( "could not determine Lob length" ); } catch (IOException ex) { fail( "could not read Lob" ); } }); } @Test @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsNClob.class) @SkipForDialect( dialectClass = SybaseDialect.class, matchSubTypes = true, reason = "jConnect does not support Connection#createNClob which is ultimately used by LobHelper#createNClob" ) public void testNClob(SessionFactoryScope scope) { final int id = scope.fromTransaction( s -> { FileNClob file = new FileNClob(); file.setClob( getLobHelper().createNClob( "TEST CASE" ) ); // merge transient entity file = (FileNClob) s.merge( file ); return file.getId(); }); scope.inTransaction( s -> { FileNClob file = s.get( FileNClob.class, id ); assertFalse( Hibernate.isPropertyInitialized( file, "clob" ) ); NClob nClob = file.getClob(); assertTrue( Hibernate.isPropertyInitialized( file, "clob" ) ); try { final char[] chars = new char[(int) file.getClob().length()]; nClob.getCharacterStream().read( chars ); assertArrayEquals( "TEST CASE".toCharArray(), chars ); } catch (SQLException ex ) { fail( "could not determine Lob length" ); } catch (IOException ex) { fail( "could not read Lob" ); } }); } @Entity(name = "FileBlob") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, includeLazy = false) public static
LobUnfetchedPropertyTest
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/CamelEvent.java
{ "start": 10756, "end": 11048 }
interface ____ extends RouteEvent { /** * Restart attempt (0 = initial start, 1 = first restart attempt) */ long getAttempt(); @Override default Type getType() { return Type.RouteRestarting; } }
RouteRestartingEvent
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-data-elasticsearch/src/dockerTest/java/smoketest/data/elasticsearch/SampleDataElasticsearchWithElasticsearch8ApplicationTests.java
{ "start": 1685, "end": 2637 }
class ____ { @Container @ServiceConnection @Ssl static final ElasticsearchContainer elasticSearch = new ElasticsearchContainer(TestImage.ELASTICSEARCH_8.toString()) .withPassword("my-custom-password"); @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Autowired private SampleRepository exampleRepository; @Test void testRepository() { SampleDocument document = new SampleDocument(); document.setText("Look, new @DataElasticsearchTest!"); String id = UUID.randomUUID().toString(); document.setId(id); SampleDocument savedDocument = this.exampleRepository.save(document); SampleDocument getDocument = this.elasticsearchTemplate.get(id, SampleDocument.class); assertThat(getDocument).isNotNull(); assertThat(getDocument.getId()).isNotNull(); assertThat(getDocument.getId()).isEqualTo(savedDocument.getId()); this.exampleRepository.deleteAll(); } }
SampleDataElasticsearchWithElasticsearch8ApplicationTests
java
google__gson
gson/src/test/java/com/google/gson/functional/PrimitiveCharacterTest.java
{ "start": 883, "end": 1666 }
class ____ { private Gson gson; @Before public void setUp() throws Exception { gson = new Gson(); } @Test public void testPrimitiveCharacterAutoboxedSerialization() { assertThat(gson.toJson('A')).isEqualTo("\"A\""); assertThat(gson.toJson('A', char.class)).isEqualTo("\"A\""); assertThat(gson.toJson('A', Character.class)).isEqualTo("\"A\""); } @Test public void testPrimitiveCharacterAutoboxedDeserialization() { char expected = 'a'; char actual = gson.fromJson("a", char.class); assertThat(actual).isEqualTo(expected); actual = gson.fromJson("\"a\"", char.class); assertThat(actual).isEqualTo(expected); actual = gson.fromJson("a", Character.class); assertThat(actual).isEqualTo(expected); } }
PrimitiveCharacterTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/exceptions/YARNFeatureNotEnabledException.java
{ "start": 1128, "end": 1526 }
class ____ extends YarnException { private static final long serialVersionUID = 898023752676L; public YARNFeatureNotEnabledException(Throwable cause) { super(cause); } public YARNFeatureNotEnabledException(String message) { super(message); } public YARNFeatureNotEnabledException(String message, Throwable cause) { super(message, cause); } }
YARNFeatureNotEnabledException
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/jaxrs/AsyncResponseImpl.java
{ "start": 779, "end": 6699 }
class ____ implements AsyncResponse, Runnable { private final ResteasyReactiveRequestContext context; private volatile boolean suspended; private volatile boolean cancelled; private volatile TimeoutHandler timeoutHandler; // only used with lock, no need for volatile private Runnable timerCancelTask = null; public AsyncResponseImpl(ResteasyReactiveRequestContext context) { this.context = context; suspended = true; } @Override public synchronized boolean resume(Object response) { if (!suspended) { return false; } else { suspended = false; } cancelTimer(); context.setResult(response); context.resume(); return true; } @Override public synchronized boolean resume(Throwable response) { if (!suspended) { return false; } else { suspended = false; } cancelTimer(); context.handleException(response); context.resume(); return true; } @Override public boolean cancel() { return internalCancel(null); } @Override public boolean cancel(int retryAfter) { return internalCancel(retryAfter); } private synchronized boolean internalCancel(Object retryAfter) { if (cancelled) { return true; } if (!suspended) { return false; } cancelTimer(); suspended = false; cancelled = true; ResponseBuilder response = Response.status(503); if (retryAfter != null) response.header(HttpHeaders.RETRY_AFTER, retryAfter); // It's not clear if we should go via the exception handlers here, but our TCK setup makes us // go through it, while RESTEasy doesn't because it does resume like this, so we do too context.setResult(response.build()); context.resume(); return true; } @Override public boolean cancel(Date retryAfter) { return internalCancel(retryAfter); } // CALL WITH LOCK private void cancelTimer() { if (timerCancelTask != null) { timerCancelTask.run(); timerCancelTask = null; } } @Override public boolean isSuspended() { return suspended; } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isDone() { // we start suspended and stop being suspended on resume/cancel/timeout(which resumes) so // this flag is enough to know if we're done return !suspended; } @Override public synchronized boolean setTimeout(long time, TimeUnit unit) { if (!suspended) return false; if (timerCancelTask != null) { timerCancelTask.run(); } timerCancelTask = context.registerTimer(TimeUnit.MILLISECONDS.convert(time, unit), this); return true; } @Override public void setTimeoutHandler(TimeoutHandler handler) { timeoutHandler = handler; } @Override public Collection<Class<?>> register(Class<?> callback) { Objects.requireNonNull(callback); // FIXME: does this mean we should use CDI to look it up? try { return register(callback.getDeclaredConstructor().newInstance()); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new RuntimeException(e); } } @Override public Map<Class<?>, Collection<Class<?>>> register(Class<?> callback, Class<?>... callbacks) { Objects.requireNonNull(callback); Objects.requireNonNull(callbacks); Map<Class<?>, Collection<Class<?>>> ret = new HashMap<>(); ret.put(callback, register(callback)); for (Class<?> cb : callbacks) { ret.put(cb, register(cb)); } return ret; } @Override public Collection<Class<?>> register(Object callback) { Objects.requireNonNull(callback); List<Class<?>> ret = new ArrayList<>(2); if (callback instanceof ConnectionCallback) { context.registerConnectionCallback((ConnectionCallback) callback); ret.add(ConnectionCallback.class); } if (callback instanceof CompletionCallback) { context.registerCompletionCallback((CompletionCallback) callback); ret.add(CompletionCallback.class); } return ret; } @Override public Map<Class<?>, Collection<Class<?>>> register(Object callback, Object... callbacks) { Objects.requireNonNull(callback); Objects.requireNonNull(callbacks); Map<Class<?>, Collection<Class<?>>> ret = new HashMap<>(); ret.put(callback.getClass(), register(callback)); for (Object cb : callbacks) { ret.put(cb.getClass(), register(cb)); } return ret; } @Override public synchronized void run() { // make sure we're not marked as waiting for a timer anymore timerCancelTask = null; // if we're not suspended anymore, or we were cancelled, drop it if (!suspended || cancelled) return; if (timeoutHandler != null) { timeoutHandler.handleTimeout(this); // Spec says: // In case the time-out handler does not take any of the actions mentioned above [resume/new timeout], // a default time-out strategy is executed by the runtime. // Stef picked to do this if the handler did not resume or set a new timeout: if (suspended && timerCancelTask == null) resume(new ServiceUnavailableException()); } else { resume(new ServiceUnavailableException()); } } }
AsyncResponseImpl
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToLongFromDoubleEvaluator.java
{ "start": 1120, "end": 4345 }
class ____ extends AbstractConvertFunction.AbstractEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(ToLongFromDoubleEvaluator.class); private final EvalOperator.ExpressionEvaluator dbl; public ToLongFromDoubleEvaluator(Source source, EvalOperator.ExpressionEvaluator dbl, DriverContext driverContext) { super(driverContext, source); this.dbl = dbl; } @Override public EvalOperator.ExpressionEvaluator next() { return dbl; } @Override public Block evalVector(Vector v) { DoubleVector vector = (DoubleVector) v; int positionCount = v.getPositionCount(); if (vector.isConstant()) { try { return driverContext.blockFactory().newConstantLongBlockWith(evalValue(vector, 0), positionCount); } catch (InvalidArgumentException e) { registerException(e); return driverContext.blockFactory().newConstantNullBlock(positionCount); } } try (LongBlock.Builder builder = driverContext.blockFactory().newLongBlockBuilder(positionCount)) { for (int p = 0; p < positionCount; p++) { try { builder.appendLong(evalValue(vector, p)); } catch (InvalidArgumentException e) { registerException(e); builder.appendNull(); } } return builder.build(); } } private long evalValue(DoubleVector container, int index) { double value = container.getDouble(index); return ToLong.fromDouble(value); } @Override public Block evalBlock(Block b) { DoubleBlock block = (DoubleBlock) b; int positionCount = block.getPositionCount(); try (LongBlock.Builder builder = driverContext.blockFactory().newLongBlockBuilder(positionCount)) { for (int p = 0; p < positionCount; p++) { int valueCount = block.getValueCount(p); int start = block.getFirstValueIndex(p); int end = start + valueCount; boolean positionOpened = false; boolean valuesAppended = false; for (int i = start; i < end; i++) { try { long value = evalValue(block, i); if (positionOpened == false && valueCount > 1) { builder.beginPositionEntry(); positionOpened = true; } builder.appendLong(value); valuesAppended = true; } catch (InvalidArgumentException e) { registerException(e); } } if (valuesAppended == false) { builder.appendNull(); } else if (positionOpened) { builder.endPositionEntry(); } } return builder.build(); } } private long evalValue(DoubleBlock container, int index) { double value = container.getDouble(index); return ToLong.fromDouble(value); } @Override public String toString() { return "ToLongFromDoubleEvaluator[" + "dbl=" + dbl + "]"; } @Override public void close() { Releasables.closeExpectNoException(dbl); } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += dbl.baseRamBytesUsed(); return baseRamBytesUsed; } public static
ToLongFromDoubleEvaluator
java
alibaba__nacos
console/src/main/java/com/alibaba/nacos/console/handler/config/HistoryHandler.java
{ "start": 1092, "end": 3132 }
interface ____ { /** * Query the detailed configuration history information. * * @param dataId the ID of the data * @param group the group ID * @param namespaceId the namespace ID * @param nid the history record ID * @return the detailed configuration history information * @throws NacosException if any error occurs during the operation */ ConfigHistoryDetailInfo getConfigHistoryInfo(String dataId, String group, String namespaceId, Long nid) throws NacosException; /** * Query the list of configuration history. * * @param dataId the ID of the data * @param group the group ID * @param namespaceId the namespace ID * @param pageNo the page number * @param pageSize the number of items per page * @return the paginated list of configuration history * @throws NacosException if any error occurs during the operation */ Page<ConfigHistoryBasicInfo> listConfigHistory(String dataId, String group, String namespaceId, Integer pageNo, Integer pageSize) throws NacosException; /** * Query the previous configuration history information. * * @param dataId the ID of the data * @param group the group ID * @param namespaceId the namespace ID * @param id the configuration ID * @return the previous configuration history information * @throws NacosException if any error occurs during the operation */ ConfigHistoryDetailInfo getPreviousConfigHistoryInfo(String dataId, String group, String namespaceId, Long id) throws NacosException; /** * Query the list of configurations by namespace. * * @param namespaceId the namespace ID * @return the list of configurations * @throws NacosException if any error occurs during the operation */ List<ConfigBasicInfo> getConfigsByTenant(String namespaceId) throws NacosException; }
HistoryHandler
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/TestTypedDeserialization.java
{ "start": 1067, "end": 1346 }
class ____ extends Animal { public int boneCount; @JsonCreator public Dog(@JsonProperty("name") String name) { super(name); } public void setBoneCount(int i) { boneCount = i; } } @JsonTypeName("kitty") static
Dog
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/HttpMessage.java
{ "start": 866, "end": 1039 }
interface ____ { /** * Return the headers of this message. * @return a corresponding HttpHeaders object (never {@code null}) */ HttpHeaders getHeaders(); }
HttpMessage
java
netty__netty
codec-dns/src/main/java/io/netty/handler/codec/dns/TcpDnsQueryDecoder.java
{ "start": 868, "end": 2068 }
class ____ extends LengthFieldBasedFrameDecoder { private final DnsRecordDecoder decoder; /** * Creates a new decoder with {@linkplain DnsRecordDecoder#DEFAULT the default record decoder}. */ public TcpDnsQueryDecoder() { this(DnsRecordDecoder.DEFAULT, 65535); } /** * Creates a new decoder with the specified {@code decoder}. */ public TcpDnsQueryDecoder(DnsRecordDecoder decoder, int maxFrameLength) { super(maxFrameLength, 0, 2, 0, 2); this.decoder = ObjectUtil.checkNotNull(decoder, "decoder"); } @Override protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf frame = (ByteBuf) super.decode(ctx, in); if (frame == null) { return null; } try { return DnsMessageUtil.decodeDnsQuery(decoder, frame.slice(), new DnsMessageUtil.DnsQueryFactory() { @Override public DnsQuery newQuery(int id, DnsOpCode dnsOpCode) { return new DefaultDnsQuery(id, dnsOpCode); } }); } finally { frame.release(); } } }
TcpDnsQueryDecoder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/shuffle/ShuffleMaster.java
{ "start": 1434, "end": 7341 }
interface ____<T extends ShuffleDescriptor> extends AutoCloseable { /** * Starts this shuffle master as a service. One can do some initialization here, for example * getting access and connecting to the external system. */ default void start() throws Exception {} /** * Closes this shuffle master service which should release all resources. A shuffle master will * only be closed when the cluster is shut down. */ @Override default void close() throws Exception {} /** * Registers the target job together with the corresponding {@link JobShuffleContext} to this * shuffle master. Through the shuffle context, one can obtain some basic information like job * ID, job configuration. It enables ShuffleMaster to notify JobMaster about lost result * partitions, so that JobMaster can identify and reproduce unavailable partitions earlier. * * @param context the corresponding shuffle context of the target job. */ default void registerJob(JobShuffleContext context) {} /** * Unregisters the target job from this shuffle master, which means the corresponding job has * reached a global termination state and all the allocated resources except for the cluster * partitions can be cleared. * * @param jobID ID of the target job to be unregistered. */ default void unregisterJob(JobID jobID) {} /** * Asynchronously register a partition and its producer with the shuffle service. * * <p>The returned shuffle descriptor is an internal handle which identifies the partition * internally within the shuffle service. The descriptor should provide enough information to * read from or write data to the partition. * * @param jobID job ID of the corresponding job which registered the partition * @param partitionDescriptor general job graph information about the partition * @param producerDescriptor general producer information (location, execution id, connection * info) * @return future with the partition shuffle descriptor used for producer/consumer deployment * and their data exchange. */ CompletableFuture<T> registerPartitionWithProducer( JobID jobID, PartitionDescriptor partitionDescriptor, ProducerDescriptor producerDescriptor); /** * Release any external resources occupied by the given partition. * * <p>This call triggers release of any resources which are occupied by the given partition in * the external systems outside of the producer executor. This is mostly relevant for the batch * jobs and blocking result partitions. The producer local resources are managed by {@link * ShuffleDescriptor#storesLocalResourcesOn()} and {@link * ShuffleEnvironment#releasePartitionsLocally(Collection)}. * * @param shuffleDescriptor shuffle descriptor of the result partition to release externally. */ void releasePartitionExternally(ShuffleDescriptor shuffleDescriptor); /** * Compute shuffle memory size for a task with the given {@link TaskInputsOutputsDescriptor}. * * @param taskInputsOutputsDescriptor describes task inputs and outputs information for shuffle * memory calculation. * @return shuffle memory size for a task with the given {@link TaskInputsOutputsDescriptor}. */ default MemorySize computeShuffleMemorySizeForTask( TaskInputsOutputsDescriptor taskInputsOutputsDescriptor) { return MemorySize.ZERO; } /** * Retrieves specified partitions and their metrics (identified by {@code expectedPartitions}), * the metrics include sizes of sub-partitions in a result partition. * * @param jobId ID of the target job * @param timeout The timeout used for retrieve the specified partitions. * @param expectedPartitions The set of identifiers for the result partitions whose metrics are * to be fetched. * @return A future will contain a collection of the partitions with their metrics that could be * retrieved from the expected partitions within the specified timeout period. */ default CompletableFuture<Collection<PartitionWithMetrics>> getPartitionWithMetrics( JobID jobId, Duration timeout, Set<ResultPartitionID> expectedPartitions) { return CompletableFuture.completedFuture(Collections.emptyList()); } /** * Whether the shuffle master supports taking snapshot in batch scenarios if {@link * org.apache.flink.configuration.BatchExecutionOptions#JOB_RECOVERY_ENABLED} is true. If it * returns true, Flink will call {@link #snapshotState} to take snapshot, and call {@link * #restoreState} to restore the state of shuffle master. */ default boolean supportsBatchSnapshot() { return false; } /** Triggers a snapshot of the shuffle master's state. */ default void snapshotState(CompletableFuture<ShuffleMasterSnapshot> snapshotFuture) {} /** Triggers a snapshot of the shuffle master's state which related the specified job. */ default void snapshotState( CompletableFuture<ShuffleMasterSnapshot> snapshotFuture, ShuffleMasterSnapshotContext context, JobID jobId) {} /** Restores the state of the shuffle master from the provided snapshots. */ default void restoreState(ShuffleMasterSnapshot snapshot) {} /** * Restores the state of the shuffle master from the provided snapshots for the specified job. */ default void restoreState(List<ShuffleMasterSnapshot> snapshots, JobID jobId) {} /** * Notifies that the recovery process of result partitions has started. * * @param jobId ID of the target job */ default void notifyPartitionRecoveryStarted(JobID jobId) {} }
ShuffleMaster
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/type/MyOidGenerator.java
{ "start": 340, "end": 586 }
class ____ implements IdentifierGenerator { private int counter; public Object generate(SharedSessionContractImplementor session, Object aObject) throws HibernateException { counter++; return new MyOid( 0, 0, 0, counter ); } }
MyOidGenerator
java
google__guava
android/guava/src/com/google/common/base/CharMatcher.java
{ "start": 3145, "end": 7384 }
class ____ implements Predicate<Character> { /* * N777777777NO * N7777777777777N * M777777777777777N * $N877777777D77777M * N M77777777ONND777M * MN777777777NN D777 * N7ZN777777777NN ~M7778 * N777777777777MMNN88777N * N777777777777MNZZZ7777O * DZN7777O77777777777777 * N7OONND7777777D77777N * 8$M++++?N???$77777$ * M7++++N+M77777777N * N77O777777777777$ M * DNNM$$$$777777N D * N$N:=N$777N7777M NZ * 77Z::::N777777777 ODZZZ * 77N::::::N77777777M NNZZZ$ * $777:::::::77777777MN ZM8ZZZZZ * 777M::::::Z7777777Z77 N++ZZZZNN * 7777M:::::M7777777$777M $++IZZZZM * M777$:::::N777777$M7777M +++++ZZZDN * NN$::::::7777$$M777777N N+++ZZZZNZ * N::::::N:7$O:77777777 N++++ZZZZN * M::::::::::::N77777777+ +?+++++ZZZM * 8::::::::::::D77777777M O+++++ZZ * ::::::::::::M777777777N O+?D * M:::::::::::M77777777778 77= * D=::::::::::N7777777777N 777 * INN===::::::=77777777777N I777N * ?777N========N7777777777787M N7777 * 77777$D======N77777777777N777N? N777777 * I77777$$$N7===M$$77777777$77777777$MMZ77777777N * $$$$$$$$$$$NIZN$$$$$$$$$M$$7777777777777777ON * M$$$$$$$$M M$$$$$$$$N=N$$$$7777777$$$ND * O77Z$$$$$$$ M$$$$$$$$MNI==$DNNNNM=~N * 7 :N MNN$$$$M$ $$$777$8 8D8I * NMM.:7O 777777778 * 7777777MN * M NO .7: * M : M * 8 */ // Constant matcher factory methods /** * Matches any character. * * @since 19.0 (since 1.0 as constant {@code ANY}) */ public static CharMatcher any() { return Any.INSTANCE; } /** * Matches no characters. * * @since 19.0 (since 1.0 as constant {@code NONE}) */ public static CharMatcher none() { return None.INSTANCE; } /** * Determines whether a character is whitespace according to the latest Unicode standard, as * illustrated <a * href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bwhitespace%7D">here</a>. * This is not the same definition used by other Java APIs. (See a <a * href="https://docs.google.com/spreadsheets/d/1kq4ECwPjHX9B8QUCTPclgsDCXYaj7T-FlT4tB5q3ahk/edit">comparison * of several definitions of "whitespace"</a>.) * * <p>All Unicode White_Space characters are on the BMP and thus supported by this API. * * <p><b>Note:</b> as the Unicode definition evolves, we will modify this matcher to keep it up to * date. * * @since 19.0 (since 1.0 as constant {@code WHITESPACE}) */ public static CharMatcher whitespace() { return Whitespace.INSTANCE; } /** * Determines whether a character is a breaking whitespace (that is, a whitespace which can be * interpreted as a break between words for formatting purposes). See {@link #whitespace()} for a * discussion of that term. * * @since 19.0 (since 2.0 as constant {@code BREAKING_WHITESPACE}) */ public static CharMatcher breakingWhitespace() { return BreakingWhitespace.INSTANCE; } /** * Determines whether a character is ASCII, meaning that its code point is less than 128. * * @since 19.0 (since 1.0 as constant {@code ASCII}) */ public static CharMatcher ascii() { return Ascii.INSTANCE; } /** * Determines whether a character is a BMP digit according to <a * href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bdigit%7D">Unicode</a>. If * you only care to match ASCII digits, you can use {@code inRange('0', '9')}. * * @deprecated Many digits are supplementary characters; see the
CharMatcher
java
apache__camel
test-infra/camel-test-infra-ibmmq/src/main/java/org/apache/camel/test/infra/ibmmq/services/IbmMQLocalContainerInfraService.java
{ "start": 1545, "end": 2367 }
class ____ implements IbmMQInfraService, ContainerService<GenericContainer<?>> { public static final String CONTAINER_NAME = "ibmmq"; public static final int MQ_LISTENER_PORT = 1414; public static final int WEB_CONSOLE_PORT = 9443; private static final Logger LOG = LoggerFactory.getLogger(IbmMQLocalContainerInfraService.class); private final GenericContainer<?> container; public IbmMQLocalContainerInfraService() { this(LocalPropertyResolver.getProperty( IbmMQLocalContainerInfraService.class, IbmMQProperties.IBM_MQ_CONTAINER)); } public IbmMQLocalContainerInfraService(String containerImage) { container = initContainer(containerImage); } protected GenericContainer<?> initContainer(String imageName) {
IbmMQLocalContainerInfraService
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/impl/CustomUnitOfWorkFactoryTest.java
{ "start": 2455, "end": 2925 }
class ____ extends DefaultUnitOfWork { MyUnitOfWork(Exchange exchange) { super(exchange); } @Override public AsyncCallback beforeProcess(Processor processor, Exchange exchange, AsyncCallback callback) { exchange.getIn().setHeader("before", "I was here"); return callback; } @Override public boolean isBeforeAfterProcess() { return true; } } }
MyUnitOfWork
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SjmsEndpointBuilderFactory.java
{ "start": 98735, "end": 106971 }
interface ____ extends SjmsEndpointConsumerBuilder, SjmsEndpointProducerBuilder { default AdvancedSjmsEndpointBuilder advanced() { return (AdvancedSjmsEndpointBuilder) this; } /** * The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, * CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE. * * The option is a: * <code>org.apache.camel.component.sjms.jms.SessionAcknowledgementType</code> type. * * Default: AUTO_ACKNOWLEDGE * Group: common * * @param acknowledgementMode the value to set * @return the dsl builder */ default SjmsEndpointBuilder acknowledgementMode(org.apache.camel.component.sjms.jms.SessionAcknowledgementType acknowledgementMode) { doSetProperty("acknowledgementMode", acknowledgementMode); return this; } /** * The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, * CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE. * * The option will be converted to a * <code>org.apache.camel.component.sjms.jms.SessionAcknowledgementType</code> type. * * Default: AUTO_ACKNOWLEDGE * Group: common * * @param acknowledgementMode the value to set * @return the dsl builder */ default SjmsEndpointBuilder acknowledgementMode(String acknowledgementMode) { doSetProperty("acknowledgementMode", acknowledgementMode); return this; } /** * The connection factory to be use. A connection factory must be * configured either on the component or endpoint. * * The option is a: <code>jakarta.jms.ConnectionFactory</code> type. * * Group: common * * @param connectionFactory the value to set * @return the dsl builder */ default SjmsEndpointBuilder connectionFactory(jakarta.jms.ConnectionFactory connectionFactory) { doSetProperty("connectionFactory", connectionFactory); return this; } /** * The connection factory to be use. A connection factory must be * configured either on the component or endpoint. * * The option will be converted to a * <code>jakarta.jms.ConnectionFactory</code> type. * * Group: common * * @param connectionFactory the value to set * @return the dsl builder */ default SjmsEndpointBuilder connectionFactory(String connectionFactory) { doSetProperty("connectionFactory", connectionFactory); return this; } /** * Specifies whether Camel ignores the JMSReplyTo header in messages. If * true, Camel does not send a reply back to the destination specified * in the JMSReplyTo header. You can use this option if you want Camel * to consume from a route and you do not want Camel to automatically * send back a reply message because another component in your code * handles the reply message. You can also use this option if you want * to use Camel as a proxy between different message brokers and you * want to route message from one system to another. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param disableReplyTo the value to set * @return the dsl builder */ default SjmsEndpointBuilder disableReplyTo(boolean disableReplyTo) { doSetProperty("disableReplyTo", disableReplyTo); return this; } /** * Specifies whether Camel ignores the JMSReplyTo header in messages. If * true, Camel does not send a reply back to the destination specified * in the JMSReplyTo header. You can use this option if you want Camel * to consume from a route and you do not want Camel to automatically * send back a reply message because another component in your code * handles the reply message. You can also use this option if you want * to use Camel as a proxy between different message brokers and you * want to route message from one system to another. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param disableReplyTo the value to set * @return the dsl builder */ default SjmsEndpointBuilder disableReplyTo(String disableReplyTo) { doSetProperty("disableReplyTo", disableReplyTo); return this; } /** * Provides an explicit ReplyTo destination (overrides any incoming * value of Message.getJMSReplyTo() in consumer). * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param replyTo the value to set * @return the dsl builder */ default SjmsEndpointBuilder replyTo(String replyTo) { doSetProperty("replyTo", replyTo); return this; } /** * Specifies whether to test the connection on startup. This ensures * that when Camel starts that all the JMS consumers have a valid * connection to the JMS broker. If a connection cannot be granted then * Camel throws an exception on startup. This ensures that Camel is not * started with failed connections. The JMS producers is tested as well. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param testConnectionOnStartup the value to set * @return the dsl builder */ default SjmsEndpointBuilder testConnectionOnStartup(boolean testConnectionOnStartup) { doSetProperty("testConnectionOnStartup", testConnectionOnStartup); return this; } /** * Specifies whether to test the connection on startup. This ensures * that when Camel starts that all the JMS consumers have a valid * connection to the JMS broker. If a connection cannot be granted then * Camel throws an exception on startup. This ensures that Camel is not * started with failed connections. The JMS producers is tested as well. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param testConnectionOnStartup the value to set * @return the dsl builder */ default SjmsEndpointBuilder testConnectionOnStartup(String testConnectionOnStartup) { doSetProperty("testConnectionOnStartup", testConnectionOnStartup); return this; } /** * Specifies whether to use transacted mode. * * The option is a: <code>boolean</code> type. * * Default: false * Group: transaction * * @param transacted the value to set * @return the dsl builder */ default SjmsEndpointBuilder transacted(boolean transacted) { doSetProperty("transacted", transacted); return this; } /** * Specifies whether to use transacted mode. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: transaction * * @param transacted the value to set * @return the dsl builder */ default SjmsEndpointBuilder transacted(String transacted) { doSetProperty("transacted", transacted); return this; } } /** * Advanced builder for endpoint for the Simple JMS component. */ public
SjmsEndpointBuilder
java
playframework__playframework
core/play-integration-test/src/test/java/play/it/http/ActionCompositionOrderTest.java
{ "start": 4728, "end": 4929 }
class ____ extends Action<SingletonActionAnnotation> { @Override public CompletionStage<Result> call(Http.Request req) { return delegate.call(req); } } }
SingletonActionAnnotationAction
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/service/invoker/HttpServiceMethodTests.java
{ "start": 13024, "end": 13233 }
interface ____ { @PostExchange("/post") @PutExchange("/post") void post(); } @HttpExchange @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) private @
MultipleMethodLevelAnnotationsService
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1200/Issue1293.java
{ "start": 1297, "end": 1333 }
enum ____{ C,D } }
UserType
java
elastic__elasticsearch
x-pack/plugin/ccr/src/javaRestTest/java/org/elasticsearch/xpack/ccr/AbstractCCRRestTestCase.java
{ "start": 18813, "end": 18909 }
enum ____ { LEADER, MIDDLE, FOLLOWER; } public static
TargetCluster
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingFilterBeanTests.java
{ "start": 5808, "end": 6010 }
class ____ implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { } } static
TestFilter
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/sequencedmultisetstate/SequencedMultiSetState.java
{ "start": 5554, "end": 7666 }
enum ____ { /** * An element was added or appended to the state. The result will not contain any elements. */ ADDITION { @Override public <T> void validate(long sizeBefore, long sizeAfter, T payload) { checkArgument(sizeAfter == sizeBefore + 1 || sizeAfter == sizeBefore); } }, /** * Nothing was removed (e.g. as a result of TTL or not matching key), the result will not * contain any elements. */ REMOVAL_NOT_FOUND { @Override public <T> void validate(long sizeBefore, long sizeAfter, T payload) { checkArgument(sizeAfter == sizeBefore); checkArgument(payload == null); } }, /** All elements were removed. The result will contain the last removed element. */ REMOVAL_ALL { @Override public <T> void validate(long sizeBefore, long sizeAfter, T payload) { checkArgument(sizeBefore > 0); checkArgument(sizeAfter == 0); checkNotNull(payload); } }, /** * The most recently added element was removed. The result will contain the element added * before it. */ REMOVAL_LAST_ADDED { @Override public <T> void validate(long sizeBefore, long sizeAfter, T payload) { checkArgument(sizeAfter == sizeBefore - 1); checkNotNull(payload); } }, /** * An element was removed, it was not the most recently added, there are more elements. The * result will not contain any elements */ REMOVAL_OTHER { @Override public <T> void validate(long sizeBefore, long sizeAfter, T payload) { checkArgument(sizeAfter == sizeBefore - 1); checkArgument(payload == null); } }; public abstract <T> void validate(long sizeBefore, long sizeAfter, T payload); }
StateChangeType
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java
{ "start": 3862, "end": 4158 }
class ____ extends ESTestCase { private static ThreadPool THREAD_POOL; private TestShardStateAction shardStateAction; private CapturingTransport transport; private TransportService transportService; private ClusterService clusterService; private static
ShardStateActionTests
java
spring-projects__spring-boot
module/spring-boot-thymeleaf/src/test/java/org/springframework/boot/thymeleaf/autoconfigure/ThymeleafServletAutoConfigurationTests.java
{ "start": 15973, "end": 16373 }
class ____ { @Bean FilterRegistrationBean<ResourceUrlEncodingFilter> filterRegistration() { FilterRegistrationBean<ResourceUrlEncodingFilter> bean = new FilterRegistrationBean<>( new ResourceUrlEncodingFilter()); bean.setDispatcherTypes(EnumSet.of(DispatcherType.INCLUDE)); return bean; } } @Configuration(proxyBeanMethods = false) static
FilterRegistrationResourceConfiguration
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractIterableAssert.java
{ "start": 111092, "end": 111335 }
class ____ { * String name; * String email; * List&lt;Book&gt; books = new ArrayList&lt;&gt;(); * * Author(String name, String email) { * this.name = name; * this.email = email; * } * } * *
Author
java
elastic__elasticsearch
x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/ScheduleTestCase.java
{ "start": 1537, "end": 12505 }
class ____ extends ESTestCase { protected static String[] expressions(CronnableSchedule schedule) { return expressions(schedule.crons); } protected static String[] expressions(Cron[] crons) { String[] expressions = new String[crons.length]; for (int i = 0; i < expressions.length; i++) { expressions[i] = crons[i].expression(); } return expressions; } protected static MonthlySchedule randomMonthlySchedule() { return switch (randomIntBetween(1, 4)) { case 1 -> monthly().build(); case 2 -> monthly().time(MonthTimes.builder().atMidnight()).build(); case 3 -> monthly().time(MonthTimes.builder().on(randomIntBetween(1, 31)).atMidnight()).build(); default -> new MonthlySchedule(validMonthTimes()); }; } protected static WeeklySchedule randomWeeklySchedule() { return switch (randomIntBetween(1, 4)) { case 1 -> weekly().build(); case 2 -> weekly().time(WeekTimes.builder().atMidnight()).build(); case 3 -> weekly().time(WeekTimes.builder().on(DayOfWeek.THURSDAY).atMidnight()).build(); default -> new WeeklySchedule(validWeekTimes()); }; } protected static DailySchedule randomDailySchedule() { return switch (randomIntBetween(1, 4)) { case 1 -> daily().build(); case 2 -> daily().atMidnight().build(); case 3 -> daily().atNoon().build(); default -> new DailySchedule(validDayTimes()); }; } protected static HourlySchedule randomHourlySchedule() { return switch (randomIntBetween(1, 4)) { case 1 -> hourly().build(); case 2 -> hourly().minutes(randomIntBetween(0, 59)).build(); case 3 -> hourly(randomIntBetween(0, 59)); default -> hourly().minutes(validMinutes()).build(); }; } protected static IntervalSchedule randomIntervalSchedule() { return switch (randomIntBetween(1, 3)) { case 1 -> interval(randomInterval().toString()); case 2 -> interval(randomIntBetween(1, 100), randomIntervalUnit()); default -> new IntervalSchedule(randomInterval()); }; } protected static IntervalSchedule.Interval randomInterval() { return new IntervalSchedule.Interval(randomIntBetween(1, 100), randomIntervalUnit()); } protected static IntervalSchedule.Interval.Unit randomIntervalUnit() { return IntervalSchedule.Interval.Unit.values()[randomIntBetween(0, IntervalSchedule.Interval.Unit.values().length - 1)]; } protected static YearTimes validYearTime() { return new YearTimes(randomMonths(), randomDaysOfMonth(), validDayTimes()); } protected static YearTimes[] validYearTimes() { int count = randomIntBetween(2, 5); Set<YearTimes> times = new HashSet<>(); for (int i = 0; i < count; i++) { times.add(validYearTime()); } return times.toArray(new YearTimes[times.size()]); } protected static MonthTimes validMonthTime() { return new MonthTimes(randomDaysOfMonth(), validDayTimes()); } protected static MonthTimes[] validMonthTimes() { int count = randomIntBetween(2, 5); Set<MonthTimes> times = new HashSet<>(); for (int i = 0; i < count; i++) { MonthTimes testMonthTimes = validMonthTime(); boolean intersectsExistingMonthTimes = false; for (MonthTimes validMonthTimes : times) { if (validMonthTimes.intersects(testMonthTimes)) { intersectsExistingMonthTimes = true; } } if (intersectsExistingMonthTimes == false) { times.add(testMonthTimes); } } return times.toArray(new MonthTimes[times.size()]); } protected static WeekTimes validWeekTime() { return new WeekTimes(randomDaysOfWeek(), validDayTimes()); } protected static WeekTimes[] validWeekTimes() { int count = randomIntBetween(2, 5); Set<WeekTimes> times = new HashSet<>(); for (int i = 0; i < count; i++) { times.add(validWeekTime()); } return times.toArray(new WeekTimes[times.size()]); } protected static EnumSet<DayOfWeek> randomDaysOfWeek() { int count = randomIntBetween(1, DayOfWeek.values().length - 1); Set<DayOfWeek> days = new HashSet<>(); for (int i = 0; i < count; i++) { days.add(DayOfWeek.values()[randomIntBetween(0, count)]); } return EnumSet.copyOf(days); } protected static EnumSet<Month> randomMonths() { int count = randomIntBetween(1, 11); Set<Month> months = new HashSet<>(); for (int i = 0; i < count; i++) { months.add(Month.values()[randomIntBetween(0, 11)]); } return EnumSet.copyOf(months); } protected static Object randomMonth() { int m = randomIntBetween(1, 14); return switch (m) { case 13 -> "first"; case 14 -> "last"; default -> Month.resolve(m); }; } protected static int[] randomDaysOfMonth() { if (rarely()) { return new int[] { 32 }; } int count = randomIntBetween(1, 5); Set<Integer> days = new HashSet<>(); for (int i = 0; i < count; i++) { days.add(randomIntBetween(1, 31)); } return CollectionUtils.toArray(days); } protected static Object randomDayOfMonth() { int day = randomIntBetween(1, 32); if (day == 32) { return "last_day"; } if (day == 1) { return randomBoolean() ? "first_day" : 1; } return day; } protected static int dayOfMonthToInt(Object dom) { if (dom instanceof Integer) { return (Integer) dom; } if ("last_day".equals(dom)) { return 32; } if ("first_day".equals(dom)) { return 1; } throw new IllegalStateException("cannot convert given day-of-month [" + dom + "] to int"); } protected static Object invalidDayOfMonth() { return randomBoolean() ? randomAlphaOfLength(5) : randomBoolean() ? randomIntBetween(-30, -1) : randomIntBetween(33, 45); } protected static DayTimes validDayTime() { return randomBoolean() ? DayTimes.parse(validDayTimeStr()) : new DayTimes(validHours(), validMinutes()); } protected static String validDayTimeStr() { int hour = validHour(); int min = validMinute(); StringBuilder sb = new StringBuilder(); if (hour < 10 && randomBoolean()) { sb.append("0"); } sb.append(hour).append(":"); if (min < 10) { sb.append("0"); } return sb.append(min).toString(); } protected static HourAndMinute invalidDayTime() { return randomBoolean() ? new HourAndMinute(invalidHour(), invalidMinute()) : randomBoolean() ? new HourAndMinute(validHour(), invalidMinute()) : new HourAndMinute(invalidHour(), validMinute()); } protected static String invalidDayTimeStr() { int hour; int min; switch (randomIntBetween(1, 3)) { case 1 -> { hour = invalidHour(); min = validMinute(); } case 2 -> { hour = validHour(); min = invalidMinute(); } default -> { hour = invalidHour(); min = invalidMinute(); } } StringBuilder sb = new StringBuilder(); if (hour < 10 && randomBoolean()) { sb.append("0"); } sb.append(hour).append(":"); if (min < 10) { sb.append("0"); } return sb.append(min).toString(); } protected static DayTimes[] validDayTimes() { int count = randomIntBetween(2, 5); Set<DayTimes> times = new HashSet<>(); for (int i = 0; i < count; i++) { times.add(validDayTime()); } return times.toArray(new DayTimes[times.size()]); } protected static DayTimes[] validDayTimesFromNumbers() { int count = randomIntBetween(2, 5); Set<DayTimes> times = new HashSet<>(); for (int i = 0; i < count; i++) { times.add(new DayTimes(validHours(), validMinutes())); } return times.toArray(new DayTimes[times.size()]); } protected static DayTimes[] validDayTimesFromStrings() { int count = randomIntBetween(2, 5); Set<DayTimes> times = new HashSet<>(); for (int i = 0; i < count; i++) { times.add(DayTimes.parse(validDayTimeStr())); } return times.toArray(new DayTimes[times.size()]); } protected static HourAndMinute[] invalidDayTimes() { int count = randomIntBetween(2, 5); Set<HourAndMinute> times = new HashSet<>(); for (int i = 0; i < count; i++) { times.add(invalidDayTime()); } return times.toArray(new HourAndMinute[times.size()]); } protected static String[] invalidDayTimesAsStrings() { int count = randomIntBetween(2, 5); Set<String> times = new HashSet<>(); for (int i = 0; i < count; i++) { times.add(invalidDayTimeStr()); } return times.toArray(new String[times.size()]); } protected static int validMinute() { return randomIntBetween(0, 59); } protected static int[] validMinutes() { int count = randomIntBetween(2, 6); int inc = 59 / count; int[] minutes = new int[count]; for (int i = 0; i < count; i++) { minutes[i] = randomIntBetween(i * inc, (i + 1) * inc); } return minutes; } protected static int invalidMinute() { return randomBoolean() ? randomIntBetween(60, 100) : randomIntBetween(-60, -1); } protected static int[] invalidMinutes() { int count = randomIntBetween(2, 6); int[] minutes = new int[count]; for (int i = 0; i < count; i++) { minutes[i] = invalidMinute(); } return minutes; } protected static int validHour() { return randomIntBetween(0, 23); } protected static int[] validHours() { int count = randomIntBetween(2, 6); int inc = 23 / count; int[] hours = new int[count]; for (int i = 0; i < count; i++) { hours[i] = randomIntBetween(i * inc, (i + 1) * inc); } return hours; } protected static int invalidHour() { return randomBoolean() ? randomIntBetween(24, 40) : randomIntBetween(-60, -1); } static
ScheduleTestCase
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/wrappedio/impl/TestWrappedIO.java
{ "start": 12370, "end": 13805 }
interface ____ and the probe successful. */ private boolean supportsIOStatisticsContext(final Object o) { return io.streamCapabilities_hasCapability(o, IOSTATISTICS_CONTEXT); } /** * Open a file through dynamic invocation of {@link FileSystem#openFile(Path)}. * @param path path * @param policy read policy * @param status optional file status * @param length file length or null * @param options nullable map of other options * @return stream of the opened file */ private FSDataInputStream openFile( final Path path, final String policy, final FileStatus status, final Long length, final Map<String, String> options) throws Throwable { final FSDataInputStream stream = io.fileSystem_openFile( getFileSystem(), path, policy, status, length, options); Assertions.assertThat(stream) .describedAs("null stream from openFile(%s)", path) .isNotNull(); return stream; } /** * Build a map from the tuples, which all have the value of * their toString() method used. * @param tuples object list (must be even) * @return a map. */ private Map<String, String> map(Map.Entry<String, Object>... tuples) { Map<String, String> map = new HashMap<>(); for (Map.Entry<String, Object> tuple : tuples) { map.put(tuple.getKey(), tuple.getValue().toString()); } return map; } /** * Load a
implemented
java
apache__camel
components/camel-dynamic-router/src/main/java/org/apache/camel/component/dynamicrouter/routing/DynamicRouterConfiguration.java
{ "start": 1360, "end": 1463 }
class ____ all configuration items for the Dynamic Router EIP component. */ @UriParams public
encapsulates
java
spring-projects__spring-boot
module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/CloudFoundryConditionalOnAvailableEndpointTests.java
{ "start": 1447, "end": 2037 }
class ____ { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(AllEndpointsConfiguration.class) .withInitializer( (context) -> context.getEnvironment().setConversionService(new ApplicationConversionService())); @Test void outcomeOnCloudFoundryShouldMatchAll() { this.contextRunner.withPropertyValues("VCAP_APPLICATION:---") .run((context) -> assertThat(context).hasBean("info").hasBean("health").hasBean("spring").hasBean("test")); } @Endpoint(id = "health") static
CloudFoundryConditionalOnAvailableEndpointTests
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/contexts/request/ControllerClient.java
{ "start": 223, "end": 392 }
class ____ { @Inject Controller controller; @ActivateRequestContext String getControllerId() { return controller.getId(); } }
ControllerClient
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/common/Accessibility.java
{ "start": 338, "end": 1021 }
enum ____ { PRIVATE( "private" ), DEFAULT( "" ), PROTECTED( "protected" ), PUBLIC( "public" ); private final String keyword; Accessibility(String keyword) { this.keyword = keyword; } public String getKeyword() { return keyword; } public static Accessibility fromModifiers(Set<Modifier> modifiers) { if ( modifiers.contains( Modifier.PUBLIC ) ) { return PUBLIC; } else if ( modifiers.contains( Modifier.PROTECTED ) ) { return PROTECTED; } else if ( modifiers.contains( Modifier.PRIVATE ) ) { return PRIVATE; } return DEFAULT; } }
Accessibility
java
alibaba__nacos
api/src/test/java/com/alibaba/nacos/api/ai/model/mcp/McpServerDetailInfoTest.java
{ "start": 1391, "end": 14422 }
class ____ extends BasicRequestTest { @Test void testSerializeForStdio() throws JsonProcessingException { McpServerDetailInfo mcpServerDetailInfo = new McpServerDetailInfo(); String id = UUID.randomUUID().toString(); mcpServerDetailInfo.setName("stdioServer"); mcpServerDetailInfo.setId(id); mcpServerDetailInfo.setProtocol(AiConstants.Mcp.MCP_PROTOCOL_STDIO); mcpServerDetailInfo.setFrontProtocol(AiConstants.Mcp.MCP_PROTOCOL_STDIO); mcpServerDetailInfo.setDescription("test stdio server"); mcpServerDetailInfo.setVersionDetail(new ServerVersionDetail()); mcpServerDetailInfo.getVersionDetail().setVersion("1.0.0"); mcpServerDetailInfo.getVersionDetail().setIs_latest(false); mcpServerDetailInfo.getVersionDetail().setRelease_date("2025-07-15 23:59:59"); mcpServerDetailInfo.setLocalServerConfig(new HashMap<>()); mcpServerDetailInfo.setCapabilities(Collections.singletonList(McpCapability.TOOL)); mcpServerDetailInfo.setToolSpec(new McpToolSpecification()); mcpServerDetailInfo.setAllVersions(Collections.singletonList(mcpServerDetailInfo.getVersionDetail())); mcpServerDetailInfo.setNamespaceId(AiConstants.Mcp.MCP_DEFAULT_NAMESPACE); mcpServerDetailInfo.setVersion("1.0.0"); String json = mapper.writeValueAsString(mcpServerDetailInfo); assertTrue(json.contains("\"name\":\"stdioServer\"")); assertTrue(json.contains(String.format("\"id\":\"%s\"", id))); assertTrue(json.contains("\"protocol\":\"stdio\"")); assertTrue(json.contains("\"frontProtocol\":\"stdio\"")); assertTrue(json.contains("\"description\":\"test stdio server\"")); assertTrue(json.contains("\"versionDetail\":{")); assertTrue(json.contains("\"version\":\"1.0.0\"")); assertTrue(json.contains("\"is_latest\":false")); assertTrue(json.contains("\"release_date\":\"2025-07-15 23:59:59\"")); assertTrue(json.contains("\"localServerConfig\":{}")); assertTrue(json.contains("\"capabilities\":[\"TOOL\"]")); assertTrue(json.contains("\"toolSpec\":{")); assertTrue(json.contains("\"allVersions\":[{")); } @Test void testDeserializeForStdio() throws JsonProcessingException { String json = "{\"id\":\"3a2c535c-d0a8-44a4-8913-0cef98904ebd\",\"name\":\"stdioServer\",\"protocol\":\"stdio\"," + "\"frontProtocol\":\"stdio\",\"description\":\"test stdio server\",\"versionDetail\":{\"version\":\"1.0.0\"," + "\"release_date\":\"2025-07-15 23:59:59\",\"is_latest\":false},\"localServerConfig\":{},\"enabled\":true," + "\"capabilities\":[\"TOOL\"],\"toolSpec\":{\"tools\":[],\"toolsMeta\":{}},\"allVersions\":[{\"version\":\"1.0.0\"," + "\"release_date\":\"2025-07-15 23:59:59\",\"is_latest\":false}],\"namespaceId\":\"public\", \"version\":\"1.0.0\"}"; McpServerDetailInfo result = mapper.readValue(json, McpServerDetailInfo.class); assertNotNull(result); assertEquals("3a2c535c-d0a8-44a4-8913-0cef98904ebd", result.getId()); assertEquals("stdioServer", result.getName()); assertEquals(AiConstants.Mcp.MCP_PROTOCOL_STDIO, result.getProtocol()); assertEquals(AiConstants.Mcp.MCP_PROTOCOL_STDIO, result.getFrontProtocol()); assertEquals("test stdio server", result.getDescription()); assertNotNull(result.getVersionDetail()); assertEquals("1.0.0", result.getVersionDetail().getVersion()); assertEquals("2025-07-15 23:59:59", result.getVersionDetail().getRelease_date()); assertFalse(result.getVersionDetail().getIs_latest()); assertNotNull(result.getLocalServerConfig()); assertTrue(result.isEnabled()); assertNotNull(result.getCapabilities()); assertEquals(1, result.getCapabilities().size()); assertEquals(McpCapability.TOOL, result.getCapabilities().get(0)); assertNotNull(result.getToolSpec()); assertNotNull(result.getAllVersions()); assertEquals(1, result.getAllVersions().size()); assertEquals(AiConstants.Mcp.MCP_DEFAULT_NAMESPACE, result.getNamespaceId()); assertEquals("1.0.0", result.getVersion()); } @Test void testSerializeForSse() throws JsonProcessingException { // Repository是空对象 mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); McpServerDetailInfo mcpServerDetailInfo = new McpServerDetailInfo(); String id = UUID.randomUUID().toString(); mcpServerDetailInfo.setName("stdioServer"); mcpServerDetailInfo.setId(id); mcpServerDetailInfo.setProtocol(AiConstants.Mcp.MCP_PROTOCOL_SSE); mcpServerDetailInfo.setFrontProtocol(AiConstants.Mcp.MCP_PROTOCOL_SSE); mcpServerDetailInfo.setDescription("test sse server"); mcpServerDetailInfo.setVersionDetail(new ServerVersionDetail()); mcpServerDetailInfo.getVersionDetail().setVersion("1.0.0"); mcpServerDetailInfo.getVersionDetail().setIs_latest(false); mcpServerDetailInfo.getVersionDetail().setRelease_date("2025-07-15 23:59:59"); mcpServerDetailInfo.setRemoteServerConfig(new McpServerRemoteServiceConfig()); mcpServerDetailInfo.getRemoteServerConfig().setExportPath("/test"); mcpServerDetailInfo.getRemoteServerConfig().setServiceRef(new McpServiceRef()); mcpServerDetailInfo.getRemoteServerConfig().getServiceRef() .setNamespaceId(AiConstants.Mcp.MCP_DEFAULT_NAMESPACE); mcpServerDetailInfo.getRemoteServerConfig().getServiceRef().setGroupName("testG"); mcpServerDetailInfo.getRemoteServerConfig().getServiceRef().setServiceName("testS"); mcpServerDetailInfo.getRemoteServerConfig() .setFrontEndpointConfigList(Collections.singletonList(new FrontEndpointConfig())); mcpServerDetailInfo.getRemoteServerConfig().getFrontEndpointConfigList().get(0) .setType(AiConstants.Mcp.MCP_PROTOCOL_SSE); mcpServerDetailInfo.getRemoteServerConfig().getFrontEndpointConfigList().get(0) .setProtocol(AiConstants.Mcp.MCP_PROTOCOL_HTTP); mcpServerDetailInfo.getRemoteServerConfig().getFrontEndpointConfigList().get(0) .setEndpointType(AiConstants.Mcp.MCP_ENDPOINT_TYPE_DIRECT); mcpServerDetailInfo.getRemoteServerConfig().getFrontEndpointConfigList().get(0).setEndpointData("1.1.1.1:8080"); mcpServerDetailInfo.getRemoteServerConfig().getFrontEndpointConfigList().get(0).setPath("/testFront"); mcpServerDetailInfo.setRepository(new Repository()); mcpServerDetailInfo.setCapabilities(Collections.singletonList(McpCapability.TOOL)); mcpServerDetailInfo.setToolSpec(new McpToolSpecification()); mcpServerDetailInfo.setAllVersions(Collections.singletonList(mcpServerDetailInfo.getVersionDetail())); mcpServerDetailInfo.setNamespaceId(AiConstants.Mcp.MCP_DEFAULT_NAMESPACE); mcpServerDetailInfo.setBackendEndpoints(Collections.singletonList(new McpEndpointInfo())); mcpServerDetailInfo.getBackendEndpoints().get(0).setPath("/testBack"); mcpServerDetailInfo.getBackendEndpoints().get(0).setAddress("1.1.1.1"); mcpServerDetailInfo.getBackendEndpoints().get(0).setPort(3306); mcpServerDetailInfo.setFrontendEndpoints(Collections.emptyList()); String json = mapper.writeValueAsString(mcpServerDetailInfo); assertTrue(json.contains("\"name\":\"stdioServer\"")); assertTrue(json.contains(String.format("\"id\":\"%s\"", id))); assertTrue(json.contains("\"protocol\":\"mcp-sse\"")); assertTrue(json.contains("\"frontProtocol\":\"mcp-sse\"")); assertTrue(json.contains("\"description\":\"test sse server\"")); assertTrue(json.contains("\"versionDetail\":{")); assertTrue(json.contains("\"version\":\"1.0.0\"")); assertTrue(json.contains("\"is_latest\":false")); assertTrue(json.contains("\"release_date\":\"2025-07-15 23:59:59\"")); assertTrue(json.contains("\"remoteServerConfig\":{")); assertTrue(json.contains("\"exportPath\":\"/test\"")); assertTrue(json.contains("\"serviceRef\":{")); assertTrue(json.contains("\"namespaceId\":\"public\"")); assertTrue(json.contains("\"groupName\":\"testG\"")); assertTrue(json.contains("\"serviceName\":\"testS\"")); assertTrue(json.contains("\"capabilities\":[\"TOOL\"]")); assertTrue(json.contains("\"toolSpec\":{")); assertTrue(json.contains("\"allVersions\":[{")); assertTrue(json.contains("\"repository\":{}")); assertTrue(json.contains("\"frontendEndpoints\":[]")); } @Test void testDeserializeForSse() throws JsonProcessingException { String json = "{\"id\":\"c769b89b-edb5-4912-8e39-71bf5dc31eab\",\"name\":\"stdioServer\",\"protocol\":\"mcp-sse\"," + "\"frontProtocol\":\"mcp-sse\",\"description\":\"test sse server\",\"repository\":{},\"versionDetail\":" + "{\"version\":\"1.0.0\",\"release_date\":\"2025-07-15 23:59:59\",\"is_latest\":false}," + "\"remoteServerConfig\":{\"serviceRef\":{\"namespaceId\":\"public\",\"groupName\":\"testG\"," + "\"serviceName\":\"testS\"},\"exportPath\":\"/test\",\"frontEndpointConfigList\":[{\"type\":" + "\"mcp-sse\",\"protocol\":\"http\",\"endpointType\":\"DIRECT\",\"endpointData\":\"1.1.1.1:8080\"," + "\"path\":\"/testFront\"}]},\"enabled\":true,\"capabilities\":[\"TOOL\"],\"backendEndpoints\":" + "[{\"address\":\"1.1.1.1\",\"port\":3306,\"path\":\"/testBack\"}],\"frontendEndpoints\":[],\"toolSpec\":{\"tools\":[]," + "\"toolsMeta\":{}},\"allVersions\":[{\"version\":\"1.0.0\",\"release_date\":\"2025-07-15 23:59:59\"," + "\"is_latest\":false}],\"namespaceId\":\"public\"}"; McpServerDetailInfo result = mapper.readValue(json, McpServerDetailInfo.class); assertNotNull(result); assertEquals("c769b89b-edb5-4912-8e39-71bf5dc31eab", result.getId()); assertEquals("stdioServer", result.getName()); assertEquals(AiConstants.Mcp.MCP_PROTOCOL_SSE, result.getProtocol()); assertEquals(AiConstants.Mcp.MCP_PROTOCOL_SSE, result.getFrontProtocol()); assertEquals("test sse server", result.getDescription()); assertNotNull(result.getVersionDetail()); assertEquals("1.0.0", result.getVersionDetail().getVersion()); assertEquals("2025-07-15 23:59:59", result.getVersionDetail().getRelease_date()); assertFalse(result.getVersionDetail().getIs_latest()); assertNotNull(result.getRemoteServerConfig()); assertNotNull(result.getRemoteServerConfig().getServiceRef()); assertEquals(AiConstants.Mcp.MCP_DEFAULT_NAMESPACE, result.getRemoteServerConfig().getServiceRef().getNamespaceId()); assertEquals("testG", result.getRemoteServerConfig().getServiceRef().getGroupName()); assertEquals("testS", result.getRemoteServerConfig().getServiceRef().getServiceName()); assertNotNull(result.getRemoteServerConfig().getExportPath()); assertEquals("/test", result.getRemoteServerConfig().getExportPath()); assertTrue(result.isEnabled()); assertNotNull(result.getCapabilities()); assertEquals(1, result.getCapabilities().size()); assertEquals(McpCapability.TOOL, result.getCapabilities().get(0)); assertNotNull(result.getToolSpec()); assertNotNull(result.getAllVersions()); assertEquals(1, result.getAllVersions().size()); assertEquals(AiConstants.Mcp.MCP_DEFAULT_NAMESPACE, result.getNamespaceId()); assertNotNull(result.getRepository()); assertNotNull(result.getBackendEndpoints()); assertEquals(1, result.getBackendEndpoints().size()); assertEquals("1.1.1.1", result.getBackendEndpoints().get(0).getAddress()); assertEquals(3306, result.getBackendEndpoints().get(0).getPort()); assertEquals("/testBack", result.getBackendEndpoints().get(0).getPath()); assertEquals(1, result.getRemoteServerConfig().getFrontEndpointConfigList().size()); FrontEndpointConfig frontEndpointConfig = result.getRemoteServerConfig().getFrontEndpointConfigList().get(0); assertEquals(AiConstants.Mcp.MCP_PROTOCOL_SSE, frontEndpointConfig.getType()); assertEquals(AiConstants.Mcp.MCP_ENDPOINT_TYPE_DIRECT, frontEndpointConfig.getEndpointType()); assertEquals("1.1.1.1:8080", frontEndpointConfig.getEndpointData()); assertEquals("/testFront", frontEndpointConfig.getPath()); assertEquals(AiConstants.Mcp.MCP_PROTOCOL_HTTP, frontEndpointConfig.getProtocol()); } }
McpServerDetailInfoTest
java
FasterXML__jackson-core
src/main/java/tools/jackson/core/util/TextBuffer.java
{ "start": 212, "end": 888 }
class ____ to {@link java.lang.StringBuffer}, with * following differences: *<ul> * <li>TextBuffer uses segments character arrays, to avoid having * to do additional array copies when array is not big enough. * This means that only reallocating that is necessary is done only once: * if and when caller * wants to access contents in a linear array (char[], String). * </li> * <li>TextBuffer can also be initialized in "shared mode", in which * it will just act as a wrapper to a single char array managed * by another object (like parser that owns it) * </li> * <li>TextBuffer is not synchronized. * </li> * </ul> */ public
similar