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
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/jdk/NumberDeserializers.java
{ "start": 22101, "end": 22999 }
class ____ extends PrimitiveOrWrapperDeserializer<Long> { final static LongDeserializer primitiveInstance = new LongDeserializer(Long.TYPE, 0L); final static LongDeserializer wrapperInstance = new LongDeserializer(Long.class, null); public LongDeserializer(Class<Long> cls, Long nvl) { super(cls, LogicalType.Integer, nvl, 0L); } @Override public boolean isCachable() { return true; } @Override public Long deserialize(JsonParser p, DeserializationContext ctxt) throws JacksonException { if (p.isExpectedNumberIntToken()) { return p.getLongValue(); } if (_primitive) { return _parseLongPrimitive(p, ctxt); } return _parseLong(p, ctxt, Long.class); } } @JacksonStdImpl public static
LongDeserializer
java
spring-projects__spring-boot
module/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/testcontainers/RedpandaContainerConnectionDetailsFactory.java
{ "start": 1420, "end": 1867 }
class ____ extends ContainerConnectionDetailsFactory<RedpandaContainer, KafkaConnectionDetails> { @Override protected KafkaConnectionDetails getContainerConnectionDetails( ContainerConnectionSource<RedpandaContainer> source) { return new RedpandaContainerConnectionDetails(source); } /** * {@link KafkaConnectionDetails} backed by a {@link ContainerConnectionSource}. */ private static final
RedpandaContainerConnectionDetailsFactory
java
spring-projects__spring-boot
module/spring-boot-webflux/src/test/java/org/springframework/boot/webflux/autoconfigure/WebFluxAutoConfigurationTests.java
{ "start": 52001, "end": 52067 }
class ____ { } } @Aspect static
HighestOrderedControllerAdvice
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/SchemaBuilder.java
{ "start": 75356, "end": 75870 }
class ____<R> extends FieldDefault<R, ArrayDefault<R>> { private ArrayDefault(FieldBuilder<R> field) { super(field); } /** Completes this field with the default value provided, cannot be null **/ public final <V> FieldAssembler<R> arrayDefault(List<V> defaultVal) { return super.usingDefault(defaultVal); } @Override final ArrayDefault<R> self() { return this; } } /** Choose whether to use a default value for the field or not. **/ public static
ArrayDefault
java
micronaut-projects__micronaut-core
management/src/test/java/io/micronaut/management/health/indicator/jdbc/JdbcIndicatorTest.java
{ "start": 654, "end": 1420 }
class ____ { @Test void jdbcHealthIndicatorViaConfiguration() { Map<String, Object> configuration = Map.of( "endpoints.health.jdbc.enabled", StringUtils.FALSE, "spec.name", "JdbcIndicatorTest"); try (ApplicationContext context = ApplicationContext.run(configuration)) { assertFalse(context.containsBean(JdbcIndicator.class)); } // enabled by default configuration = Map.of("spec.name", "JdbcIndicatorTest"); try (ApplicationContext context = ApplicationContext.run(configuration)) { assertTrue(context.containsBean(JdbcIndicator.class)); } } @Requires(property = "spec.name", value = "JdbcIndicatorTest") @Singleton static
JdbcIndicatorTest
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/catalog/AbstractConstraint.java
{ "start": 1059, "end": 1992 }
class ____ implements Constraint { private final String name; private final boolean enforced; AbstractConstraint(String name, boolean enforced) { this.name = checkNotNull(name); this.enforced = enforced; } @Override public String getName() { return name; } @Override public boolean isEnforced() { return enforced; } @Override public String toString() { return asSummaryString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AbstractConstraint that = (AbstractConstraint) o; return enforced == that.enforced && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name, enforced); } }
AbstractConstraint
java
google__guice
core/test/com/google/inject/TypeLiteralInjectionTest.java
{ "start": 3259, "end": 3428 }
class ____<T> { @Inject TypeLiteral<String> string; @Inject TypeLiteral<List<T>> listOfT; @Inject TypeLiteral<List<? extends T>> listOfWildcardT; } static
A
java
spring-projects__spring-boot
module/spring-boot-webmvc/src/test/java/org/springframework/boot/webmvc/autoconfigure/error/DefaultErrorViewIntegrationTests.java
{ "start": 2108, "end": 3528 }
class ____ { @Autowired private WebApplicationContext wac; private MockMvcTester mvc; @BeforeEach void setup() { this.mvc = MockMvcTester.from(this.wac); } @Test void testErrorForBrowserClient() { assertThat(this.mvc.get().uri("/error").accept(MediaType.TEXT_HTML)).hasStatus5xxServerError() .bodyText() .contains("<html>", "999"); } @Test void testErrorWithHtmlEscape() { assertThat(this.mvc.get() .uri("/error") .requestAttr("jakarta.servlet.error.exception", new RuntimeException("<script>alert('Hello World')</script>")) .accept(MediaType.TEXT_HTML)).hasStatus5xxServerError() .bodyText() .contains("&lt;script&gt;", "Hello World", "999"); } @Test void testErrorWithSpelEscape() { String spel = "${T(" + getClass().getName() + ").injectCall()}"; assertThat(this.mvc.get() .uri("/error") .requestAttr("jakarta.servlet.error.exception", new RuntimeException(spel)) .accept(MediaType.TEXT_HTML)).hasStatus5xxServerError().bodyText().doesNotContain("injection"); } static String injectCall() { return "injection"; } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({ DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @
DefaultErrorViewIntegrationTests
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/GetOverallBucketsAction.java
{ "start": 10009, "end": 10553 }
class ____ extends AbstractGetResourcesResponse<OverallBucket> implements ToXContentObject { public Response(StreamInput in) throws IOException { super(in); } public Response(QueryPage<OverallBucket> overallBuckets) { super(overallBuckets); } public QueryPage<OverallBucket> getOverallBuckets() { return getResources(); } @Override protected Reader<OverallBucket> getReader() { return OverallBucket::new; } } }
Response
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/collection/internal/StandardListSemantics.java
{ "start": 1140, "end": 2958 }
class ____<E> implements CollectionSemantics<List<E>, E> { /** * Singleton access */ public static final StandardListSemantics<?> INSTANCE = new StandardListSemantics<>(); private StandardListSemantics() { } @Override public CollectionClassification getCollectionClassification() { return CollectionClassification.LIST; } @SuppressWarnings("rawtypes") @Override public Class<List> getCollectionJavaType() { return List.class; } @Override public List<E> instantiateRaw( int anticipatedSize, CollectionPersister collectionDescriptor) { return CollectionHelper.arrayList( anticipatedSize ); } @Override public Iterator<E> getElementIterator(List<E> rawCollection) { return rawCollection.iterator(); } @Override public void visitElements(List<E> rawCollection, Consumer<? super E> action) { rawCollection.forEach( action ); } @Override public PersistentCollection<E> instantiateWrapper( Object key, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { return new PersistentList<>( session ); } @Override public PersistentCollection<E> wrap( List<E> rawCollection, CollectionPersister collectionDescriptor, SharedSessionContractImplementor session) { return new PersistentList<>( session, rawCollection ); } @Override public CollectionInitializerProducer createInitializerProducer( NavigablePath navigablePath, PluralAttributeMapping attributeMapping, FetchParent fetchParent, boolean selected, String resultVariable, Fetch indexFetch, Fetch elementFetch, DomainResultCreationState creationState) { return InitializerProducerBuilder.createListInitializerProducer( navigablePath, attributeMapping, fetchParent, selected, indexFetch, elementFetch, creationState ); } }
StandardListSemantics
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/config/v2/SerializationType.java
{ "start": 856, "end": 1421 }
enum ____ { UNSPECIFIED((byte) 0), JSON((byte) 1), PROTOBUF((byte) 2), FLAT_BUFFERS((byte) 3); private final byte value; SerializationType(byte value) { this.value = value; } public byte getValue() { return value; } public static SerializationType valueOf(byte value) { for (SerializationType type : SerializationType.values()) { if (type.getValue() == value) { return type; } } return SerializationType.UNSPECIFIED; } }
SerializationType
java
google__error-prone
check_api/src/test/java/com/google/errorprone/util/ASTHelpersTest.java
{ "start": 63003, "end": 63077 }
class ____ { @Target({METHOD, FIELD}) @
Declaration
java
spring-projects__spring-boot
module/spring-boot-security/src/main/java/org/springframework/boot/security/web/servlet/ApplicationContextRequestMatcher.java
{ "start": 1672, "end": 4326 }
class ____<C> implements RequestMatcher { private final Class<? extends C> contextClass; private volatile boolean initialized; private final Object initializeLock = new Object(); public ApplicationContextRequestMatcher(Class<? extends C> contextClass) { Assert.notNull(contextClass, "'contextClass' must not be null"); this.contextClass = contextClass; } @Override public final boolean matches(HttpServletRequest request) { WebApplicationContext webApplicationContext = WebApplicationContextUtils .getRequiredWebApplicationContext(request.getServletContext()); if (ignoreApplicationContext(webApplicationContext)) { return false; } Supplier<C> context = () -> getContext(webApplicationContext); if (!this.initialized) { synchronized (this.initializeLock) { if (!this.initialized) { initialized(context); this.initialized = true; } } } return matches(request, context); } @SuppressWarnings("unchecked") private C getContext(WebApplicationContext webApplicationContext) { if (this.contextClass.isInstance(webApplicationContext)) { return (C) webApplicationContext; } return webApplicationContext.getBean(this.contextClass); } /** * Returns if the {@link WebApplicationContext} should be ignored and not used for * matching. If this method returns {@code true} then the context will not be used and * the {@link #matches(HttpServletRequest) matches} method will return {@code false}. * @param webApplicationContext the candidate web application context * @return if the application context should be ignored */ protected boolean ignoreApplicationContext(WebApplicationContext webApplicationContext) { return false; } /** * Method that can be implemented by subclasses that wish to initialize items the * first time that the matcher is called. This method will be called only once and * only if {@link #ignoreApplicationContext(WebApplicationContext)} returns * {@code false}. Note that the supplied context will be based on the * <strong>first</strong> request sent to the matcher. * @param context a supplier for the initialized context (may throw an exception) * @see #ignoreApplicationContext(WebApplicationContext) */ protected void initialized(Supplier<C> context) { } /** * Decides whether the rule implemented by the strategy matches the supplied request. * @param request the source request * @param context a supplier for the initialized context (may throw an exception) * @return if the request matches */ protected abstract boolean matches(HttpServletRequest request, Supplier<C> context); }
ApplicationContextRequestMatcher
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CxfEndpointBuilderFactory.java
{ "start": 11180, "end": 12776 }
class ____ * could have JSR181 annotation or not. * * The option will be converted to a * <code>java.lang.Class&lt;java.lang.Object&gt;</code> type. * * Group: service * * @param serviceClass the value to set * @return the dsl builder */ default CxfEndpointConsumerBuilder serviceClass(String serviceClass) { doSetProperty("serviceClass", serviceClass); return this; } /** * The service name this service is implementing, it maps to the * wsdl:servicename. * * The option is a: <code>java.lang.String</code> type. * * Group: service * * @param serviceName the value to set * @return the dsl builder */ default CxfEndpointConsumerBuilder serviceName(String serviceName) { doSetProperty("serviceName", serviceName); return this; } /** * The location of the WSDL. Can be on the classpath, file system, or be * hosted remotely. * * The option is a: <code>java.lang.String</code> type. * * Group: service * * @param wsdlURL the value to set * @return the dsl builder */ default CxfEndpointConsumerBuilder wsdlURL(String wsdlURL) { doSetProperty("wsdlURL", wsdlURL); return this; } } /** * Advanced builder for endpoint consumers for the CXF component. */ public
which
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/ITestAzureBlobFileSystemStoreListStatusWithRange.java
{ "start": 1402, "end": 6120 }
class ____ extends AbstractAbfsIntegrationTest { private static final boolean SUCCEED = true; private static final boolean FAIL = false; private static final String[] SORTED_ENTRY_NAMES = {"1_folder", "A0", "D01", "a+", "c0", "name5"}; private AzureBlobFileSystemStore store; private AzureBlobFileSystem fs; public String path; /** * A valid startFrom for listFileStatus with range is a non-fully qualified dir/file name * */ public String startFrom; public int expectedStartIndexInArray; public boolean expectedResult; public static Iterable<Object[]> params() { return Arrays.asList( new Object[][]{ // case 0: list in root, without range {"/", null, 0, SUCCEED}, // case 1: list in the root, start from the second file {"/", SORTED_ENTRY_NAMES[1], 1, SUCCEED}, // case 2: list in the root, invalid startFrom {"/", "/", -1, FAIL}, // case 3: list in non-root level, valid startFrom : dir name {"/" + SORTED_ENTRY_NAMES[2], SORTED_ENTRY_NAMES[1], 1, SUCCEED}, // case 4: list in non-root level, valid startFrom : file name {"/" + SORTED_ENTRY_NAMES[2], SORTED_ENTRY_NAMES[2], 2, SUCCEED}, // case 5: list in non root level, invalid startFrom {"/" + SORTED_ENTRY_NAMES[2], "/" + SORTED_ENTRY_NAMES[3], -1, FAIL}, // case 6: list using non existent startFrom, startFrom is smaller than the entries in lexical order // expecting return all entries {"/" + SORTED_ENTRY_NAMES[2], "0-non-existent", 0, SUCCEED}, // case 7: list using non existent startFrom, startFrom is larger than the entries in lexical order // expecting return 0 entries {"/" + SORTED_ENTRY_NAMES[2], "z-non-existent", -1, SUCCEED}, // case 8: list using non existent startFrom, startFrom is in the range {"/" + SORTED_ENTRY_NAMES[2], "A1", 2, SUCCEED} }); } public ITestAzureBlobFileSystemStoreListStatusWithRange(String pPath, String pStartFrom, int pExpectedStartIndexInArray, boolean pExpectedResult) throws Exception { super(); this.path = pPath; this.startFrom = pStartFrom; this.expectedStartIndexInArray = pExpectedStartIndexInArray; this.expectedResult = pExpectedResult; if (this.getFileSystem() == null) { super.createFileSystem(); } fs = this.getFileSystem(); store = fs.getAbfsStore(); prepareTestFiles(); // Sort the names for verification, ABFS service should return the results in order. Arrays.sort(SORTED_ENTRY_NAMES); } @Test public void testListWithRange() throws IOException { try { FileStatus[] listResult = store.listStatus(new Path(path), startFrom, getTestTracingContext(fs, true)); if (!expectedResult) { Assertions.fail("Excepting failure with IllegalArgumentException"); } verifyFileStatus(listResult, new Path(path), expectedStartIndexInArray); } catch (IllegalArgumentException ex) { if (expectedResult) { Assertions.fail("Excepting success"); } } } // compare the file status private void verifyFileStatus(FileStatus[] listResult, Path parentPath, int startIndexInSortedName) throws IOException { if (startIndexInSortedName == -1) { Assertions.assertEquals(0, listResult.length, "Expected empty FileStatus array"); return; } FileStatus[] allFileStatuses = fs.listStatus(parentPath); Assertions.assertEquals(SORTED_ENTRY_NAMES.length, allFileStatuses.length, "number of dir/file doesn't match"); int indexInResult = 0; for (int index = startIndexInSortedName; index < SORTED_ENTRY_NAMES.length; index++) { Assertions.assertEquals(allFileStatuses[index], listResult[indexInResult++], "fileStatus doesn't match"); } } private void prepareTestFiles() throws IOException { final AzureBlobFileSystem fs = getFileSystem(); // created 2 level file structures for (String levelOneFolder : SORTED_ENTRY_NAMES) { Path levelOnePath = new Path("/" + levelOneFolder); Assertions.assertTrue(fs.mkdirs(levelOnePath)); for (String fileName : SORTED_ENTRY_NAMES) { Path filePath = new Path(levelOnePath, fileName); ContractTestUtils.touch(fs, filePath); ContractTestUtils.assertIsFile(fs, filePath); } } } }
ITestAzureBlobFileSystemStoreListStatusWithRange
java
spring-projects__spring-boot
module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/DataSourceUnwrapper.java
{ "start": 3814, "end": 4097 }
class ____ { private static @Nullable DataSource getTargetDataSource(DataSource dataSource) { if (dataSource instanceof DelegatingDataSource delegatingDataSource) { return delegatingDataSource.getTargetDataSource(); } return null; } } }
DelegatingDataSourceUnwrapper
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/targetclass/mixed/AroundInvokeOnTargetClassAndOutsideAndSuperclassesWithOverridesTest.java
{ "start": 1241, "end": 1510 }
class ____ { @AroundInvoke Object intercept(InvocationContext ctx) throws Exception { return "this should not be called as the method is overridden in MyBean"; } } @Singleton @MyInterceptorBinding static
MyBeanSuperclass
java
apache__camel
core/camel-util/src/test/java/org/apache/camel/util/CamelURIParserTest.java
{ "start": 999, "end": 5170 }
class ____ { @Test public void testParseUri() { String[] out1 = CamelURIParser.parseUri("smtp://localhost?username=davsclaus&password=secret"); assertEquals("smtp", out1[0]); assertEquals("localhost", out1[1]); assertEquals("username=davsclaus&password=secret", out1[2]); } @Test public void testParseNoSlashUri() { String[] out1 = CamelURIParser.parseUri("direct:start"); assertEquals("direct", out1[0]); assertEquals("start", out1[1]); assertNull(out1[2]); } @Test public void testParseUriSlashAndQuery() { String[] out1 = CamelURIParser.parseUri("file:/absolute?recursive=true"); assertEquals("file", out1[0]); assertEquals("/absolute", out1[1]); assertEquals("recursive=true", out1[2]); String[] out2 = CamelURIParser.parseUri("file:///absolute?recursive=true"); assertEquals("file", out2[0]); assertEquals("/absolute", out2[1]); assertEquals("recursive=true", out2[2]); String[] out3 = CamelURIParser.parseUri("file://relative?recursive=true"); assertEquals("file", out3[0]); assertEquals("relative", out3[1]); assertEquals("recursive=true", out3[2]); String[] out4 = CamelURIParser.parseUri("file:relative?recursive=true"); assertEquals("file", out4[0]); assertEquals("relative", out4[1]); assertEquals("recursive=true", out4[2]); } @Test public void testParseUriSlash() { String[] out1 = CamelURIParser.parseUri("file:/absolute"); assertEquals("file", out1[0]); assertEquals("/absolute", out1[1]); assertNull(out1[2]); String[] out2 = CamelURIParser.parseUri("file:///absolute"); assertEquals("file", out2[0]); assertEquals("/absolute", out2[1]); assertNull(out2[2]); String[] out3 = CamelURIParser.parseUri("file://relative"); assertEquals("file", out3[0]); assertEquals("relative", out3[1]); assertNull(out3[2]); String[] out4 = CamelURIParser.parseUri("file:relative"); assertEquals("file", out4[0]); assertEquals("relative", out4[1]); assertNull(out4[2]); } @Test public void testParseInvalid() { assertNull(CamelURIParser.parseUri("doesnotexists")); assertNull(CamelURIParser.parseUri("doesnotexists:")); assertNull(CamelURIParser.parseUri("doesnotexists/foo")); assertNull(CamelURIParser.parseUri("doesnotexists?")); } @Test public void testParseNoPathButSlash() { String[] out1 = CamelURIParser.parseUri("file:/"); assertEquals("file", out1[0]); assertEquals("/", out1[1]); assertNull(out1[2]); String[] out2 = CamelURIParser.parseUri("file:///"); assertEquals("file", out2[0]); assertEquals("/", out2[1]); assertNull(out2[2]); } @Test public void testParseEmptyQuery() { String[] out1 = CamelURIParser.parseUri("file:relative"); assertEquals("file", out1[0]); assertEquals("relative", out1[1]); assertNull(out1[2]); String[] out2 = CamelURIParser.parseUri("file:relative?"); assertEquals("file", out2[0]); assertEquals("relative", out2[1]); assertNull(out2[2]); } @Test public void testFastParse() { String[] out1 = CamelURIParser.fastParseUri("file:relative"); assertEquals("file", out1[0]); assertEquals("relative", out1[1]); assertNull(out1[2]); String[] out2 = CamelURIParser.fastParseUri("file://relative"); assertEquals(CamelURIParser.URI_ALREADY_NORMALIZED, out2); String[] out3 = CamelURIParser.fastParseUri("file:relative?delete=true"); assertEquals("file", out3[0]); assertEquals("relative", out3[1]); assertEquals("delete=true", out3[2]); String[] out4 = CamelURIParser.fastParseUri("file://relative?delete=true"); assertEquals("file", out4[0]); assertEquals("relative", out4[1]); assertEquals("delete=true", out4[2]); } }
CamelURIParserTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DefaultLocaleTest.java
{ "start": 17478, "end": 17874 }
class ____ { void f() throws Exception { new MessageFormat("%d", Locale.ROOT).format(42); } } """) .doTest(); } @Test public void refactoringAddLocaleCategoryFormatStaticImport() { refactoringTest() .addInputLines( "Test.java", """ import java.text.*;
Test
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/transport/LinkedProjectConfig.java
{ "start": 11120, "end": 13215 }
class ____ extends Builder<SniffLinkedProjectConfigBuilder> { private Predicate<DiscoveryNode> nodePredicate = RemoteClusterSettings.SniffConnectionStrategySettings.DEFAULT_NODE_PREDICATE; private List<String> seedNodes = RemoteClusterSettings.SniffConnectionStrategySettings.DEFAULT_SEED_NODES; public SniffLinkedProjectConfigBuilder(String linkedProjectAlias) { super(ProjectId.DEFAULT, ProjectId.DEFAULT, linkedProjectAlias, ConnectionStrategy.SNIFF); } public SniffLinkedProjectConfigBuilder(ProjectId originProjectId, ProjectId linkedProjectId, String linkedProjectAlias) { super(originProjectId, linkedProjectId, linkedProjectAlias, ConnectionStrategy.SNIFF); } public SniffLinkedProjectConfigBuilder nodePredicate(Predicate<DiscoveryNode> nodePredicate) { this.nodePredicate = Objects.requireNonNull(nodePredicate); return this; } public SniffLinkedProjectConfigBuilder seedNodes(List<String> seedNodes) { // TODO: Eliminate leniency here allowing an empty set of seed nodes, ES-12737. Objects.requireNonNull(seedNodes).forEach(RemoteConnectionStrategy::parsePort); this.seedNodes = seedNodes; return this; } @Override public SniffLinkedProjectConfig build() { return new SniffLinkedProjectConfig( originProjectId, linkedProjectId, linkedProjectAlias, transportConnectTimeout, connectionCompression, connectionCompressionScheme, clusterPingSchedule, initialConnectionTimeout, skipUnavailable, maxPendingConnectionListeners, maxNumConnections, nodePredicate, seedNodes, proxyAddress ); } @Override protected SniffLinkedProjectConfigBuilder self() { return this; } } }
SniffLinkedProjectConfigBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/elementcollection/EmbeddedElementCollectionWithIdenticallyNamedAssociation2Test.java
{ "start": 4845, "end": 5308 }
class ____ { @OneToOne @JoinColumn(name = "entityA_id") EntityA identicallyNamedAssociation; public IdenticallyNamedAssociationHolder() { } public IdenticallyNamedAssociationHolder(EntityA identicallyNamedAssociation) { this.identicallyNamedAssociation = identicallyNamedAssociation; } public EntityA getIdenticallyNamedAssociation() { return identicallyNamedAssociation; } } @Embeddable public static
IdenticallyNamedAssociationHolder
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/TypeInferenceExtractorTest.java
{ "start": 93418, "end": 93534 }
class ____ extends TableFunction<String> { // nothing to do } private static
MissingMethodTableFunction
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/testers/QueuePollTester.java
{ "start": 1759, "end": 2521 }
class ____<E> extends AbstractQueueTester<E> { @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ZERO) public void testPoll_empty() { assertNull("emptyQueue.poll() should return null", getQueue().poll()); expectUnchanged(); } @CollectionFeature.Require(SUPPORTS_REMOVE) @CollectionSize.Require(ONE) public void testPoll_size1() { assertEquals("size1Queue.poll() should return first element", e0(), getQueue().poll()); expectMissing(e0()); } @CollectionFeature.Require({KNOWN_ORDER, SUPPORTS_REMOVE}) @CollectionSize.Require(SEVERAL) public void testPoll_sizeMany() { assertEquals("sizeManyQueue.poll() should return first element", e0(), getQueue().poll()); expectMissing(e0()); } }
QueuePollTester
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/TypeToStringTest.java
{ "start": 869, "end": 1738 }
class ____ { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(TypeToString.class, getClass()); @Test public void noMatch() { testHelper .addSourceLines( "ExampleChecker.java", """ import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ClassTree; import com.sun.tools.javac.code.Types; @BugPattern(name = "Example", summary = "", severity = SeverityLevel.ERROR) public
TypeToStringTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/enums/EnumAliasDeser2352Test.java
{ "start": 490, "end": 568 }
class ____ { // for [databind#2352]: Support aliases on
EnumAliasDeser2352Test
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/MonitoringInfoTransportActionTests.java
{ "start": 1846, "end": 6985 }
class ____ extends ESTestCase { private final MonitoringService monitoring = mock(MonitoringService.class); private final Exporters exporters = mock(Exporters.class); public void testAvailable() { TransportService transportService = MockUtils.setupTransportServiceWithThreadpoolExecutor(); MonitoringInfoTransportAction featureSet = new MonitoringInfoTransportAction(transportService, mock(ActionFilters.class)); assertThat(featureSet.available(), is(true)); } public void testMonitoringEnabledByDefault() { TransportService transportService = MockUtils.setupTransportServiceWithThreadpoolExecutor(); MonitoringInfoTransportAction featureSet = new MonitoringInfoTransportAction(transportService, mock(ActionFilters.class)); assertThat(featureSet.enabled(), is(true)); } public void testUsage() throws Exception { TransportVersion serializedVersion = TransportVersionUtils.randomCompatibleVersion(random()); final boolean collectionEnabled = randomBoolean(); int localCount = randomIntBetween(0, 5); List<Exporter> exporterList = new ArrayList<>(); for (int i = 0; i < localCount; i++) { Exporter exporter = mockExporter(LocalExporter.TYPE, true); exporterList.add(exporter); if (randomBoolean()) { exporter = mockExporter(LocalExporter.TYPE, false); exporterList.add(exporter); } } int httpCount = randomIntBetween(0, 5); for (int i = 0; i < httpCount; i++) { Exporter exporter = mockExporter(HttpExporter.TYPE, true); exporterList.add(exporter); if (randomBoolean()) { exporter = mockExporter(HttpExporter.TYPE, false); exporterList.add(exporter); } } int xCount = randomIntBetween(0, 5); String xType = randomAlphaOfLength(10); for (int i = 0; i < xCount; i++) { Exporter exporter = mockExporter(xType, true); exporterList.add(exporter); if (randomBoolean()) { exporter = mockExporter(xType, false); exporterList.add(exporter); } } when(exporters.getEnabledExporters()).thenReturn(exporterList); when(monitoring.isMonitoringActive()).thenReturn(collectionEnabled); ThreadPool threadPool = mock(ThreadPool.class); TransportService transportService = MockUtils.setupTransportServiceWithThreadpoolExecutor(threadPool); var usageAction = new MonitoringUsageTransportAction( transportService, null, threadPool, mock(ActionFilters.class), new MonitoringUsageServices(monitoring, exporters) ); PlainActionFuture<XPackUsageFeatureResponse> future = new PlainActionFuture<>(); usageAction.localClusterStateOperation(null, null, null, future); MonitoringFeatureSetUsage monitoringUsage = (MonitoringFeatureSetUsage) future.get().getUsage(); BytesStreamOutput out = new BytesStreamOutput(); out.setTransportVersion(serializedVersion); monitoringUsage.writeTo(out); StreamInput in = out.bytes().streamInput(); in.setTransportVersion(serializedVersion); XPackFeatureUsage serializedUsage = new MonitoringFeatureSetUsage(in); for (XPackFeatureUsage usage : Arrays.asList(monitoringUsage, serializedUsage)) { ObjectPath source; try (XContentBuilder builder = jsonBuilder()) { usage.toXContent(builder, ToXContent.EMPTY_PARAMS); source = ObjectPath.createFromXContent(builder.contentType().xContent(), BytesReference.bytes(builder)); } assertThat(source.evaluate("collection_enabled"), is(collectionEnabled)); assertThat(source.evaluate("enabled_exporters"), is(notNullValue())); if (localCount > 0) { assertThat(source.evaluate("enabled_exporters.local"), is(localCount)); } else { assertThat(source.evaluate("enabled_exporters.local"), is(nullValue())); } if (httpCount > 0) { assertThat(source.evaluate("enabled_exporters.http"), is(httpCount)); } else { assertThat(source.evaluate("enabled_exporters.http"), is(nullValue())); } if (xCount > 0) { assertThat(source.evaluate("enabled_exporters." + xType), is(xCount)); } else { assertThat(source.evaluate("enabled_exporters." + xType), is(nullValue())); } } } private Exporter mockExporter(String type, boolean enabled) { Exporter exporter = mock(Exporter.class); Exporter.Config enabledConfig = mock(Exporter.Config.class); when(enabledConfig.enabled()).thenReturn(enabled); when(exporter.config()).thenReturn(enabledConfig); when(enabledConfig.type()).thenReturn(type); return exporter; } }
MonitoringInfoTransportActionTests
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/v2/StateBackendTestV2Base.java
{ "start": 29651, "end": 30001 }
class ____ implements AsyncFutureImpl.AsyncFrameworkExceptionHandler { String message = null; Throwable exception = null; public void handleException(String message, Throwable exception) { this.message = message; this.exception = exception; } } }
TestAsyncFrameworkExceptionHandler
java
spring-projects__spring-boot
core/spring-boot-test/src/main/java/org/springframework/boot/test/context/AnnotatedClassFinder.java
{ "start": 1201, "end": 1376 }
class ____ with a particular annotation in a hierarchy. * * @author Phillip Webb * @author Artsiom Yudovin * @author Stephane Nicoll * @since 2.1.0 */ public final
annotated
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/SequenceFile.java
{ "start": 65849, "end": 66047 }
class ____ extends Options.LongOption implements Option { private StartOption(long value) { super(value); } } private static
StartOption
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableBufferBoundary.java
{ "start": 8916, "end": 10214 }
class ____<Open> extends AtomicReference<Disposable> implements Observer<Open>, Disposable { private static final long serialVersionUID = -8498650778633225126L; final BufferBoundaryObserver<?, ?, Open, ?> parent; BufferOpenObserver(BufferBoundaryObserver<?, ?, Open, ?> parent) { this.parent = parent; } @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(this, d); } @Override public void onNext(Open t) { parent.open(t); } @Override public void onError(Throwable t) { lazySet(DisposableHelper.DISPOSED); parent.boundaryError(this, t); } @Override public void onComplete() { lazySet(DisposableHelper.DISPOSED); parent.openComplete(this); } @Override public void dispose() { DisposableHelper.dispose(this); } @Override public boolean isDisposed() { return get() == DisposableHelper.DISPOSED; } } } static final
BufferOpenObserver
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/proxy/InsertValues_1.java
{ "start": 272, "end": 911 }
class ____ extends TestCase { public void test_insert_values() throws Exception { String sql = "insert into t (f0, f1, f2, f3, f4) values ('????????????????????????', '????????????????????????', '????????????????????????', '????????????????????????', '????????????????????????')"; PreparedStatementProxyImpl proxy = new PreparedStatementProxyImpl(null, null, sql, 0); Field field = PreparedStatementProxyImpl.class.getDeclaredField("parameters"); field.setAccessible(true); JdbcParameter[] params = (JdbcParameter[]) field.get(proxy); assertEquals(0, params.length); } }
InsertValues_1
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/EagerAnyDiscriminatorQueryTest.java
{ "start": 4660, "end": 5045 }
class ____ implements Property<String> { @Id private Long id; @Column(name = "VALUE_COLUMN") private String value; public StringProperty() { } public StringProperty(Long id, String value) { this.id = id; this.value = value; } @Override public Long getId() { return id; } @Override public String getValue() { return value; } } }
StringProperty
java
apache__camel
components/camel-reactive-streams/src/main/java/org/apache/camel/component/reactive/streams/util/ConvertingPublisher.java
{ "start": 1287, "end": 4101 }
class ____<R> implements Publisher<R> { private static final Logger LOG = LoggerFactory.getLogger(ConvertingPublisher.class); private final Publisher<Exchange> delegate; private final Class<R> type; private final BodyConverter<R> converter; public ConvertingPublisher(Publisher<Exchange> delegate, Class<R> type) { Objects.requireNonNull(delegate, "delegate publisher cannot be null"); Objects.requireNonNull(type, "type cannot be null"); this.delegate = delegate; this.type = type; this.converter = BodyConverter.forType(type); } @Override public void subscribe(Subscriber<? super R> subscriber) { delegate.subscribe(new Subscriber<Exchange>() { private AtomicBoolean active = new AtomicBoolean(true); private Subscription subscription; @Override public void onSubscribe(Subscription newSubscription) { if (newSubscription == null) { throw new NullPointerException("subscription is null"); } else if (newSubscription == this.subscription) { throw new IllegalArgumentException("already subscribed to the subscription: " + newSubscription); } if (this.subscription != null) { newSubscription.cancel(); } else { this.subscription = newSubscription; subscriber.onSubscribe(newSubscription); } } @Override public void onNext(Exchange ex) { if (!active.get()) { return; } R r; try { r = converter.apply(ex); } catch (TypeConversionException e) { LOG.warn("Unable to convert body to the specified type: {}", type.getName(), e); r = null; } if (r == null && ex.getIn().getBody() != null) { this.onError(new ClassCastException("Unable to convert body to the specified type: " + type.getName())); active.set(false); subscription.cancel(); } else { subscriber.onNext(r); } } @Override public void onError(Throwable throwable) { if (!active.get()) { return; } subscriber.onError(throwable); } @Override public void onComplete() { if (!active.get()) { return; } subscriber.onComplete(); } }); } }
ConvertingPublisher
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/deser/InnerClassDeser2.java
{ "start": 188, "end": 482 }
class ____ extends TestCase { public void test_for_inner_class() throws Exception { Model model = JSON.parseObject("{\"items\":[{\"id\":123}]}", Model.class); assertNotNull(model.items); assertEquals(123, model.items.get(0).id); } public static
InnerClassDeser2
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/stringlist/User.java
{ "start": 730, "end": 1340 }
class ____ { private Integer id; private String name; private List<String> groups; private List<String> roles; public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } public List<String> getGroups() { return groups; } public void setGroups(List<String> groups) { this.groups = groups; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
User
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/utils/YarnServerSecurityUtils.java
{ "start": 1807, "end": 5725 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(YarnServerSecurityUtils.class); private YarnServerSecurityUtils() { } /** * Authorizes the current request and returns the AMRMTokenIdentifier for the * current application. * * @return the AMRMTokenIdentifier instance for the current user * @throws YarnException exceptions from yarn servers. */ public static AMRMTokenIdentifier authorizeRequest() throws YarnException { UserGroupInformation remoteUgi; try { remoteUgi = UserGroupInformation.getCurrentUser(); } catch (IOException e) { String msg = "Cannot obtain the user-name for authorizing ApplicationMaster. " + "Got exception: " + StringUtils.stringifyException(e); LOG.warn(msg); throw RPCUtil.getRemoteException(msg); } boolean tokenFound = false; String message = ""; AMRMTokenIdentifier appTokenIdentifier = null; try { appTokenIdentifier = selectAMRMTokenIdentifier(remoteUgi); if (appTokenIdentifier == null) { tokenFound = false; message = "No AMRMToken found for user " + remoteUgi.getUserName(); } else { tokenFound = true; } } catch (IOException e) { tokenFound = false; message = "Got exception while looking for AMRMToken for user " + remoteUgi.getUserName(); } if (!tokenFound) { LOG.warn(message); throw RPCUtil.getRemoteException(message); } return appTokenIdentifier; } // Obtain the needed AMRMTokenIdentifier from the remote-UGI. RPC layer // currently sets only the required id, but iterate through anyways just to be // sure. private static AMRMTokenIdentifier selectAMRMTokenIdentifier( UserGroupInformation remoteUgi) throws IOException { AMRMTokenIdentifier result = null; Set<TokenIdentifier> tokenIds = remoteUgi.getTokenIdentifiers(); for (TokenIdentifier tokenId : tokenIds) { if (tokenId instanceof AMRMTokenIdentifier) { result = (AMRMTokenIdentifier) tokenId; break; } } return result; } /** * Update the new AMRMToken into the ugi used for RM proxy. * * @param token the new AMRMToken sent by RM * @param user ugi used for RM proxy * @param conf configuration */ public static void updateAMRMToken( org.apache.hadoop.yarn.api.records.Token token, UserGroupInformation user, Configuration conf) { Token<AMRMTokenIdentifier> amrmToken = new Token<AMRMTokenIdentifier>( token.getIdentifier().array(), token.getPassword().array(), new Text(token.getKind()), new Text(token.getService())); // Preserve the token service sent by the RM when adding the token // to ensure we replace the previous token setup by the RM. // Afterwards we can update the service address for the RPC layer. user.addToken(amrmToken); amrmToken.setService(ClientRMProxy.getAMRMTokenService(conf)); } /** * Parses the container launch context and returns a Credential instance that * contains all the tokens from the launch context. * * @param launchContext ContainerLaunchContext. * @return the credential instance * @throws IOException if there are I/O errors. */ public static Credentials parseCredentials( ContainerLaunchContext launchContext) throws IOException { Credentials credentials = new Credentials(); ByteBuffer tokens = launchContext.getTokens(); if (tokens != null) { DataInputByteBuffer buf = new DataInputByteBuffer(); tokens.rewind(); buf.reset(tokens); credentials.readTokenStorageStream(buf); if (LOG.isDebugEnabled()) { for (Token<? extends TokenIdentifier> tk : credentials.getAllTokens()) { LOG.debug("{}={}", tk.getService(), tk); } } } return credentials; } }
YarnServerSecurityUtils
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/testutil/DatabindTestUtil.java
{ "start": 8866, "end": 9027 }
class ____ { public float f; public FloatWrapper() { } public FloatWrapper(float value) { f = value; } } public static
FloatWrapper
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/XmlVerifierEndpointBuilderFactory.java
{ "start": 31078, "end": 36166 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final XmlVerifierHeaderNameBuilder INSTANCE = new XmlVerifierHeaderNameBuilder(); /** * Header which indicates that either the resulting signature document * in the signature generation case or the resulting output of the * verifier should not contain an XML declaration. If the header is not * specified then a XML declaration is created. There is one exception: * If the verifier result is a plain text this header has no effect. * Possible values of the header are Boolean#TRUE or Boolean#FALSE. * Overwrites the configuration parameter * XmlSignatureConfiguration#setOmitXmlDeclaration(Boolean). * * The option is a: {@code Boolean} type. * * Group: producer * * @return the name of the header {@code * XmlSignatureOmitXmlDeclaration}. */ public String xmlSignatureOmitXmlDeclaration() { return "CamelXmlSignatureOmitXmlDeclaration"; } /** * The schema resource URI. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code XmlSignatureSchemaResourceUri}. */ public String xmlSignatureSchemaResourceUri() { return "CamelXmlSignatureSchemaResourceUri"; } /** * XPaths to id attributes. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code * XmlSignatureXpathsToIdAttributes}. */ public String xmlSignatureXpathsToIdAttributes() { return "CamelXmlSignatureXpathsToIdAttributes"; } /** * for the 'Id' attribute value of QualifyingProperties element. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code * XmlSignatureXAdESQualifyingPropertiesId}. */ public String xmlSignatureXAdESQualifyingPropertiesId() { return "CamelXmlSignatureXAdESQualifyingPropertiesId"; } /** * for the 'Id' attribute value of SignedDataObjectProperties element. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code * XmlSignatureXAdESSignedDataObjectPropertiesId}. */ public String xmlSignatureXAdESSignedDataObjectPropertiesId() { return "CamelXmlSignatureXAdESSignedDataObjectPropertiesId"; } /** * for the 'Id' attribute value of SignedSignatureProperties element. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code * XmlSignatureXAdESSignedSignaturePropertiesId}. */ public String xmlSignatureXAdESSignedSignaturePropertiesId() { return "CamelXmlSignatureXAdESSignedSignaturePropertiesId"; } /** * for the value of the Encoding element of the DataObjectFormat * element. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code * XmlSignatureXAdESDataObjectFormatEncoding}. */ public String xmlSignatureXAdESDataObjectFormatEncoding() { return "CamelXmlSignatureXAdESDataObjectFormatEncoding"; } /** * overwrites the XAdES namespace parameter value. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code XmlSignatureXAdESNamespace}. */ public String xmlSignatureXAdESNamespace() { return "CamelXmlSignatureXAdESNamespace"; } /** * overwrites the XAdES prefix parameter value. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code XmlSignatureXAdESPrefix}. */ public String xmlSignatureXAdESPrefix() { return "CamelXmlSignatureXAdESPrefix"; } /** * The name of the charset. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code CharsetName}. */ public String charsetName() { return "CamelCharsetName"; } } static XmlVerifierEndpointBuilder endpointBuilder(String componentName, String path) {
XmlVerifierHeaderNameBuilder
java
alibaba__nacos
logger-adapter-impl/log4j2-adapter/src/main/java/com/alibaba/nacos/logger/adapter/log4j2/Log4J2NacosLoggingAdapter.java
{ "start": 1552, "end": 5355 }
class ____ implements NacosLoggingAdapter { private static final String NACOS_LOG4J2_LOCATION = "classpath:nacos-log4j2.xml"; private static final String FILE_PROTOCOL = "file"; private static final String NACOS_LOGGER_PREFIX = "com.alibaba.nacos"; private static final String APPENDER_MARK = "ASYNC_NAMING"; private static final String LOG4J2_CLASSES = "org.apache.logging.slf4j.Log4jLogger"; @Override public boolean isAdaptedLogger(Class<?> loggerClass) { Class<?> expectedLoggerClass = getExpectedLoggerClass(); return null != expectedLoggerClass && expectedLoggerClass.isAssignableFrom(loggerClass); } private Class<?> getExpectedLoggerClass() { try { return Class.forName(LOG4J2_CLASSES); } catch (ClassNotFoundException e) { return null; } } @Override public boolean isNeedReloadConfiguration() { final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); final Configuration contextConfiguration = loggerContext.getConfiguration(); for (Map.Entry<String, Appender> entry : contextConfiguration.getAppenders().entrySet()) { if (APPENDER_MARK.equals(entry.getValue().getName())) { return false; } } return true; } @Override public String getDefaultConfigLocation() { return NACOS_LOG4J2_LOCATION; } @Override public void loadConfiguration(NacosLoggingProperties loggingProperties) { Log4j2NacosLoggingPropertiesHolder.setProperties(loggingProperties); String location = loggingProperties.getLocation(); loadConfiguration(location); } private void loadConfiguration(String location) { if (StringUtils.isBlank(location)) { return; } final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); final Configuration contextConfiguration = loggerContext.getConfiguration(); // load and start nacos configuration Configuration configuration = loadConfiguration(loggerContext, location); configuration.start(); // append loggers and appenders to contextConfiguration Map<String, Appender> appenders = configuration.getAppenders(); for (Appender appender : appenders.values()) { contextConfiguration.addAppender(appender); } Map<String, LoggerConfig> loggers = configuration.getLoggers(); for (String name : loggers.keySet()) { if (name.startsWith(NACOS_LOGGER_PREFIX)) { contextConfiguration.addLogger(name, loggers.get(name)); } } loggerContext.updateLoggers(); } private Configuration loadConfiguration(LoggerContext loggerContext, String location) { try { URL url = ResourceUtils.getResourceUrl(location); ConfigurationSource source = getConfigurationSource(url); // since log4j 2.7 getConfiguration(LoggerContext loggerContext, ConfigurationSource source) return ConfigurationFactory.getInstance().getConfiguration(loggerContext, source); } catch (Exception e) { throw new IllegalStateException("Could not initialize Log4J2 logging from " + location, e); } } private ConfigurationSource getConfigurationSource(URL url) throws IOException { InputStream stream = url.openStream(); if (FILE_PROTOCOL.equals(url.getProtocol())) { return new ConfigurationSource(stream, ResourceUtils.getResourceAsFile(url)); } return new ConfigurationSource(stream, url); } }
Log4J2NacosLoggingAdapter
java
apache__camel
components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/consumer/integration/replication_controllers/KubernetesReplicationControllersConsumerClusterwideLabelsIT.java
{ "start": 1993, "end": 3188 }
class ____ extends KubernetesConsumerTestSupport { @Test public void clusterWideLabelsTest() { createReplicationController(ns1, "rc1", LABELS); createReplicationController(ns2, "rc2", LABELS); createReplicationController(ns2, "rc3", Map.of("otherKey", "otherValue")); Awaitility.await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> { final List<String> list = result.getExchanges().stream().map(ex -> ex.getIn().getBody(String.class)).toList(); assertThat(list, allOf( hasItem(containsString("rc1")), hasItem(containsString("rc2")), not(hasItem(containsString("rc3"))))); }); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { fromF("kubernetes-replication-controllers://%s?oauthToken=%s&labelKey=%s&labelValue=%s", host, authToken, "testkey", "testvalue") .process(new KubernetesProcessor()) .to(result); } }; } }
KubernetesReplicationControllersConsumerClusterwideLabelsIT
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2807/spring/before/BeforeMethod.java
{ "start": 280, "end": 439 }
class ____ { private BeforeMethod() { } @BeforeMapping public static <T> void doNothing(Iterable<T> source) { return; } }
BeforeMethod
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/IterableMappingMethod.java
{ "start": 757, "end": 944 }
class ____ maps one iterable type to another. The collection * elements are mapped either by a {@link TypeConversion} or another mapping method. * * @author Gunnar Morling */ public
which
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/param/MySqlParameterizedOutputVisitorTest_30.java
{ "start": 583, "end": 6799 }
class ____ extends TestCase { public void test_for_parameterize() throws Exception { final DbType dbType = JdbcConstants.MYSQL; String sql = "/* 0a67bca314863468702364451e/0.3// */select `udata`.`id` as `id`,`udata`.`gmt_create` as `gmtCreate`,`udata`.`gmt_modified` as `gmtModified`,`udata`.`uid` as `userId`,`udata`.`user_nick` as `userNick`,`udata`.`user_type` as `userType`,`udata`.`aps` as `acPeSe`,`udata`.`rn` as `rn`,`udata`.`start_period_time` as `startPeriodTime`,`udata`.`ept` as `adTm`,`udata`.`status` as `status`,`udata`.`charging_period` as `chargingPeriod`,`udata`.`sn` as `sn`,`udata`.`cpd` as `chargingPeriodDesc`,`udata`.`task_total_num` as `taskTotalNum`,`udata`.`tcn` as `taCoNu`,`udata`.`task_type` as `taskType`,`udata`.`ilbu` as `isLaBiUs`" + " from `udata_0888` `udata` where ((`udata`.`id` IN (" + " (select MAX(`udata`.`id`) " + " from `udata_0888` `udata` " + " where ((`udata`.`uid` = 1039100792) AND (`udata`.`user_type` = 2) AND (`udata`.`start_period_time` <= '2017-01-01 00:00:00') AND (`udata`.`status` = 10) AND (`udata`.`charging_period` = 1) AND (`udata`.`task_type` = 1) AND (`udata`.`task_total_num` <= `udata`.`tcn`)) group by `udata`.`charging_period`,`udata`.`start_period_time`,`udata`.`ept`))) AND ((`udata`.`uid` = '1039100792') AND (`udata`.`user_type` = 2))) order by `udata`.`start_period_time` desc limit 0,6"; String psql = ParameterizedOutputVisitorUtils.parameterize(sql, dbType); assertEquals("SELECT `udata`.`id` AS `id`, `udata`.`gmt_create` AS `gmtCreate`, `udata`.`gmt_modified` AS `gmtModified`, `udata`.`uid` AS `userId`, `udata`.`user_nick` AS `userNick`\n" + "\t, `udata`.`user_type` AS `userType`, `udata`.`aps` AS `acPeSe`, `udata`.`rn` AS `rn`, `udata`.`start_period_time` AS `startPeriodTime`, `udata`.`ept` AS `adTm`\n" + "\t, `udata`.`status` AS `status`, `udata`.`charging_period` AS `chargingPeriod`, `udata`.`sn` AS `sn`, `udata`.`cpd` AS `chargingPeriodDesc`, `udata`.`task_total_num` AS `taskTotalNum`\n" + "\t, `udata`.`tcn` AS `taCoNu`, `udata`.`task_type` AS `taskType`, `udata`.`ilbu` AS `isLaBiUs`\n" + "FROM udata `udata`\n" + "WHERE (`udata`.`id` IN (\n" + "\t\tSELECT MAX(`udata`.`id`)\n" + "\t\tFROM udata `udata`\n" + "\t\tWHERE (`udata`.`uid` = ?)\n" + "\t\t\tAND (`udata`.`user_type` = ?)\n" + "\t\t\tAND (`udata`.`start_period_time` <= ?)\n" + "\t\t\tAND (`udata`.`status` = ?)\n" + "\t\t\tAND (`udata`.`charging_period` = ?)\n" + "\t\t\tAND (`udata`.`task_type` = ?)\n" + "\t\t\tAND (`udata`.`task_total_num` <= `udata`.`tcn`)\n" + "\t\tGROUP BY `udata`.`charging_period`, `udata`.`start_period_time`, `udata`.`ept`\n" + "\t)\n" + "\tAND ((`udata`.`uid` = ?)\n" + "\t\tAND (`udata`.`user_type` = ?)))\n" + "ORDER BY `udata`.`start_period_time` DESC\n" + "LIMIT ?, ?", psql); SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType); List<SQLStatement> stmtList = parser.parseStatementList(); StringBuilder out = new StringBuilder(); SQLASTOutputVisitor visitor = SQLUtils.createOutputVisitor(out, JdbcConstants.MYSQL); List<Object> parameters = new ArrayList<Object>(); visitor.setParameterized(true); visitor.setParameterizedMergeInList(true); visitor.setParameters(parameters); visitor.setExportTables(true); /*visitor.setPrettyFormat(false);*/ SQLStatement stmt = stmtList.get(0); stmt.accept(visitor); // System.out.println(parameters); assertEquals(10, parameters.size()); //SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(psql, dbType); // List<SQLStatement> stmtList = parser.parseStatementList(); SQLStatement pstmt = SQLUtils.parseStatements(psql, dbType).get(0); StringBuilder buf = new StringBuilder(); SQLASTOutputVisitor visitor1 = SQLUtils.createOutputVisitor(buf, dbType); visitor1.addTableMapping("udata", "udata_0888"); visitor1.setInputParameters(visitor.getParameters()); pstmt.accept(visitor1); assertEquals("SELECT `udata`.`id` AS `id`, `udata`.`gmt_create` AS `gmtCreate`, `udata`.`gmt_modified` AS `gmtModified`, `udata`.`uid` AS `userId`, `udata`.`user_nick` AS `userNick`\n" + "\t, `udata`.`user_type` AS `userType`, `udata`.`aps` AS `acPeSe`, `udata`.`rn` AS `rn`, `udata`.`start_period_time` AS `startPeriodTime`, `udata`.`ept` AS `adTm`\n" + "\t, `udata`.`status` AS `status`, `udata`.`charging_period` AS `chargingPeriod`, `udata`.`sn` AS `sn`, `udata`.`cpd` AS `chargingPeriodDesc`, `udata`.`task_total_num` AS `taskTotalNum`\n" + "\t, `udata`.`tcn` AS `taCoNu`, `udata`.`task_type` AS `taskType`, `udata`.`ilbu` AS `isLaBiUs`\n" + "FROM udata_0888 `udata`\n" + "WHERE (`udata`.`id` IN (\n" + "\t\tSELECT MAX(`udata`.`id`)\n" + "\t\tFROM udata_0888 `udata`\n" + "\t\tWHERE (`udata`.`uid` = 1039100792)\n" + "\t\t\tAND (`udata`.`user_type` = 2)\n" + "\t\t\tAND (`udata`.`start_period_time` <= '2017-01-01 00:00:00')\n" + "\t\t\tAND (`udata`.`status` = 10)\n" + "\t\t\tAND (`udata`.`charging_period` = 1)\n" + "\t\t\tAND (`udata`.`task_type` = 1)\n" + "\t\t\tAND (`udata`.`task_total_num` <= `udata`.`tcn`)\n" + "\t\tGROUP BY `udata`.`charging_period`, `udata`.`start_period_time`, `udata`.`ept`\n" + "\t)\n" + "\tAND ((`udata`.`uid` = '1039100792')\n" + "\t\tAND (`udata`.`user_type` = 2)))\n" + "ORDER BY `udata`.`start_period_time` DESC\n" + "LIMIT 0, 6", buf.toString()); } }
MySqlParameterizedOutputVisitorTest_30
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/TestJsonSerialize.java
{ "start": 1535, "end": 1994 }
class ____ { @JsonSerialize(typing=JsonSerialize.Typing.STATIC) public ValueInterface getStaticValue() { return new ValueClass(); } @JsonSerialize(typing=JsonSerialize.Typing.DYNAMIC) public ValueInterface getDynamicValue() { return new ValueClass(); } } /** * Test bean that has an invalid {@link JsonSerialize} annotation. */ static
WrapperClassForStaticTyping2
java
apache__rocketmq
proxy/src/main/java/org/apache/rocketmq/proxy/metrics/ProxyMetricsConstant.java
{ "start": 853, "end": 1076 }
class ____ { public static final String GAUGE_PROXY_UP = "rocketmq_proxy_up"; public static final String LABEL_PROXY_MODE = "proxy_mode"; public static final String NODE_TYPE_PROXY = "proxy"; }
ProxyMetricsConstant
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/MultipartWebClientIntegrationTests.java
{ "start": 8117, "end": 8299 }
class ____ { @Bean public MultipartController testController() { return new MultipartController(); } } @RestController @SuppressWarnings("unused") static
TestConfiguration
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/IsInstanceIncompatibleTypeTest.java
{ "start": 1694, "end": 2195 }
class ____ { Optional<String> f(Optional<String> s) { // BUG: Diagnostic contains: String cannot be cast to Integer return s.filter(x -> Integer.class.isInstance(x)); } } """) .doTest(); } @Test public void positiveInstanceOf2() { testHelper .addSourceLines( "Test.java", """ import java.util.Optional; import java.util.HashMap;
Test
java
elastic__elasticsearch
x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/action/SamlValidateAuthnRequestRequestTests.java
{ "start": 581, "end": 1746 }
class ____ extends ESTestCase { public void testSerialization() throws Exception { final SamlValidateAuthnRequestRequest request = new SamlValidateAuthnRequestRequest(); request.setQueryString("?SAMLRequest=x&RelayState=y&SigAlg=z&Signature=sig"); final BytesStreamOutput out = new BytesStreamOutput(); request.writeTo(out); final SamlValidateAuthnRequestRequest request1 = new SamlValidateAuthnRequestRequest(out.bytes().streamInput()); assertThat(request.getQueryString(), equalTo(request1.getQueryString())); final ActionRequestValidationException exception = request1.validate(); assertNull(exception); } public void testValidation() { final SamlValidateAuthnRequestRequest request = new SamlValidateAuthnRequestRequest(); final ActionRequestValidationException exception = request.validate(); assertNotNull(exception); assertThat(exception.validationErrors().size(), equalTo(1)); assertThat(exception.validationErrors().get(0), containsString("Authentication request query string must be provided")); } }
SamlValidateAuthnRequestRequestTests
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/assignability/generics/AssignabilityWithGenericsTest.java
{ "start": 3763, "end": 3816 }
interface ____<K> { K ping(); }
BetaFace
java
apache__camel
components/camel-ai/camel-neo4j/src/generated/java/org/apache/camel/component/neo4j/Neo4jComponentConfigurer.java
{ "start": 732, "end": 8243 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private org.apache.camel.component.neo4j.Neo4jConfiguration getOrCreateConfiguration(Neo4jComponent target) { if (target.getConfiguration() == null) { target.setConfiguration(new org.apache.camel.component.neo4j.Neo4jConfiguration()); } return target.getConfiguration(); } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { Neo4jComponent target = (Neo4jComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "alias": getOrCreateConfiguration(target).setAlias(property(camelContext, java.lang.String.class, value)); return true; case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.neo4j.Neo4jConfiguration.class, value)); return true; case "databaseurl": case "databaseUrl": getOrCreateConfiguration(target).setDatabaseUrl(property(camelContext, java.lang.String.class, value)); return true; case "detachrelationship": case "detachRelationship": getOrCreateConfiguration(target).setDetachRelationship(property(camelContext, boolean.class, value)); return true; case "dimension": getOrCreateConfiguration(target).setDimension(property(camelContext, java.lang.Integer.class, value)); return true; case "driver": getOrCreateConfiguration(target).setDriver(property(camelContext, org.neo4j.driver.Driver.class, value)); return true; case "kerberosauthticket": case "kerberosAuthTicket": getOrCreateConfiguration(target).setKerberosAuthTicket(property(camelContext, java.lang.String.class, value)); return true; case "label": getOrCreateConfiguration(target).setLabel(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "maxresults": case "maxResults": getOrCreateConfiguration(target).setMaxResults(property(camelContext, int.class, value)); return true; case "minscore": case "minScore": getOrCreateConfiguration(target).setMinScore(property(camelContext, double.class, value)); return true; case "password": getOrCreateConfiguration(target).setPassword(property(camelContext, java.lang.String.class, value)); return true; case "query": getOrCreateConfiguration(target).setQuery(property(camelContext, java.lang.String.class, value)); return true; case "realm": getOrCreateConfiguration(target).setRealm(property(camelContext, java.lang.String.class, value)); return true; case "similarityfunction": case "similarityFunction": getOrCreateConfiguration(target).setSimilarityFunction(property(camelContext, org.apache.camel.component.neo4j.Neo4jSimilarityFunction.class, value)); return true; case "token": getOrCreateConfiguration(target).setToken(property(camelContext, java.lang.String.class, value)); return true; case "username": getOrCreateConfiguration(target).setUsername(property(camelContext, java.lang.String.class, value)); return true; case "vectorindexname": case "vectorIndexName": getOrCreateConfiguration(target).setVectorIndexName(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public String[] getAutowiredNames() { return new String[]{"driver"}; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "alias": return java.lang.String.class; case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "configuration": return org.apache.camel.component.neo4j.Neo4jConfiguration.class; case "databaseurl": case "databaseUrl": return java.lang.String.class; case "detachrelationship": case "detachRelationship": return boolean.class; case "dimension": return java.lang.Integer.class; case "driver": return org.neo4j.driver.Driver.class; case "kerberosauthticket": case "kerberosAuthTicket": return java.lang.String.class; case "label": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "maxresults": case "maxResults": return int.class; case "minscore": case "minScore": return double.class; case "password": return java.lang.String.class; case "query": return java.lang.String.class; case "realm": return java.lang.String.class; case "similarityfunction": case "similarityFunction": return org.apache.camel.component.neo4j.Neo4jSimilarityFunction.class; case "token": return java.lang.String.class; case "username": return java.lang.String.class; case "vectorindexname": case "vectorIndexName": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { Neo4jComponent target = (Neo4jComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "alias": return getOrCreateConfiguration(target).getAlias(); case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "configuration": return target.getConfiguration(); case "databaseurl": case "databaseUrl": return getOrCreateConfiguration(target).getDatabaseUrl(); case "detachrelationship": case "detachRelationship": return getOrCreateConfiguration(target).isDetachRelationship(); case "dimension": return getOrCreateConfiguration(target).getDimension(); case "driver": return getOrCreateConfiguration(target).getDriver(); case "kerberosauthticket": case "kerberosAuthTicket": return getOrCreateConfiguration(target).getKerberosAuthTicket(); case "label": return getOrCreateConfiguration(target).getLabel(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "maxresults": case "maxResults": return getOrCreateConfiguration(target).getMaxResults(); case "minscore": case "minScore": return getOrCreateConfiguration(target).getMinScore(); case "password": return getOrCreateConfiguration(target).getPassword(); case "query": return getOrCreateConfiguration(target).getQuery(); case "realm": return getOrCreateConfiguration(target).getRealm(); case "similarityfunction": case "similarityFunction": return getOrCreateConfiguration(target).getSimilarityFunction(); case "token": return getOrCreateConfiguration(target).getToken(); case "username": return getOrCreateConfiguration(target).getUsername(); case "vectorindexname": case "vectorIndexName": return getOrCreateConfiguration(target).getVectorIndexName(); default: return null; } } }
Neo4jComponentConfigurer
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/IdJpaAnnotation.java
{ "start": 455, "end": 1026 }
class ____ implements Id { /** * Used in creating dynamic annotation instances (e.g. from XML) */ public IdJpaAnnotation(ModelsContext modelContext) { } /** * Used in creating annotation instances from JDK variant */ public IdJpaAnnotation(Id annotation, ModelsContext modelContext) { } /** * Used in creating annotation instances from Jandex variant */ public IdJpaAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) { } @Override public Class<? extends Annotation> annotationType() { return Id.class; } }
IdJpaAnnotation
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/http/impl/http2/multiplex/Http2MultiplexClientConnection.java
{ "start": 1347, "end": 7736 }
class ____ extends Http2MultiplexConnection<Http2ClientStream> implements HttpClientConnection, Http2ClientConnection { private final boolean decompressionSupported; private final ClientMetrics<?, ?, ?> clientMetrics; private final HostAndPort authority; private Promise<HttpClientConnection> completion; private long concurrency; private Handler<Long> concurrencyChangeHandler; private Handler<Void> evictionHandler; private final long maxConcurrency; private final long keepAliveTimeoutMillis; private boolean evicted; private final long lifetimeEvictionTimestampMillis; private long expirationTimestampMillis; public Http2MultiplexClientConnection(Http2MultiplexHandler handler, ChannelHandlerContext chctx, ContextInternal context, ClientMetrics<?, ?, ?> clientMetrics, HttpClientMetrics<?, ?, ?> transportMetrics, HostAndPort authority, int maxConcurrency, long keepAliveTimeoutMillis, long maxLifetimeMillis, boolean decompressionSupported, Promise<HttpClientConnection> completion) { super(handler, transportMetrics, chctx, context); this.authority = authority; this.completion = completion; this.clientMetrics = clientMetrics; this.concurrencyChangeHandler = DEFAULT_CONCURRENCY_CHANGE_HANDLER; this.maxConcurrency = maxConcurrency < 0 ? Long.MAX_VALUE : maxConcurrency; this.keepAliveTimeoutMillis = keepAliveTimeoutMillis; this.lifetimeEvictionTimestampMillis = maxLifetimeMillis > 0 ? System.currentTimeMillis() + maxLifetimeMillis : Long.MAX_VALUE; this.evicted = false; this.decompressionSupported = decompressionSupported; } @Override public MultiMap newHttpRequestHeaders() { return new HttpResponseHeaders(new DefaultHttp2Headers()); } @Override boolean isServer() { return false; } ClientMetrics<?, ?, ?> clientMetrics() { return clientMetrics; } void refresh() { expirationTimestampMillis = keepAliveTimeoutMillis > 0 ? System.currentTimeMillis() + keepAliveTimeoutMillis : Long.MAX_VALUE; } private long actualConcurrency(Http2Settings settings) { return Math.min(settings.getMaxConcurrentStreams(), maxConcurrency); } void onInitialSettingsSent() { } @Override void onInitialSettingsReceived(Http2Settings settings) { concurrency = actualConcurrency(settings); Promise<HttpClientConnection> c = completion; completion = null; c.complete(this); } @Override void onSettings(Http2Settings settings) { long newConcurrency = actualConcurrency(settings); if (newConcurrency != concurrency) { Handler<Long> handler = concurrencyChangeHandler; if (handler != null) { context.emit(newConcurrency, handler); } } concurrency = newConcurrency; super.onSettings(settings); } @Override void receiveHeaders(ChannelHandlerContext chctx, Http2FrameStream frameStream, Http2Headers headers, boolean ended) { int streamId = frameStream.id(); Http2ClientStream stream = stream(streamId); HttpResponseHeaders headersMap = new HttpResponseHeaders(headers); if (!stream.isHeadersReceived()) { if (!headersMap.validate()) { chctx.writeAndFlush(new DefaultHttp2ResetFrame(Http2Error.PROTOCOL_ERROR.code())); } else { headersMap.sanitize(); stream.onHeaders(headersMap); if (ended) { stream.onTrailers(); } } } else { stream.onTrailers(headersMap); } } @Override public long activeStreams() { Http2FrameCodec frameCodec = chctx.pipeline().get(Http2FrameCodec.class); return frameCodec.connection().numActiveStreams(); } @Override public long concurrency() { return concurrency; } @Override public HostAndPort authority() { return authority; } @Override public HttpClientConnection evictionHandler(Handler<Void> handler) { this.evictionHandler = handler; return this; } @Override public HttpClientConnection invalidMessageHandler(Handler<Object> handler) { return this; } @Override public HttpClientConnection concurrencyChangeHandler(Handler<Long> handler) { concurrencyChangeHandler = handler; return this; } @Override public Future<HttpClientStream> createStream(ContextInternal context) { Http2ClientStream stream = Http2ClientStream.create(this, context, null, decompressionSupported, transportMetrics, clientMetrics); return context.succeededFuture(stream.unwrap()); } @Override public boolean isValid() { long now = System.currentTimeMillis(); return now <= expirationTimestampMillis && now <= lifetimeEvictionTimestampMillis; } @Override public long lastResponseReceivedTimestamp() { throw new UnsupportedOperationException(); } @Override public void createStream(Http2ClientStream stream) throws Exception { handler.createClientStream(stream); } @Override public void writeHeaders(int streamId, Headers<CharSequence, CharSequence, ?> headers, StreamPriority priority, boolean end, boolean checkFlush, Promise<Void> promise) { writeStreamFrame(streamId, new DefaultHttp2HeadersFrame((Http2Headers) headers, end), promise); } @Override public void writePriorityFrame(int streamId, StreamPriority priority, Promise<Void> promise) { throw new UnsupportedOperationException(); } @Override void onGoAway(long errorCode, int lastStreamId, Buffer debugData) { if (!evicted) { evicted = true; Handler<Void> handler = evictionHandler; if (handler != null) { context.emit(handler); } } super.onGoAway(errorCode, lastStreamId, debugData); } @Override void onIdle() { if (numberOfChannels() > 0) { super.onIdle(); } } @Override void onClose() { super.onClose(); Promise<HttpClientConnection> promise = completion; if (promise != null) { completion = null; promise.fail(ConnectionBase.CLOSED_EXCEPTION); } } }
Http2MultiplexClientConnection
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableGroupJoin.java
{ "start": 2776, "end": 3090 }
interface ____ { void innerError(Throwable ex); void innerComplete(LeftRightSubscriber sender); void innerValue(boolean isLeft, Object o); void innerClose(boolean isLeft, LeftRightEndSubscriber index); void innerCloseError(Throwable ex); } static final
JoinSupport
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/RolesAllowedService.java
{ "start": 375, "end": 1108 }
class ____ { public static final String SERVICE_HELLO = "Hello from Service!"; public static final String SERVICE_BYE = "Bye from Service!"; public static final List<String> EVENT_BUS_MESSAGES = new CopyOnWriteArrayList<>(); @RolesAllowed("admin") public String hello() { return SERVICE_HELLO; } @PermitAll public String bye() { return SERVICE_BYE; } @PermitAll @ActivateRequestContext void receivePermitAllMessage(String m) { EVENT_BUS_MESSAGES.add("permit all " + m); } @RolesAllowed("admin") @ActivateRequestContext void receiveRolesAllowedMessage(String m) { EVENT_BUS_MESSAGES.add("roles allowed " + m); } }
RolesAllowedService
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/JoinedInheritanceForceDiscriminatorTest.java
{ "start": 4838, "end": 5240 }
class ____ { @Id protected Long id; protected String name; public CommonBase() { } public CommonBase(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public String getName() { return name; } } @Entity( name = "ElementEntity" ) @DiscriminatorValue( "element" ) @Table( name = "element_table" ) public static
CommonBase
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/bytearray/ByteArrayAssert_usingComparator_Test.java
{ "start": 1162, "end": 1845 }
class ____ extends ByteArrayAssertBaseTest { private Comparator<byte[]> comparator = alwaysEqual(); private ByteArrays arraysBefore; @BeforeEach void before() { arraysBefore = getArrays(assertions); } @Override protected ByteArrayAssert invoke_api_method() { // in that test, the comparator type is not important, we only check that we correctly switch of comparator return assertions.usingComparator(comparator); } @Override protected void verify_internal_effects() { assertThat(getObjects(assertions).getComparator()).isSameAs(comparator); assertThat(getArrays(assertions)).isSameAs(arraysBefore); } }
ByteArrayAssert_usingComparator_Test
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/annotatewith/AnnotateStreamMappingMethodMapper.java
{ "start": 336, "end": 503 }
interface ____ { @AnnotateWith(CustomMethodOnlyAnnotation.class) Stream<String> toStringStream(Stream<Integer> integerStream); }
AnnotateStreamMappingMethodMapper
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/AutoValueBoxedValues.java
{ "start": 7753, "end": 8826 }
class ____ also fixed. */ private static void maybeFixGetterInBuilder( MethodTree methodTree, VisitorState state, List<Getter> getters) { Optional<Getter> fixedGetter = getters.stream() .filter( getter -> !getter.fix().isEmpty() && getter.method().getName().contentEquals(methodTree.getName().toString()) && isSameType( getType(getter.method().getReturnType()), getType(methodTree.getReturnType()), state)) .findAny(); if (fixedGetter.isPresent()) { Type type = getType(methodTree.getReturnType()); suggestRemoveUnnecessaryBoxing( methodTree.getReturnType(), state, type, fixedGetter.get().fix()); } } /** * Identifies and fixes the factory method in the {@link AutoValue} class. * * <p>This method only handles the case of "trivial" factory methods, i.e. methods that have one * argument for each getter in the
was
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockReconstructionWork.java
{ "start": 1301, "end": 4266 }
class ____ { public static final Logger LOG = LoggerFactory.getLogger(BlockReconstructionWork.class); private final BlockInfo block; private final String srcPath; private final long blockSize; private final byte storagePolicyID; /** * An erasure coding reconstruction task has multiple source nodes. * A replication task only has 1 source node, stored on top of the array */ private final DatanodeDescriptor[] srcNodes; /** Nodes containing the block; avoid them in choosing new targets */ private final List<DatanodeDescriptor> containingNodes; /** Required by {@link BlockPlacementPolicy#chooseTarget} */ private final List<DatanodeStorageInfo> liveReplicaStorages; private final int additionalReplRequired; private DatanodeStorageInfo[] targets; private final int priority; private boolean notEnoughRack = false; public BlockReconstructionWork(BlockInfo block, BlockCollection bc, DatanodeDescriptor[] srcNodes, List<DatanodeDescriptor> containingNodes, List<DatanodeStorageInfo> liveReplicaStorages, int additionalReplRequired, int priority) { this.block = block; this.srcPath = bc.getName(); this.blockSize = block.getNumBytes(); this.storagePolicyID = bc.getStoragePolicyID(); this.srcNodes = srcNodes; this.containingNodes = containingNodes; this.liveReplicaStorages = liveReplicaStorages; this.additionalReplRequired = additionalReplRequired; this.priority = priority; this.targets = null; } DatanodeStorageInfo[] getTargets() { return targets; } void resetTargets() { this.targets = null; } void setTargets(DatanodeStorageInfo[] targets) { this.targets = targets; } List<DatanodeDescriptor> getContainingNodes() { return Collections.unmodifiableList(containingNodes); } public int getPriority() { return priority; } public BlockInfo getBlock() { return block; } public DatanodeDescriptor[] getSrcNodes() { return srcNodes; } public String getSrcPath() { return srcPath; } public long getBlockSize() { return blockSize; } public byte getStoragePolicyID() { return storagePolicyID; } List<DatanodeStorageInfo> getLiveReplicaStorages() { return liveReplicaStorages; } public int getAdditionalReplRequired() { return additionalReplRequired; } /** * Mark that the reconstruction work is to replicate internal block to a new * rack. */ void setNotEnoughRack() { notEnoughRack = true; } boolean hasNotEnoughRack() { return notEnoughRack; } abstract void chooseTargets(BlockPlacementPolicy blockplacement, BlockStoragePolicySuite storagePolicySuite, Set<Node> excludedNodes); /** * Add reconstruction task into a source datanode. * * @param numberReplicas replica details */ abstract boolean addTaskToDatanode(NumberReplicas numberReplicas); }
BlockReconstructionWork
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/ibmwatsonx/embeddings/IbmWatsonxEmbeddingsServiceSettings.java
{ "start": 2495, "end": 9858 }
class ____ extends FilteredXContentObject implements ServiceSettings, IbmWatsonxRateLimitServiceSettings { public static final String NAME = "ibmwatsonx_embeddings_service_settings"; /** * Rate limits are defined at * <a href="https://www.ibm.com/docs/en/watsonx/saas?topic=learning-watson-machine-plans">Watson Machine Learning plans</a>. * For the Lite plan, the limit is 120 requests per minute. */ private static final RateLimitSettings DEFAULT_RATE_LIMIT_SETTINGS = new RateLimitSettings(120); public static IbmWatsonxEmbeddingsServiceSettings fromMap(Map<String, Object> map, ConfigurationParseContext context) { ValidationException validationException = new ValidationException(); String model = extractRequiredString(map, MODEL_ID, ModelConfigurations.SERVICE_SETTINGS, validationException); String projectId = extractRequiredString(map, PROJECT_ID, ModelConfigurations.SERVICE_SETTINGS, validationException); var url = extractUri(map, URL, validationException); String apiVersion = extractRequiredString(map, API_VERSION, ModelConfigurations.SERVICE_SETTINGS, validationException); Integer maxInputTokens = extractOptionalPositiveInteger( map, MAX_INPUT_TOKENS, ModelConfigurations.SERVICE_SETTINGS, validationException ); SimilarityMeasure similarityMeasure = extractSimilarity(map, ModelConfigurations.SERVICE_SETTINGS, validationException); Integer dims = extractOptionalPositiveInteger(map, DIMENSIONS, ModelConfigurations.SERVICE_SETTINGS, validationException); RateLimitSettings rateLimitSettings = RateLimitSettings.of( map, DEFAULT_RATE_LIMIT_SETTINGS, validationException, IbmWatsonxService.NAME, context ); if (validationException.validationErrors().isEmpty() == false) { throw validationException; } return new IbmWatsonxEmbeddingsServiceSettings( model, projectId, url, apiVersion, maxInputTokens, dims, similarityMeasure, rateLimitSettings ); } public static URI extractUri(Map<String, Object> map, String fieldName, ValidationException validationException) { String parsedUrl = extractRequiredString(map, fieldName, ModelConfigurations.SERVICE_SETTINGS, validationException); return convertToUri(parsedUrl, fieldName, ModelConfigurations.SERVICE_SETTINGS, validationException); } private final String modelId; private final String projectId; private final URI url; private final String apiVersion; private final RateLimitSettings rateLimitSettings; private final Integer dims; private final Integer maxInputTokens; private final SimilarityMeasure similarity; public IbmWatsonxEmbeddingsServiceSettings( String modelId, String projectId, URI uri, String apiVersion, @Nullable Integer maxInputTokens, @Nullable Integer dims, @Nullable SimilarityMeasure similarity, @Nullable RateLimitSettings rateLimitSettings ) { this.modelId = modelId; this.projectId = projectId; this.url = uri; this.apiVersion = apiVersion; this.maxInputTokens = maxInputTokens; this.dims = dims; this.similarity = similarity; this.rateLimitSettings = Objects.requireNonNullElse(rateLimitSettings, DEFAULT_RATE_LIMIT_SETTINGS); } public IbmWatsonxEmbeddingsServiceSettings(StreamInput in) throws IOException { this.modelId = in.readString(); this.projectId = in.readString(); this.url = createUri(in.readString()); this.apiVersion = in.readString(); this.maxInputTokens = in.readOptionalVInt(); this.dims = in.readOptionalVInt(); this.similarity = in.readOptionalEnum(SimilarityMeasure.class); this.rateLimitSettings = new RateLimitSettings(in); } @Override public String modelId() { return modelId; } public String projectId() { return projectId; } public URI url() { return url; } public String apiVersion() { return apiVersion; } @Override public RateLimitSettings rateLimitSettings() { return rateLimitSettings; } public Integer maxInputTokens() { return maxInputTokens; } @Override public Integer dimensions() { return dims; } @Override public SimilarityMeasure similarity() { return similarity; } @Override public DenseVectorFieldMapper.ElementType elementType() { return DenseVectorFieldMapper.ElementType.FLOAT; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); toXContentFragmentOfExposedFields(builder, params); builder.endObject(); return builder; } @Override public String getWriteableName() { return NAME; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersions.V_8_16_0; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(modelId); out.writeString(projectId); out.writeString(url.toString()); out.writeString(apiVersion); out.writeOptionalVInt(maxInputTokens); out.writeOptionalVInt(dims); out.writeOptionalEnum(similarity); rateLimitSettings.writeTo(out); } @Override protected XContentBuilder toXContentFragmentOfExposedFields(XContentBuilder builder, Params params) throws IOException { builder.field(MODEL_ID, modelId); builder.field(PROJECT_ID, projectId); builder.field(URL, url.toString()); builder.field(API_VERSION, apiVersion); if (maxInputTokens != null) { builder.field(MAX_INPUT_TOKENS, maxInputTokens); } if (dims != null) { builder.field(DIMENSIONS, dims); } if (similarity != null) { builder.field(SIMILARITY, similarity); } rateLimitSettings.toXContent(builder, params); return builder; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; IbmWatsonxEmbeddingsServiceSettings that = (IbmWatsonxEmbeddingsServiceSettings) object; return Objects.equals(modelId, that.modelId) && Objects.equals(projectId, that.projectId) && Objects.equals(url, that.url) && Objects.equals(apiVersion, that.apiVersion) && Objects.equals(rateLimitSettings, that.rateLimitSettings) && Objects.equals(dims, that.dims) && Objects.equals(maxInputTokens, that.maxInputTokens) && similarity == that.similarity; } @Override public int hashCode() { return Objects.hash(modelId, projectId, url, apiVersion, rateLimitSettings, dims, maxInputTokens, similarity); } }
IbmWatsonxEmbeddingsServiceSettings
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/io/support/ResourcePatternUtils.java
{ "start": 829, "end": 1156 }
class ____ determining whether a given URL is a resource * location that can be loaded via a {@link ResourcePatternResolver}. * * <p>Callers will usually assume that a location is a relative path * if the {@link #isUrl(String)} method returns {@code false}. * * @author Juergen Hoeller * @since 1.2.3 */ public abstract
for
java
grpc__grpc-java
core/src/main/java/io/grpc/internal/MigratingThreadDeframer.java
{ "start": 7829, "end": 8092 }
class ____ implements Op { @Override public void run(boolean isDeframerOnTransportThread) { deframer.closeWhenComplete(); } } runWhereAppropriate(new CloseWhenCompleteOp()); } @Override public void close() {
CloseWhenCompleteOp
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerTests.java
{ "start": 28152, "end": 28598 }
class ____ { static ObjectPostProcessor<Object> objectPostProcessor; @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .sessionManagement((management) -> management .maximumSessions(1)); return http.build(); // @formatter:on } @Bean static ObjectPostProcessor<Object> objectPostProcessor() { return objectPostProcessor; } } static
ObjectPostProcessorConfig
java
quarkusio__quarkus
integration-tests/rest-client-reactive/src/main/java/io/quarkus/it/rest/client/main/ParamConverter.java
{ "start": 203, "end": 1631 }
class ____ implements ParamConverterProvider { @SuppressWarnings("unchecked") @Override public <T> jakarta.ws.rs.ext.ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { if (genericType == null || !genericType.equals(Param.class)) { throw new RuntimeException("Wrong generic type in ParamConverter!"); } if (annotations == null || annotations.length != 1 || !(annotations[0] instanceof QueryParam)) { throw new RuntimeException("Wrong annotations in ParamConverter!"); } if (rawType == Param.class) { return (jakarta.ws.rs.ext.ParamConverter<T>) new jakarta.ws.rs.ext.ParamConverter<Param>() { @Override public Param fromString(String value) { return null; } @Override public String toString(Param value) { if (value == null) { return null; } switch (value) { case FIRST: return "1"; case SECOND: return "2"; default: return "unexpected"; } } }; } return null; } }
ParamConverter
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/iterative/concurrent/SolutionSetUpdateBarrierBroker.java
{ "start": 1131, "end": 1526 }
class ____ extends Broker<SolutionSetUpdateBarrier> { private static final SolutionSetUpdateBarrierBroker INSTANCE = new SolutionSetUpdateBarrierBroker(); private SolutionSetUpdateBarrierBroker() {} /** * @return singleton instance */ public static Broker<SolutionSetUpdateBarrier> instance() { return INSTANCE; } }
SolutionSetUpdateBarrierBroker
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/engine/prefill/BitmapPreFillRunner.java
{ "start": 1475, "end": 5911 }
class ____ implements Runnable { @VisibleForTesting static final String TAG = "PreFillRunner"; private static final Clock DEFAULT_CLOCK = new Clock(); /** * The maximum number of millis we can run before posting. Set to match and detect the duration of * non concurrent GCs. */ static final long MAX_DURATION_MS = 32; /** * The amount of time in ms we wait before continuing to allocate after the first GC is detected. */ static final long INITIAL_BACKOFF_MS = 40; /** The amount by which the current backoff time is multiplied each time we detect a GC. */ static final int BACKOFF_RATIO = 4; /** The maximum amount of time in ms we wait before continuing to allocate. */ static final long MAX_BACKOFF_MS = TimeUnit.SECONDS.toMillis(1); private final BitmapPool bitmapPool; private final MemoryCache memoryCache; private final PreFillQueue toPrefill; private final Clock clock; private final Set<PreFillType> seenTypes = new HashSet<>(); private final Handler handler; private long currentDelay = INITIAL_BACKOFF_MS; private boolean isCancelled; // Public API. @SuppressWarnings("WeakerAccess") public BitmapPreFillRunner( BitmapPool bitmapPool, MemoryCache memoryCache, PreFillQueue allocationOrder) { this( bitmapPool, memoryCache, allocationOrder, DEFAULT_CLOCK, new Handler(Looper.getMainLooper())); } @VisibleForTesting BitmapPreFillRunner( BitmapPool bitmapPool, MemoryCache memoryCache, PreFillQueue allocationOrder, Clock clock, Handler handler) { this.bitmapPool = bitmapPool; this.memoryCache = memoryCache; this.toPrefill = allocationOrder; this.clock = clock; this.handler = handler; } public void cancel() { isCancelled = true; } /** * Attempts to allocate {@link android.graphics.Bitmap}s and returns {@code true} if there are * more {@link android.graphics.Bitmap}s to allocate and {@code false} otherwise. */ @VisibleForTesting boolean allocate() { long start = clock.now(); while (!toPrefill.isEmpty() && !isGcDetected(start)) { PreFillType toAllocate = toPrefill.remove(); final Bitmap bitmap; if (!seenTypes.contains(toAllocate)) { seenTypes.add(toAllocate); bitmap = bitmapPool.getDirty( toAllocate.getWidth(), toAllocate.getHeight(), toAllocate.getConfig()); } else { bitmap = Bitmap.createBitmap( toAllocate.getWidth(), toAllocate.getHeight(), toAllocate.getConfig()); } // Order matters here! If the Bitmap is too large or the BitmapPool is too full, it may be // recycled after the call to bitmapPool#put below. int bitmapSize = Util.getBitmapByteSize(bitmap); // Don't over fill the memory cache to avoid evicting useful resources, but make sure it's // not empty so that we use all available space. if (getFreeMemoryCacheBytes() >= bitmapSize) { // We could probably make UniqueKey just always return false from equals, // but the allocation of the Key is not nearly as expensive as the allocation of the Bitmap, // so it's probably not worth it. @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Key uniqueKey = new UniqueKey(); memoryCache.put(uniqueKey, BitmapResource.obtain(bitmap, bitmapPool)); } else { bitmapPool.put(bitmap); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d( TAG, "allocated [" + toAllocate.getWidth() + "x" + toAllocate.getHeight() + "] " + toAllocate.getConfig() + " size: " + bitmapSize); } } return !isCancelled && !toPrefill.isEmpty(); } private boolean isGcDetected(long startTimeMs) { return clock.now() - startTimeMs >= MAX_DURATION_MS; } private long getFreeMemoryCacheBytes() { return memoryCache.getMaxSize() - memoryCache.getCurrentSize(); } @Override public void run() { if (allocate()) { handler.postDelayed(this, getNextDelay()); } } private long getNextDelay() { long result = currentDelay; currentDelay = Math.min(currentDelay * BACKOFF_RATIO, MAX_BACKOFF_MS); return result; } private static final
BitmapPreFillRunner
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/bcextensions/InvokerInfoImpl.java
{ "start": 116, "end": 356 }
class ____ implements InvokerInfo { final io.quarkus.arc.processor.InvokerInfo arcInvokerInfo; InvokerInfoImpl(io.quarkus.arc.processor.InvokerInfo arcInvokerInfo) { this.arcInvokerInfo = arcInvokerInfo; } }
InvokerInfoImpl
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/show/MySqlShowTest_15_outlines.java
{ "start": 1036, "end": 2389 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "SHOW OUTLINES"; SQLStatement stmt = SQLUtils.parseStatements(sql, DbType.mysql).get(0); String result = SQLUtils.toMySqlString(stmt); assertEquals("SHOW OUTLINES", result); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(DbType.mysql); stmt.accept(visitor); assertEquals(0, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); } public void test_1() throws Exception { String sql = "/*TDDL:SCAN*/SHOW OUTLINES"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.TDDLHint); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); String result = SQLUtils.toMySqlString(stmt); assertEquals("SHOW OUTLINES", result); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(DbType.mysql); stmt.accept(visitor); assertTrue(statementList.size() == 1); assertEquals(0, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); } }
MySqlShowTest_15_outlines
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/snowflake/SnowflakeLexer.java
{ "start": 188, "end": 598 }
class ____ extends Lexer { public SnowflakeLexer(String input, SQLParserFeature... features) { super(input); dbType = DbType.snowflake; this.skipComment = true; this.keepComments = true; this.features |= SQLParserFeature.SupportUnicodeCodePoint.mask; for (SQLParserFeature feature : features) { config(feature, true); } } }
SnowflakeLexer
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/HandlerInstantiationTest.java
{ "start": 4747, "end": 8319 }
class ____ extends HandlerInstantiator { private final String _prefix; public MyInstantiator(String p) { _prefix = p; } @Override public ValueDeserializer<?> deserializerInstance(DeserializationConfig config, Annotated annotated, Class<?> deserClass) { if (deserClass == MyBeanDeserializer.class) { return new MyBeanDeserializer(_prefix); } return null; } @Override public KeyDeserializer keyDeserializerInstance(DeserializationConfig config, Annotated annotated, Class<?> keyDeserClass) { if (keyDeserClass == MyKeyDeserializer.class) { return new MyKeyDeserializer(); } return null; } @Override public ValueSerializer<?> serializerInstance(SerializationConfig config, Annotated annotated, Class<?> serClass) { if (serClass == MyBeanSerializer.class) { return new MyBeanSerializer(_prefix); } return null; } @Override public TypeIdResolver typeIdResolverInstance(MapperConfig<?> config, Annotated annotated, Class<?> resolverClass) { if (resolverClass == TestCustomIdResolver.class) { return new TestCustomIdResolver("!!!"); } return null; } @Override public TypeResolverBuilder<?> typeResolverBuilderInstance(MapperConfig<?> config, Annotated annotated, Class<?> builderClass) { return null; } } /* /********************************************************************** /* Unit tests /********************************************************************** */ @Test public void testDeserializer() throws Exception { JsonMapper mapper = JsonMapper.builder() .handlerInstantiator(new MyInstantiator("abc:")) .build(); MyBean result = mapper.readValue(q("123"), MyBean.class); assertEquals("abc:123", result.value); } @Test public void testKeyDeserializer() throws Exception { JsonMapper mapper = JsonMapper.builder() .handlerInstantiator(new MyInstantiator("abc:")) .build(); MyMap map = mapper.readValue("{\"a\":\"b\"}", MyMap.class); // easiest to test by just serializing... assertEquals("{\"KEY\":\"b\"}", mapper.writeValueAsString(map)); } @Test public void testSerializer() throws Exception { JsonMapper mapper = JsonMapper.builder() .handlerInstantiator(new MyInstantiator("xyz:")) .build(); assertEquals(q("xyz:456"), mapper.writeValueAsString(new MyBean("456"))); } @Test public void testTypeIdResolver() throws Exception { JsonMapper mapper = JsonMapper.builder() .handlerInstantiator(new MyInstantiator("foobar")) .build(); String json = mapper.writeValueAsString(new TypeIdBeanWrapper(new TypeIdBean(123))); // should now use our custom id scheme: assertEquals("{\"bean\":[\"!!!\",{\"x\":123}]}", json); // and bring it back too: TypeIdBeanWrapper result = mapper.readValue(json, TypeIdBeanWrapper.class); TypeIdBean bean = result.bean; assertEquals(123, bean.x); } }
MyInstantiator
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetomany/merge/MergeOrphanRemovalTest.java
{ "start": 871, "end": 4082 }
class ____ { private static final Long ID_PARENT_WITHOUT_CHILDREN = 1L; private static final Long ID_PARENT_WITH_CHILDREN = 2L; @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { Parent parent = new Parent( ID_PARENT_WITHOUT_CHILDREN, "old name" ); session.persist( parent ); Parent parent2 = new Parent( ID_PARENT_WITH_CHILDREN, "old name" ); Child child = new Child( 2l, "Child" ); parent2.addChild( child ); session.persist( child ); session.persist( parent2 ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testMergeParentWihoutChildren(SessionFactoryScope scope) { scope.inTransaction( session -> { Parent parent = new Parent( ID_PARENT_WITHOUT_CHILDREN, "new name" ); Parent merged = session.merge( parent ); assertThat( merged.getName() ).isEqualTo( "new name" ); } ); } @Test public void testMergeParentWithChildren(SessionFactoryScope scope) { scope.inTransaction( session -> { Parent parent = new Parent( ID_PARENT_WITH_CHILDREN, "new name" ); Child child = new Child( 2l, "Child" ); parent.addChild( child ); Parent merged = session.merge( parent ); assertThat( merged.getName() ).isEqualTo( "new name" ); } ); scope.inTransaction( session -> { Parent parent = session.get( Parent.class, ID_PARENT_WITH_CHILDREN ); assertThat( parent.getChildren().size() ).isEqualTo( 1 ); } ); } @Test public void testMergeParentWithChildren2(SessionFactoryScope scope) { scope.inTransaction( session -> { Parent parent = new Parent( ID_PARENT_WITH_CHILDREN, "new name" ); Parent merged = session.merge( parent ); } ); scope.inTransaction( session -> { Parent parent = session.get( Parent.class, ID_PARENT_WITH_CHILDREN ); assertThat( parent.getName() ).isEqualTo( "new name" ); assertThat( parent.getChildren().size() ).isEqualTo( 0 ); List<Child> children = session.createQuery( "Select c from Child c", Child.class ).list(); assertThat( children.size() ).isEqualTo( 0 ); } ); } @Test public void testMergeParentWithChildren3(SessionFactoryScope scope) { scope.inTransaction( session -> { Parent parent = new Parent( ID_PARENT_WITH_CHILDREN, "new name" ); Child child = new Child( 3l, "Child2" ); parent.addChild( child ); session.persist( child ); Parent merged = session.merge( parent ); } ); scope.inTransaction( session -> { Parent parent = session.get( Parent.class, ID_PARENT_WITH_CHILDREN ); assertThat( parent.getName() ).isEqualTo( "new name" ); assertThat( parent.getChildren().size() ).isEqualTo( 1 ); assertThat( parent.getChildren().get( 0 ).getName() ).isEqualTo( "Child2" ); List<Child> children = session.createQuery( "Select c from Child c", Child.class ).list(); assertThat( children.size() ).isEqualTo( 1 ); assertThat( children.get( 0 ).getName() ).isEqualTo( "Child2" ); } ); } @Entity(name = "Parent") public static
MergeOrphanRemovalTest
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronAndSizeLookupTest.java
{ "start": 1618, "end": 3348 }
class ____ { private static final String CONFIG = "log4j-rolling-cron-and-size-lookup.xml"; private static final String DIR = "target/rolling-cron-size-lookup"; public static LoggerContextRule loggerContextRule = LoggerContextRule.createShutdownTimeoutLoggerContextRule(CONFIG); @Rule public RuleChain chain = loggerContextRule.withCleanFoldersRule(DIR); private Logger logger; @Before public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderCronAndSizeLookupTest.class.getName()); } @Test public void testAppender() throws Exception { final Random rand = new Random(); // Loop for 500 times with a 5ms wait guarantees at least 2 time based rollovers. for (int j = 0; j < 500; ++j) { for (int i = 0; i < 10; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(5); } Thread.sleep(50); final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); Arrays.sort(files); assertNotNull(files); assertThat(files, hasItemInArray(that(hasName(that(endsWith(".log")))))); final int found = 0; final int fileCounter = 0; String previous = ""; for (final File file : files) { final String actual = file.getName(); if (previous.isEmpty()) { previous = actual; } else { assertNotSame("File names snould not be equal", previous, actual); } } } }
RollingAppenderCronAndSizeLookupTest
java
spring-projects__spring-framework
spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/JCacheOperation.java
{ "start": 1310, "end": 1901 }
interface ____<A extends Annotation> extends BasicOperation, CacheMethodDetails<A> { /** * Return the {@link CacheResolver} instance to use to resolve the cache * to use for this operation. */ CacheResolver getCacheResolver(); /** * Return the {@link CacheInvocationParameter} instances based on the * specified method arguments. * <p>The method arguments must match the signature of the related method invocation * @param values the parameters value for a particular invocation */ CacheInvocationParameter[] getAllParameters(@Nullable Object... values); }
JCacheOperation
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/CascadeTest.java
{ "start": 848, "end": 3433 }
class ____ { @Test public void testPersist(SessionFactoryScope scope) { Tooth leftTooth = new Tooth(); scope.inTransaction( session -> { Tooth tooth = new Tooth(); tooth.leftNeighbour = leftTooth; session.persist( tooth ); } ); scope.inTransaction( session -> { Tooth tooth = ( session.get( Tooth.class, leftTooth.id ) ); assertNotNull( tooth ); } ); } @Test public void testMerge(SessionFactoryScope scope) { Tooth t = new Tooth(); Tooth rightTooth = new Tooth(); scope.inTransaction( session -> { t.type = "canine"; t.rightNeighbour = rightTooth; rightTooth.type = "incisive"; session.persist( rightTooth ); session.persist( t ); } ); Tooth tooth = scope.fromTransaction( session -> { Tooth result = session.get( Tooth.class, t.id ); assertEquals( "incisive", t.rightNeighbour.type ); return result; } ); scope.inTransaction( session -> { tooth.rightNeighbour.type = "premolars"; session.merge( tooth ); } ); scope.inTransaction( session -> { Tooth result = session.get( Tooth.class, rightTooth.id ); assertEquals( "premolars", result.type ); } ); } @Test public void testRemove(SessionFactoryScope scope) { Tooth tooth = new Tooth(); scope.inTransaction( session -> { Mouth mouth = new Mouth(); session.persist( mouth ); session.persist( tooth ); tooth.mouth = mouth; mouth.teeth = new ArrayList<>(); mouth.teeth.add( tooth ); } ); scope.inTransaction( session -> { Tooth t = session.get( Tooth.class, tooth.id ); assertNotNull( t ); session.remove( t.mouth ); } ); scope.inTransaction( session -> { Tooth t = session.get( Tooth.class, tooth.id ); assertNull( t ); } ); } @Test public void testDetach(SessionFactoryScope scope) { Mouth mouth = new Mouth(); scope.inTransaction( session -> { Tooth tooth = new Tooth(); session.persist( mouth ); session.persist( tooth ); tooth.mouth = mouth; mouth.teeth = new ArrayList<>(); mouth.teeth.add( tooth ); } ); scope.inTransaction( session -> { Mouth m = session.get( Mouth.class, mouth.id ); assertNotNull( m ); assertEquals( 1, m.teeth.size() ); Tooth tooth = m.teeth.iterator().next(); session.evict( m ); assertFalse( session.contains( tooth ) ); } ); scope.inTransaction( session -> session.remove( session.get( Mouth.class, mouth.id ) ) ); } }
CascadeTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DoNotMockCheckerTest.java
{ "start": 3208, "end": 3593 }
class ____", " implements MetaDoNotMockInterface {} ", "}"); @Test public void matchesMockitoDotMock_doNotMock() { testHelper .addSourceLines( "lib/Lib.java", "package lib;", "import org.mockito.Mockito;", "import lib.DoNotMockObjects.*;", "
ImplementsMetaDoNotMockInterfaceObject
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ConditionalExpressionNumericPromotionTest.java
{ "start": 2609, "end": 4125 }
class ____ { Object returnObject(boolean b) { return b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0)); } Number returnNumber(boolean b) { // Extra parentheses, just for fun. return (b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0))); } Serializable returnSerializable(boolean b) { return b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0)); } void assignObject(boolean b, Object obj) { obj = b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0)); } void assignNumber(boolean b, Number obj) { obj = b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0)); } void variableObject(boolean b) { Object obj = b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0)); } void variableNumber(boolean b) { Number obj = b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0)); } void invokeMethod(boolean b, Number n) { invokeMethod(b, b ? ((Number) Integer.valueOf(0)) : ((Number) Long.valueOf(0))); } } """) .doTest(); } @Test public void negative() { testHelper .addInputLines( "Test.java", """
Test
java
spring-projects__spring-framework
spring-jms/src/test/java/org/springframework/jms/core/JmsClientTests.java
{ "start": 2487, "end": 21978 }
class ____ { @Captor private ArgumentCaptor<MessageCreator> messageCreator; @Mock(strictness = Mock.Strictness.LENIENT) private JmsTemplate jmsTemplate; private JmsClient jmsClient; @BeforeEach void setup() { given(this.jmsTemplate.getMessageConverter()).willReturn(new SimpleMessageConverter()); this.jmsClient = JmsClient.create(this.jmsTemplate); } @Test void send() { Destination destination = new Destination() {}; Message<String> message = createTextMessage(); this.jmsClient.destination(destination).send(message); verify(this.jmsTemplate).send(eq(destination), this.messageCreator.capture()); assertTextMessage(this.messageCreator.getValue()); } @Test void sendName() { Message<String> message = createTextMessage(); this.jmsClient.destination("myQueue").send(message); verify(this.jmsTemplate).send(eq("myQueue"), this.messageCreator.capture()); assertTextMessage(this.messageCreator.getValue()); } @Test void convertAndSendPayload() throws JMSException { Destination destination = new Destination() {}; this.jmsClient.destination(destination).send("my Payload"); verify(this.jmsTemplate).send(eq(destination), this.messageCreator.capture()); TextMessage textMessage = createTextMessage(this.messageCreator.getValue()); assertThat(textMessage.getText()).isEqualTo("my Payload"); } @Test void convertAndSendPayloadName() throws JMSException { this.jmsClient.destination("myQueue").send("my Payload"); verify(this.jmsTemplate).send(eq("myQueue"), this.messageCreator.capture()); TextMessage textMessage = createTextMessage(this.messageCreator.getValue()); assertThat(textMessage.getText()).isEqualTo("my Payload"); } @Test void convertAndSendPayloadAndHeaders() { Destination destination = new Destination() {}; Map<String, Object> headers = new HashMap<>(); headers.put("foo", "bar"); this.jmsClient.destination(destination).send("Hello", headers); verify(this.jmsTemplate).send(eq(destination), this.messageCreator.capture()); assertTextMessage(this.messageCreator.getValue()); // see createTextMessage } @Test void convertAndSendPayloadAndHeadersName() { Map<String, Object> headers = new HashMap<>(); headers.put("foo", "bar"); this.jmsClient.destination("myQueue").send("Hello", headers); verify(this.jmsTemplate).send(eq("myQueue"), this.messageCreator.capture()); assertTextMessage(this.messageCreator.getValue()); // see createTextMessage } @Test void convertAndSendPayloadAndHeadersWithPostProcessor() throws JMSException { Destination destination = new Destination() {}; Map<String, Object> headers = new HashMap<>(); headers.put("foo", "bar"); this.jmsClient = JmsClient.builder(this.jmsTemplate) .messagePostProcessor(msg -> MessageBuilder.fromMessage(msg).setHeader("spring", "framework").build()) .build(); this.jmsClient.destination(destination).send("Hello", headers); verify(this.jmsTemplate).send(eq(destination), this.messageCreator.capture()); TextMessage jmsMessage = createTextMessage(this.messageCreator.getValue()); assertThat(jmsMessage.getObjectProperty("spring")).isEqualTo("framework"); } @Test void receive() { Destination destination = new Destination() {}; jakarta.jms.Message jmsMessage = createJmsTextMessage(); given(this.jmsTemplate.receive(destination)).willReturn(jmsMessage); Message<?> message = this.jmsClient.destination(destination).receive().get(); verify(this.jmsTemplate).receive(destination); assertTextMessage(message); } @Test void receiveName() { jakarta.jms.Message jmsMessage = createJmsTextMessage(); given(this.jmsTemplate.receive("myQueue")).willReturn(jmsMessage); Message<?> message = this.jmsClient.destination("myQueue").receive().get(); verify(this.jmsTemplate).receive("myQueue"); assertTextMessage(message); } @Test void receiveSelected() { Destination destination = new Destination() {}; jakarta.jms.Message jmsMessage = createJmsTextMessage(); given(this.jmsTemplate.receiveSelected(destination, "selector")).willReturn(jmsMessage); Message<?> message = this.jmsClient.destination(destination).receive("selector").get(); verify(this.jmsTemplate).receiveSelected(destination, "selector"); assertTextMessage(message); } @Test void receiveSelectedName() { jakarta.jms.Message jmsMessage = createJmsTextMessage(); given(this.jmsTemplate.receiveSelected("myQueue", "selector")).willReturn(jmsMessage); Message<?> message = this.jmsClient.destination("myQueue").receive("selector").get(); verify(this.jmsTemplate).receiveSelected("myQueue", "selector"); assertTextMessage(message); } @Test void receiveAndConvert() { Destination destination = new Destination() {}; jakarta.jms.Message jmsMessage = createJmsTextMessage("my Payload"); given(this.jmsTemplate.receive(destination)).willReturn(jmsMessage); String payload = this.jmsClient.destination(destination).receive(String.class).get(); assertThat(payload).isEqualTo("my Payload"); verify(this.jmsTemplate).receive(destination); } @Test void receiveAndConvertName() { jakarta.jms.Message jmsMessage = createJmsTextMessage("my Payload"); given(this.jmsTemplate.receive("myQueue")).willReturn(jmsMessage); String payload = this.jmsClient.destination("myQueue").receive(String.class).get(); assertThat(payload).isEqualTo("my Payload"); verify(this.jmsTemplate).receive("myQueue"); } @Test void receiveAndConvertWithConversion() { jakarta.jms.Message jmsMessage = createJmsTextMessage("123"); given(this.jmsTemplate.receive("myQueue")).willReturn(jmsMessage); this.jmsClient = JmsClient.builder(this.jmsTemplate).messageConverter(new GenericMessageConverter()).build(); Integer payload = this.jmsClient.destination("myQueue").receive(Integer.class).get(); assertThat(payload).isEqualTo(Integer.valueOf(123)); verify(this.jmsTemplate).receive("myQueue"); } @Test void receiveAndConvertNoConverter() { jakarta.jms.Message jmsMessage = createJmsTextMessage("Hello"); given(this.jmsTemplate.receive("myQueue")).willReturn(jmsMessage); assertThatExceptionOfType(org.springframework.messaging.converter.MessageConversionException.class).isThrownBy(() -> this.jmsClient.destination("myQueue").receive(Writer.class)); } @Test void receiveAndConvertNoInput() { given(this.jmsTemplate.receive("myQueue")).willReturn(null); assertThat(this.jmsClient.destination("myQueue").receive(String.class)).isEmpty(); } @Test void receiveSelectedAndConvert() { Destination destination = new Destination() {}; jakarta.jms.Message jmsMessage = createJmsTextMessage("my Payload"); given(this.jmsTemplate.receiveSelected(destination, "selector")).willReturn(jmsMessage); String payload = this.jmsClient.destination(destination).receive("selector", String.class).get(); assertThat(payload).isEqualTo("my Payload"); verify(this.jmsTemplate).receiveSelected(destination, "selector"); } @Test void receiveSelectedAndConvertName() { jakarta.jms.Message jmsMessage = createJmsTextMessage("my Payload"); given(this.jmsTemplate.receiveSelected("myQueue", "selector")).willReturn(jmsMessage); String payload = this.jmsClient.destination("myQueue").receive("selector", String.class).get(); assertThat(payload).isEqualTo("my Payload"); verify(this.jmsTemplate).receiveSelected("myQueue", "selector"); } @Test void receiveSelectedAndConvertWithConversion() { jakarta.jms.Message jmsMessage = createJmsTextMessage("123"); given(this.jmsTemplate.receiveSelected("myQueue", "selector")).willReturn(jmsMessage); this.jmsClient = JmsClient.builder(this.jmsTemplate).messageConverter(new GenericMessageConverter()).build(); Integer payload = this.jmsClient.destination("myQueue").receive("selector", Integer.class).get(); assertThat(payload).isEqualTo(Integer.valueOf(123)); verify(this.jmsTemplate).receiveSelected("myQueue", "selector"); } @Test void receiveSelectedAndConvertNoConverter() { jakarta.jms.Message jmsMessage = createJmsTextMessage("Hello"); given(this.jmsTemplate.receiveSelected("myQueue", "selector")).willReturn(jmsMessage); assertThatExceptionOfType(org.springframework.messaging.converter.MessageConversionException.class).isThrownBy(() -> this.jmsClient.destination("myQueue").receive("selector", Writer.class)); } @Test void receiveSelectedAndConvertNoInput() { given(this.jmsTemplate.receiveSelected("myQueue", "selector")).willReturn(null); assertThat(this.jmsClient.destination("myQueue").receive("selector", String.class)).isEmpty(); } @Test void sendAndReceive() { Destination destination = new Destination() {}; Message<String> request = createTextMessage(); jakarta.jms.Message replyJmsMessage = createJmsTextMessage(); given(this.jmsTemplate.sendAndReceive(eq(destination), any())).willReturn(replyJmsMessage); Message<?> actual = this.jmsClient.destination(destination).sendAndReceive(request).get(); verify(this.jmsTemplate, times(1)).sendAndReceive(eq(destination), any()); assertTextMessage(actual); } @Test void sendAndReceiveName() { Message<String> request = createTextMessage(); jakarta.jms.Message replyJmsMessage = createJmsTextMessage(); given(this.jmsTemplate.sendAndReceive(eq("myQueue"), any())).willReturn(replyJmsMessage); Message<?> actual = this.jmsClient.destination("myQueue").sendAndReceive(request).get(); verify(this.jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), any()); assertTextMessage(actual); } @Test void convertSendAndReceivePayload() { Destination destination = new Destination() {}; jakarta.jms.Message replyJmsMessage = createJmsTextMessage("My reply"); given(this.jmsTemplate.sendAndReceive(eq(destination), any())).willReturn(replyJmsMessage); String reply = this.jmsClient.destination(destination).sendAndReceive("my Payload", String.class).get(); verify(this.jmsTemplate, times(1)).sendAndReceive(eq(destination), any()); assertThat(reply).isEqualTo("My reply"); } @Test void convertSendAndReceivePayloadWithPostProcessor() throws JMSException { Destination destination = new Destination() {}; jakarta.jms.Message replyJmsMessage = createJmsTextMessage("My reply"); given(this.jmsTemplate.sendAndReceive(eq(destination), any())).willReturn(replyJmsMessage); this.jmsClient = JmsClient.builder(this.jmsTemplate) .messagePostProcessor(msg -> MessageBuilder.fromMessage(msg).setHeader("spring", "framework").build()) .build(); this.jmsClient.destination(destination).sendAndReceive("my Payload", String.class); verify(this.jmsTemplate).sendAndReceive(eq(destination), this.messageCreator.capture()); TextMessage jmsMessage = createTextMessage(this.messageCreator.getValue()); assertThat(jmsMessage.getObjectProperty("spring")).isEqualTo("framework"); verify(this.jmsTemplate, times(1)).sendAndReceive(eq(destination), any()); } @Test void convertSendAndReceivePayloadName() { jakarta.jms.Message replyJmsMessage = createJmsTextMessage("My reply"); given(this.jmsTemplate.sendAndReceive(eq("myQueue"), any())).willReturn(replyJmsMessage); String reply = this.jmsClient.destination("myQueue").sendAndReceive("my Payload", String.class).get(); verify(this.jmsTemplate, times(1)).sendAndReceive(eq("myQueue"), any()); assertThat(reply).isEqualTo("My reply"); } @Test void convertMessageNotReadableException() { willThrow(MessageNotReadableException.class).given(this.jmsTemplate).receive("myQueue"); assertThatExceptionOfType(MessagingException.class).isThrownBy(() -> this.jmsClient.destination("myQueue").receive()); } @Test void convertDestinationResolutionExceptionOnSend() { Destination destination = new Destination() {}; willThrow(DestinationResolutionException.class).given(this.jmsTemplate).send(eq(destination), any()); assertThatExceptionOfType(org.springframework.messaging.core.DestinationResolutionException.class).isThrownBy(() -> this.jmsClient.destination(destination).send(createTextMessage())); } @Test void convertDestinationResolutionExceptionOnReceive() { Destination destination = new Destination() {}; willThrow(DestinationResolutionException.class).given(this.jmsTemplate).receive(destination); assertThatExceptionOfType(org.springframework.messaging.core.DestinationResolutionException.class).isThrownBy(() -> this.jmsClient.destination(destination).receive()); } @Test void convertInvalidDestinationExceptionOnSendAndReceiveWithName() { willThrow(InvalidDestinationException.class).given(this.jmsTemplate).sendAndReceive(eq("unknownQueue"), any()); assertThatExceptionOfType(org.springframework.messaging.core.DestinationResolutionException.class).isThrownBy(() -> this.jmsClient.destination("unknownQueue").sendAndReceive(createTextMessage())); } @Test void convertInvalidDestinationExceptionOnSendAndReceive() { Destination destination = new Destination() {}; willThrow(InvalidDestinationException.class).given(this.jmsTemplate).sendAndReceive(eq(destination), any()); assertThatExceptionOfType(org.springframework.messaging.core.DestinationResolutionException.class).isThrownBy(() -> this.jmsClient.destination(destination).sendAndReceive(createTextMessage())); } @Test void sendWithDefaults() throws Exception { ConnectionFactory connectionFactory = mock(); Connection connection = mock(); Session session = mock(); Queue queue = mock(); MessageProducer messageProducer = mock(); TextMessage textMessage = mock(); given(connectionFactory.createConnection()).willReturn(connection); given(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(session); given(session.createProducer(queue)).willReturn(messageProducer); given(session.createTextMessage("just testing")).willReturn(textMessage); JmsClient.create(connectionFactory).destination(queue) .send("just testing"); verify(messageProducer).send(textMessage); verify(messageProducer).close(); verify(session).close(); verify(connection).close(); } @Test void sendWithPostProcessor() throws Exception { ConnectionFactory connectionFactory = mock(); Connection connection = mock(); Session session = mock(); Queue queue = mock(); MessageProducer messageProducer = mock(); TextMessage textMessage = mock(); given(connectionFactory.createConnection()).willReturn(connection); given(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(session); given(session.createProducer(queue)).willReturn(messageProducer); given(session.createTextMessage("just testing")).willReturn(textMessage); JmsClient.builder(connectionFactory) .messagePostProcessor(msg -> MessageBuilder.fromMessage(msg).setHeader("spring", "framework").build()) .build() .destination(queue).send("just testing"); verify(textMessage).setObjectProperty("spring", "framework"); verify(messageProducer).send(textMessage); verify(messageProducer).close(); verify(session).close(); verify(connection).close(); } @Test void sendWithCustomSettings() throws Exception { ConnectionFactory connectionFactory = mock(); Connection connection = mock(); Session session = mock(); Queue queue = mock(); MessageProducer messageProducer = mock(); TextMessage textMessage = mock(); given(connectionFactory.createConnection()).willReturn(connection); given(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(session); given(session.createProducer(queue)).willReturn(messageProducer); given(session.createTextMessage("just testing")).willReturn(textMessage); JmsClient.create(connectionFactory).destination(queue) .withDeliveryDelay(0).withDeliveryPersistent(false).withPriority(2).withTimeToLive(3) .send("just testing"); verify(messageProducer).setDeliveryDelay(0); verify(messageProducer).send(textMessage, DeliveryMode.NON_PERSISTENT, 2, 3); verify(messageProducer).close(); verify(session).close(); verify(connection).close(); } @Test void receiveWithDefaults() throws Exception { ConnectionFactory connectionFactory = mock(); Connection connection = mock(); Session session = mock(); Queue queue = mock(); MessageConsumer messageConsumer = mock(); TextMessage textMessage = mock(); given(connectionFactory.createConnection()).willReturn(connection); given(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(session); given(session.createConsumer(queue, null)).willReturn(messageConsumer); given(messageConsumer.receive()).willReturn(textMessage); given(textMessage.getText()).willReturn("Hello World!"); String result = JmsClient.create(connectionFactory).destination(queue) .receive(String.class).get(); assertThat(result).isEqualTo("Hello World!"); verify(connection).start(); verify(messageConsumer).close(); verify(session).close(); verify(connection).close(); } @Test void receiveWithCustomTimeout() throws Exception { ConnectionFactory connectionFactory = mock(); Connection connection = mock(); Session session = mock(); Queue queue = mock(); MessageConsumer messageConsumer = mock(); TextMessage textMessage = mock(); given(connectionFactory.createConnection()).willReturn(connection); given(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(session); given(session.createConsumer(queue, null)).willReturn(messageConsumer); given(messageConsumer.receive(10)).willReturn(textMessage); given(textMessage.getText()).willReturn("Hello World!"); String result = JmsClient.create(connectionFactory).destination(queue) .withReceiveTimeout(10).receive(String.class).get(); assertThat(result).isEqualTo("Hello World!"); verify(connection).start(); verify(messageConsumer).close(); verify(session).close(); verify(connection).close(); } private Message<String> createTextMessage(String payload) { return MessageBuilder.withPayload(payload).setHeader("foo", "bar").build(); } private Message<String> createTextMessage() { return createTextMessage("Hello"); } private jakarta.jms.Message createJmsTextMessage(String payload) { StubTextMessage jmsMessage = new StubTextMessage(payload); jmsMessage.setStringProperty("foo", "bar"); return jmsMessage; } private jakarta.jms.Message createJmsTextMessage() { return createJmsTextMessage("Hello"); } private void assertTextMessage(MessageCreator messageCreator) { try { TextMessage jmsMessage = createTextMessage(messageCreator); assertThat(jmsMessage.getText()).as("Wrong body message").isEqualTo("Hello"); assertThat(jmsMessage.getStringProperty("foo")).as("Invalid foo property").isEqualTo("bar"); } catch (JMSException e) { throw new IllegalStateException("Wrong text message", e); } } private void assertTextMessage(Message<?> message) { assertThat(message).as("message should not be null").isNotNull(); assertThat(message.getPayload()).as("Wrong payload").isEqualTo("Hello"); assertThat(message.getHeaders().get("foo")).as("Invalid foo property").isEqualTo("bar"); } protected TextMessage createTextMessage(MessageCreator creator) throws JMSException { Session mock = mock(); given(mock.createTextMessage(any())).willAnswer( (Answer<TextMessage>) invocation -> new StubTextMessage((String) invocation.getArguments()[0])); jakarta.jms.Message message = creator.createMessage(mock); verify(mock).createTextMessage(any()); return (TextMessage) message; } }
JmsClientTests
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/EnvironmentSettings.java
{ "start": 2251, "end": 5676 }
class ____ { /** * Holds all the configuration generated by the builder, together with any required additional * configuration. */ private final Configuration configuration; private final ClassLoader classLoader; private final @Nullable CatalogStore catalogStore; private final @Nullable SqlFactory sqlFactory; private EnvironmentSettings( Configuration configuration, ClassLoader classLoader, CatalogStore catalogStore, SqlFactory sqlFactory) { this.configuration = configuration; this.classLoader = classLoader; this.catalogStore = catalogStore; this.sqlFactory = sqlFactory; } /** * Creates a default instance of {@link EnvironmentSettings} in streaming execution mode. * * <p>In this mode, both bounded and unbounded data streams can be processed. * * <p>This method is a shortcut for creating a {@link TableEnvironment} with little code. Use * the builder provided in {@link EnvironmentSettings#newInstance()} for advanced settings. */ public static EnvironmentSettings inStreamingMode() { return EnvironmentSettings.newInstance().inStreamingMode().build(); } /** * Creates a default instance of {@link EnvironmentSettings} in batch execution mode. * * <p>This mode is highly optimized for batch scenarios. Only bounded data streams can be * processed in this mode. * * <p>This method is a shortcut for creating a {@link TableEnvironment} with little code. Use * the builder provided in {@link EnvironmentSettings#newInstance()} for advanced settings. */ public static EnvironmentSettings inBatchMode() { return EnvironmentSettings.newInstance().inBatchMode().build(); } /** Creates a builder for creating an instance of {@link EnvironmentSettings}. */ public static Builder newInstance() { return new Builder(); } /** Get the underlying {@link Configuration}. */ public Configuration getConfiguration() { return configuration; } /** * Gets the specified name of the initial catalog to be created when instantiating a {@link * TableEnvironment}. */ public String getBuiltInCatalogName() { return configuration.get(TABLE_CATALOG_NAME); } /** * Gets the specified name of the default database in the initial catalog to be created when * instantiating a {@link TableEnvironment}. */ public String getBuiltInDatabaseName() { return configuration.get(TABLE_DATABASE_NAME); } /** Tells if the {@link TableEnvironment} should work in a batch or streaming mode. */ public boolean isStreamingMode() { return configuration.get(RUNTIME_MODE) == STREAMING; } /** * Returns the user {@link ClassLoader} to use for code generation, UDF loading and other * operations requiring reflections on user code. */ @Internal public ClassLoader getUserClassLoader() { return classLoader; } @Internal @Nullable public CatalogStore getCatalogStore() { return catalogStore; } @Internal public Optional<SqlFactory> getSqlFactory() { return Optional.ofNullable(sqlFactory); } /** A builder for {@link EnvironmentSettings}. */ @PublicEvolving public static
EnvironmentSettings
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/domain/sample/AuditableEntity.java
{ "start": 1103, "end": 1847 }
class ____ { @Id @GeneratedValue // private Long id; private String data; @Embedded // private AuditableEmbeddable auditDetails; public AuditableEntity() { this(null, null, null); } public AuditableEntity(Long id, String data, AuditableEmbeddable auditDetails) { this.id = id; this.data = data; this.auditDetails = auditDetails; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public AuditableEmbeddable getAuditDetails() { return auditDetails; } public void setAuditDetails(AuditableEmbeddable auditDetails) { this.auditDetails = auditDetails; } }
AuditableEntity
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/recovery/RecoveryResponse.java
{ "start": 745, "end": 3453 }
class ____ extends TransportResponse { final List<String> phase1FileNames; final List<Long> phase1FileSizes; final List<String> phase1ExistingFileNames; final List<Long> phase1ExistingFileSizes; final long phase1TotalSize; final long phase1ExistingTotalSize; final long phase1Time; final long phase1ThrottlingWaitTime; final long startTime; final int phase2Operations; final long phase2Time; RecoveryResponse( List<String> phase1FileNames, List<Long> phase1FileSizes, List<String> phase1ExistingFileNames, List<Long> phase1ExistingFileSizes, long phase1TotalSize, long phase1ExistingTotalSize, long phase1Time, long phase1ThrottlingWaitTime, long startTime, int phase2Operations, long phase2Time ) { this.phase1FileNames = phase1FileNames; this.phase1FileSizes = phase1FileSizes; this.phase1ExistingFileNames = phase1ExistingFileNames; this.phase1ExistingFileSizes = phase1ExistingFileSizes; this.phase1TotalSize = phase1TotalSize; this.phase1ExistingTotalSize = phase1ExistingTotalSize; this.phase1Time = phase1Time; this.phase1ThrottlingWaitTime = phase1ThrottlingWaitTime; this.startTime = startTime; this.phase2Operations = phase2Operations; this.phase2Time = phase2Time; } RecoveryResponse(StreamInput in) throws IOException { phase1FileNames = in.readStringCollectionAsList(); phase1FileSizes = in.readCollectionAsList(StreamInput::readVLong); phase1ExistingFileNames = in.readStringCollectionAsList(); phase1ExistingFileSizes = in.readCollectionAsList(StreamInput::readVLong); phase1TotalSize = in.readVLong(); phase1ExistingTotalSize = in.readVLong(); phase1Time = in.readVLong(); phase1ThrottlingWaitTime = in.readVLong(); startTime = in.readVLong(); phase2Operations = in.readVInt(); phase2Time = in.readVLong(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeStringCollection(phase1FileNames); out.writeCollection(phase1FileSizes, StreamOutput::writeVLong); out.writeStringCollection(phase1ExistingFileNames); out.writeCollection(phase1ExistingFileSizes, StreamOutput::writeVLong); out.writeVLong(phase1TotalSize); out.writeVLong(phase1ExistingTotalSize); out.writeVLong(phase1Time); out.writeVLong(phase1ThrottlingWaitTime); out.writeVLong(startTime); out.writeVInt(phase2Operations); out.writeVLong(phase2Time); } }
RecoveryResponse
java
apache__hadoop
hadoop-tools/hadoop-gcp/src/main/java/org/apache/hadoop/fs/gs/GoogleHadoopFSInputStream.java
{ "start": 1429, "end": 6209 }
class ____ extends FSInputStream { public static final Logger LOG = LoggerFactory.getLogger(GoogleHadoopFSInputStream.class); // Used for single-byte reads. private final byte[] singleReadBuf = new byte[1]; // Path of the file to read. private final URI gcsPath; // File Info of gcsPath, will be pre-populated in some cases i.e. when Json client is used and // failFast is disabled. // All store IO access goes through this. private final SeekableByteChannel channel; // Number of bytes read through this channel. private long totalBytesRead = 0; /** * Closed bit. Volatile so reads are non-blocking. Updates must be in a synchronized block to * guarantee an atomic check and set */ private volatile boolean closed; // Statistics tracker provided by the parent GoogleHadoopFileSystem for recording stats private final FileSystem.Statistics statistics; static GoogleHadoopFSInputStream create( GoogleHadoopFileSystem ghfs, URI gcsPath, FileSystem.Statistics statistics) throws IOException { LOG.trace("create(gcsPath: {})", gcsPath); GoogleCloudStorageFileSystem gcsFs = ghfs.getGcsFs(); FileInfo fileInfo = gcsFs.getFileInfoObject(gcsPath); SeekableByteChannel channel = gcsFs.open(fileInfo, ghfs.getFileSystemConfiguration()); return new GoogleHadoopFSInputStream(gcsPath, channel, statistics); } private GoogleHadoopFSInputStream( URI gcsPath, SeekableByteChannel channel, FileSystem.Statistics statistics) { LOG.trace("GoogleHadoopFSInputStream(gcsPath: {})", gcsPath); this.gcsPath = gcsPath; this.channel = channel; this.statistics = statistics; } @Override public synchronized int read() throws IOException { checkNotClosed(); int numRead = read(singleReadBuf, /* offset= */ 0, /* length= */ 1); checkState( numRead == -1 || numRead == 1, "Read %s bytes using single-byte buffer for path %s ending in position %s", numRead, gcsPath, channel.position()); return numRead > 0 ? singleReadBuf[0] & 0xff : numRead; } @Override public synchronized int read(@Nonnull byte[] buf, int offset, int length) throws IOException { checkNotClosed(); checkNotNull(buf, "buf must not be null"); if (offset < 0 || length < 0 || length > buf.length - offset) { throw new IndexOutOfBoundsException(); } // TODO(user): Wrap this in a while-loop if we ever introduce a non-blocking mode for // the underlying channel. int numRead = channel.read(ByteBuffer.wrap(buf, offset, length)); if (numRead > 0) { // -1 means we actually read 0 bytes, but requested at least one byte. totalBytesRead += numRead; statistics.incrementBytesRead(numRead); statistics.incrementReadOps(1); } return numRead; } @Override public synchronized void seek(long pos) throws IOException { checkNotClosed(); LOG.trace("seek({})", pos); try { channel.position(pos); } catch (IllegalArgumentException e) { throw new IOException(e); } } @Override public synchronized void close() throws IOException { if (!closed) { closed = true; LOG.trace("close(): {}", gcsPath); try { if (channel != null) { LOG.trace( "Closing '{}' file with {} total bytes read", gcsPath, totalBytesRead); channel.close(); } } catch (Exception e) { LOG.warn("Error while closing underneath read channel resources for path: {}", gcsPath, e); } } } /** * Gets the current position within the file being read. * * @return The current position within the file being read. * @throws IOException if an IO error occurs. */ @Override public synchronized long getPos() throws IOException { checkNotClosed(); long pos = channel.position(); LOG.trace("getPos(): {}", pos); return pos; } /** * Seeks a different copy of the data. Not supported. * * @return true if a new source is found, false otherwise. */ @Override public boolean seekToNewSource(long targetPos) { LOG.trace("seekToNewSource({}): false", targetPos); return false; } @Override public int available() throws IOException { if (!channel.isOpen()) { throw new ClosedChannelException(); } return super.available(); } /** * Verify that the input stream is open. Non-blocking; this gives the last state of the volatile * {@link #closed} field. * * @throws IOException if the connection is closed. */ private void checkNotClosed() throws IOException { if (closed) { throw new IOException(gcsPath + ": " + FSExceptionMessages.STREAM_IS_CLOSED); } } }
GoogleHadoopFSInputStream
java
spring-projects__spring-framework
spring-core-test/src/test/java/org/springframework/core/test/tools/SourceFileTests.java
{ "start": 991, "end": 1109 }
class ____ { private static final String HELLO_WORLD = """ package com.example.helloworld; public
SourceFileTests
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-nativetask/src/test/java/org/apache/hadoop/mapred/nativetask/buffer/TestBufferPushPull.java
{ "start": 5318, "end": 5726 }
class ____ implements RecordWriter<BytesWritable, BytesWritable> { protected int count = 0; RecordWriterForPush() { } @Override public abstract void write(BytesWritable key, BytesWritable value) throws IOException; @Override public void close(Reporter reporter) throws IOException { } public void reset() { count = 0; } }; public static
RecordWriterForPush
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java
{ "start": 40924, "end": 41469 }
class ____ { private final ExecutorService executor; public final Info info; ExecutorHolder(ExecutorService executor, Info info) { assert executor instanceof EsThreadPoolExecutor || executor == EsExecutors.DIRECT_EXECUTOR_SERVICE; this.executor = executor; this.info = info; } ExecutorService executor() { return executor; } } /** * The settings used to create a Java ExecutorService thread pool. */ public static
ExecutorHolder
java
apache__flink
flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/protobuf/ParquetProtoWriters.java
{ "start": 1308, "end": 1494 }
class ____ { /** * Creates a {@link ParquetWriterFactory} for the given type. The type should represent a * Protobuf message. * * @param type The
ParquetProtoWriters
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/client/MockRestServiceServerTests.java
{ "start": 2119, "end": 9273 }
class ____ { private final RestTemplate restTemplate = new RestTemplate(); @Test void buildMultipleTimes() { MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(this.restTemplate); MockRestServiceServer server = builder.build(); server.expect(requestTo("/foo")).andRespond(withSuccess()); this.restTemplate.getForObject("/foo", Void.class); server.verify(); server = builder.ignoreExpectOrder(true).build(); server.expect(requestTo("/foo")).andRespond(withSuccess()); server.expect(requestTo("/bar")).andRespond(withSuccess()); this.restTemplate.getForObject("/bar", Void.class); this.restTemplate.getForObject("/foo", Void.class); server.verify(); server = builder.build(); server.expect(requestTo("/bar")).andRespond(withSuccess()); this.restTemplate.getForObject("/bar", Void.class); server.verify(); } @Test void exactExpectOrder() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate) .ignoreExpectOrder(false).build(); server.expect(requestTo("/foo")).andRespond(withSuccess()); server.expect(requestTo("/bar")).andRespond(withSuccess()); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.restTemplate.getForObject("/bar", Void.class)); } @Test void ignoreExpectOrder() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate) .ignoreExpectOrder(true).build(); server.expect(requestTo("/foo")).andRespond(withSuccess()); server.expect(requestTo("/bar")).andRespond(withSuccess()); this.restTemplate.getForObject("/bar", Void.class); this.restTemplate.getForObject("/foo", Void.class); server.verify(); } @Test void executingResponseCreator() { RestTemplate restTemplate = createEchoRestTemplate(); ExecutingResponseCreator withActualCall = new ExecutingResponseCreator(restTemplate.getRequestFactory()); MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build(); server.expect(requestTo("/profile")).andRespond(withSuccess()); server.expect(requestTo("/quoteOfTheDay")).andRespond(withActualCall); var response1 = restTemplate.getForEntity("/profile", String.class); var response2 = restTemplate.getForEntity("/quoteOfTheDay", String.class); server.verify(); assertThat(response1.getStatusCode().value()).isEqualTo(200); assertThat(response1.getBody()).isNullOrEmpty(); assertThat(response2.getStatusCode().value()).isEqualTo(300); assertThat(response2.getBody()).isEqualTo("echo from /quoteOfTheDay"); } private static RestTemplate createEchoRestTemplate() { ClientHttpRequestFactory requestFactory = (uri, httpMethod) -> { MockClientHttpRequest request = new MockClientHttpRequest(httpMethod, uri); ClientHttpResponse response = new MockClientHttpResponse( ("echo from " + uri.getPath()).getBytes(StandardCharsets.UTF_8), HttpStatus.MULTIPLE_CHOICES); // use a different status on purpose response.getHeaders().setContentType(MediaType.TEXT_PLAIN); request.setResponse(response); return request; }; return new RestTemplate(requestFactory); } @Test void resetAndReuseServer() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build(); server.expect(requestTo("/foo")).andRespond(withSuccess()); this.restTemplate.getForObject("/foo", Void.class); server.verify(); server.reset(); server.expect(requestTo("/bar")).andRespond(withSuccess()); this.restTemplate.getForObject("/bar", Void.class); server.verify(); } @Test void resetAndReuseServerWithUnorderedExpectationManager() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate) .ignoreExpectOrder(true).build(); server.expect(requestTo("/foo")).andRespond(withSuccess()); this.restTemplate.getForObject("/foo", Void.class); server.verify(); server.reset(); server.expect(requestTo("/foo")).andRespond(withSuccess()); server.expect(requestTo("/bar")).andRespond(withSuccess()); this.restTemplate.getForObject("/bar", Void.class); this.restTemplate.getForObject("/foo", Void.class); server.verify(); } @Test // gh-24486 void resetClearsRequestFailures() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build(); server.expect(once(), requestTo("/remoteurl")).andRespond(withSuccess()); this.restTemplate.postForEntity("/remoteurl", null, String.class); server.verify(); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> this.restTemplate.postForEntity("/remoteurl", null, String.class)) .withMessageStartingWith("No further requests expected"); server.reset(); server.expect(once(), requestTo("/remoteurl")).andRespond(withSuccess()); this.restTemplate.postForEntity("/remoteurl", null, String.class); server.verify(); } @Test // SPR-16132 void followUpRequestAfterFailure() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build(); server.expect(requestTo("/some-service/some-endpoint")) .andRespond(request -> { throw new SocketException("pseudo network error"); }); server.expect(requestTo("/reporting-service/report-error")) .andExpect(method(POST)).andRespond(withSuccess()); try { this.restTemplate.getForEntity("/some-service/some-endpoint", String.class); fail("Expected exception"); } catch (Exception ex) { this.restTemplate.postForEntity("/reporting-service/report-error", ex.toString(), String.class); } server.verify(); } @Test // gh-21799 void verifyShouldFailIfRequestsFailed() { MockRestServiceServer server = MockRestServiceServer.bindTo(this.restTemplate).build(); server.expect(once(), requestTo("/remoteurl")).andRespond(withSuccess()); this.restTemplate.postForEntity("/remoteurl", null, String.class); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> this.restTemplate.postForEntity("/remoteurl", null, String.class)) .withMessageStartingWith("No further requests expected"); assertThatExceptionOfType(AssertionError.class) .isThrownBy(server::verify) .withMessageStartingWith("Some requests did not execute successfully"); } @Test void verifyWithTimeout() { MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(this.restTemplate); MockRestServiceServer server1 = builder.build(); server1.expect(requestTo("/foo")).andRespond(withSuccess()); server1.expect(requestTo("/bar")).andRespond(withSuccess()); this.restTemplate.getForObject("/foo", Void.class); assertThatThrownBy(() -> server1.verify(Duration.ofMillis(100))).hasMessage(""" Further request(s) expected leaving 1 unsatisfied expectation(s). 1 request(s) executed: GET /foo, headers: [Accept:"application/json, application/*+json"] """); MockRestServiceServer server2 = builder.build(); server2.expect(requestTo("/foo")).andRespond(withSuccess()); server2.expect(requestTo("/bar")).andRespond(withSuccess()); this.restTemplate.getForObject("/foo", Void.class); this.restTemplate.getForObject("/bar", Void.class); server2.verify(Duration.ofMillis(100)); } }
MockRestServiceServerTests
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/co/KeyedCoProcessOperatorTest.java
{ "start": 15751, "end": 16875 }
class ____ extends KeyedCoProcessFunction<String, Integer, String, String> { private static final long serialVersionUID = 1L; @Override public void processElement1(Integer value, Context ctx, Collector<String> out) throws Exception { out.collect( value + "WM:" + ctx.timerService().currentWatermark() + " TS:" + ctx.timestamp()); } @Override public void processElement2(String value, Context ctx, Collector<String> out) throws Exception { out.collect( value + "WM:" + ctx.timerService().currentWatermark() + " TS:" + ctx.timestamp()); } @Override public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {} } private static
WatermarkQueryingProcessFunction
java
quarkusio__quarkus
extensions/smallrye-graphql-client/deployment/src/test/java/io/quarkus/smallrye/graphql/client/deployment/TypesafeGraphQLClientMapTest.java
{ "start": 2835, "end": 5324 }
class ____ { private String bar; public Foo() { } public Foo(String bar) { this.bar = bar; } public String getBar() { return bar; } public void setBar(String bar) { this.bar = bar; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Foo foo = (Foo) o; return Objects.equals(bar, foo.bar); } @Override public int hashCode() { return Objects.hash(bar); } } @Test public void scalarToScalar() { Map<Integer, String> input = new HashMap<>(); input.put(1, "a"); input.put(2, "b"); Map<Integer, String> result = client.scalarToScalar(input); assertEquals("a", result.get(1)); assertEquals("b", result.get(2)); assertEquals(2, result.size()); } @Test public void complexToScalar() { Map<Foo, Integer> input = new HashMap<>(); input.put(new Foo("a"), 68); input.put(new Foo("x"), 55); Map<Foo, Integer> result = client.complexToScalar(input); assertEquals(68L, result.get(new Foo("a")).longValue()); assertEquals(55L, result.get(new Foo("x")).longValue()); assertEquals(2, result.size()); } @Test public void scalarToComplex() { Map<Integer, Foo> input = new HashMap<>(); input.put(68, new Foo("a")); input.put(55, new Foo("x")); Map<Integer, Foo> result = client.scalarToComplex(input); assertEquals(result.get(68), new Foo("a")); assertEquals(result.get(55), new Foo("x")); assertEquals(2, result.size()); } @Test public void complexToComplexWrapped() { ComplexToComplexMapWrapper input = new ComplexToComplexMapWrapper(); Map<Foo, Foo> wrappedMap = new HashMap<>(); wrappedMap.put(new Foo("a"), new Foo("aa")); wrappedMap.put(new Foo("b"), new Foo("bb")); input.setMap(wrappedMap); ComplexToComplexMapWrapper result = client.complexToComplexWrapped(input); assertEquals(new Foo("aa"), result.getMap().get(new Foo("a"))); assertEquals(new Foo("bb"), result.getMap().get(new Foo("b"))); assertEquals(2, result.getMap().size()); } }
Foo
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/context/support/SpringBeanAutowiringSupport.java
{ "start": 1995, "end": 2248 }
class ____ provide * {@code @Autowired} processing based on the current Spring context. * * <p><b>NOTE:</b> If there is an explicit way to access the ServletContext, * prefer such a way over using this class. The {@link WebApplicationContextUtils} *
to
java
alibaba__druid
core/src/test/java/com/alibaba/druid/pool/Test_C2.java
{ "start": 788, "end": 3324 }
class ____ extends TestCase { private String jdbcUrl; private String user; private String password; private String driverClass; private int minPoolSize = 50; private int maxPoolSize = 100; private int maxActive = 500; protected void setUp() throws Exception { // jdbcUrl = // "jdbc:mysql://a.b.c.d/dragoon_v25masterdb?useUnicode=true&characterEncoding=UTF-8"; // user = "dragoon25"; // password = "dragoon25"; // driverClass = "com.mysql.jdbc.Driver"; jdbcUrl = "jdbc:fake:dragoon_v25masterdb"; user = "dragoon25"; password = "dragoon25"; driverClass = "com.alibaba.druid.mock.MockDriver"; } public void test_concurrent_2() throws Exception { final DruidDataSource dataSource = new DruidDataSource(); Class.forName("com.alibaba.druid.mock.MockDriver"); dataSource.setInitialSize(10); dataSource.setMaxActive(maxPoolSize); dataSource.setMinIdle(minPoolSize); dataSource.setMaxIdle(maxPoolSize); dataSource.setPoolPreparedStatements(true); dataSource.setDriverClassName(driverClass); dataSource.setUrl(jdbcUrl); dataSource.setPoolPreparedStatements(true); final int THREAD_COUNT = 2; final int LOOP_COUNT = 1000 * 1000; final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(THREAD_COUNT); for (int threadIndex = 0; threadIndex < THREAD_COUNT; ++threadIndex) { Thread thread = new Thread() { public void run() { try { startLatch.await(); for (int i = 0; i < LOOP_COUNT; ++i) { Connection conn = dataSource.getConnection(); conn.close(); } } catch (Throwable e) { e.printStackTrace(); } finally { endLatch.countDown(); } } }; thread.start(); } startLatch.countDown(); endLatch.await(); Assert.assertEquals(THREAD_COUNT * LOOP_COUNT, dataSource.getConnectCount()); Assert.assertEquals(THREAD_COUNT * LOOP_COUNT, dataSource.getCloseCount()); Assert.assertEquals(0, dataSource.getConnectErrorCount()); Assert.assertEquals(0, dataSource.getActiveCount()); } }
Test_C2
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/execution/ImperativeExecutionFlowImpl.java
{ "start": 1089, "end": 4223 }
class ____ implements ImperativeExecutionFlow<Object> { @Nullable private Object value; @Nullable private Throwable error; @Nullable private Map<String, Object> context; <T> ImperativeExecutionFlowImpl(T value, Throwable error) { this.value = value; this.error = error; } @Nullable @Override public Object getValue() { return value; } @Nullable @Override public Throwable getError() { return error; } @Override public Map<String, Object> getContext() { return context == null ? Collections.emptyMap() : context; } @Override public <R> ExecutionFlow<R> flatMap(Function<? super Object, ? extends ExecutionFlow<? extends R>> transformer) { if (error == null) { try { if (value != null) { return (ExecutionFlow<R>) transformer.apply(value); } } catch (Throwable e) { error = e; value = null; } } return (ExecutionFlow<R>) this; } @Override public <R> ExecutionFlow<R> then(Supplier<? extends ExecutionFlow<? extends R>> supplier) { if (error == null) { try { return (ExecutionFlow<R>) supplier.get(); } catch (Throwable e) { error = e; value = null; } } return (ExecutionFlow<R>) this; } @Override public <R> ExecutionFlow<R> map(Function<? super Object, ? extends R> transformer) { if (error == null) { try { value = transformer.apply(value); } catch (Throwable e) { error = e; value = null; } } return (ExecutionFlow<R>) this; } @Override public ExecutionFlow<Object> onErrorResume(Function<? super Throwable, ? extends ExecutionFlow<? extends Object>> fallback) { if (error != null) { try { return (ExecutionFlow<Object>) fallback.apply(error); } catch (Throwable e) { error = e; value = null; } } return this; } @Override public ExecutionFlow<Object> putInContext(String key, Object value) { if (context == null) { context = new LinkedHashMap<>(); } context.put(key, value); return this; } @Override public void onComplete(BiConsumer<? super Object, Throwable> fn) { fn.accept(value, error); } @Override public void completeTo(CompletableFuture<Object> completableFuture) { if (error != null) { completableFuture.completeExceptionally(error); } else { completableFuture.complete(value); } } @Override public CompletableFuture<Object> toCompletableFuture() { if (error != null) { return CompletableFuture.failedFuture(error); } return CompletableFuture.completedFuture(value); } }
ImperativeExecutionFlowImpl
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/clickhouse/issues/Issue5933.java
{ "start": 736, "end": 4973 }
class ____ { @Test public void test_parse_arrauy_join_0() { for (DbType dbType : new DbType[]{DbType.clickhouse}) { for (String sql : new String[]{ "SELECT * FROM base_customized_cost " + "ARRAY JOIN split.service AS service " + "WHERE capture_time >= DATE('2024-04-01') " + "AND capture_time < DATE('2024-05-01') LIMIT 100;", }) { System.out.println("最原始SQL===" + sql); SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType); List<SQLStatement> statementList = parser.parseStatementList(); System.out.println(statementList); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); SQLJoinTableSource sts = (SQLJoinTableSource) stmt.getSelect().getQueryBlock().getFrom(); System.out.println("JOIN类型 " + sts.getJoinType()); assertEquals("ARRAY JOIN", sts.getJoinType().name); assertEquals("SELECT *\n" + "FROM base_customized_cost\n" + "\tARRAY JOIN split.service AS service\n" + "WHERE capture_time >= DATE('2024-04-01')\n" + "\tAND capture_time < DATE('2024-05-01')\n" + "LIMIT 100;", stmt.toString()); SQLParseAssertUtil.assertParseSql(sql, dbType); } } } @Test public void test_parse_arrauy_join_all() { for (DbType dbType : new DbType[]{DbType.clickhouse}) { for (String sql : new String[]{ "SELECT s, arr\n" + "FROM arrays_test\n" + "LEFT ARRAY JOIN arr;", "SELECT s, arr\n" + "FROM arrays_test\n" + "ARRAY JOIN arr;", "SELECT s, arr\n" + "FROM arrays_test\n" + "LEFT ARRAY JOIN arr;", "SELECT s, arr, a\n" + "FROM arrays_test\n" + "ARRAY JOIN arr AS a;", "SELECT s, arr_external\n" + "FROM arrays_test\n" + "ARRAY JOIN [1, 2, 3] AS arr_external;", "SELECT s, arr, a, num, mapped\n" + "FROM arrays_test\n" + "ARRAY JOIN arr AS a, arrayEnumerate(arr) AS num, arrayMap(x -> x + 1, arr) AS mapped;", "SELECT s, arr, a, num, arrayEnumerate(arr)\n" + "FROM arrays_test\n" + "ARRAY JOIN arr AS a, arrayEnumerate(arr) AS num;", // "SELECT s, arr, a, b\n" // + "FROM arrays_test ARRAY JOIN arr as a, [['a','b'],['c']] as b\n" // + "SETTINGS enable_unaligned_array_join = 1;", "SELECT s, `nest.x`, `nest.y`\n" + "FROM nested_test\n" + "ARRAY JOIN nest;", "SELECT s, `nest.x`, `nest.y`\n" + "FROM nested_test\n" + "ARRAY JOIN `nest.x`, `nest.y`;", "SELECT s, `nest.x`, `nest.y`\n" + "FROM nested_test\n" + "ARRAY JOIN `nest.x`;", "SELECT s, `n.x`, `n.y`, `nest.x`, `nest.y`\n" + "FROM nested_test\n" + "ARRAY JOIN nest AS n;", "SELECT s, `n.x`, `n.y`, `nest.x`, `nest.y`, num\n" + "FROM nested_test\n" + "ARRAY JOIN nest AS n, arrayEnumerate(`nest.x`) AS num;", "SELECT arrayJoin([1, 2, 3] AS src) AS dst, 'Hello', src", }) { System.out.println("最原始SQL===" + sql); SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType); List<SQLStatement> statementList = parser.parseStatementList(); System.out.println(statementList); assertEquals(1, statementList.size()); SQLParseAssertUtil.assertParseSql(sql, dbType); } } } }
Issue5933
java
google__guava
android/guava/src/com/google/common/util/concurrent/SmoothRateLimiter.java
{ "start": 15689, "end": 19734 }
class ____ extends SmoothRateLimiter { /** The work (permits) of how many seconds can be saved up if this RateLimiter is unused? */ final double maxBurstSeconds; SmoothBursty(SleepingStopwatch stopwatch, double maxBurstSeconds) { super(stopwatch); this.maxBurstSeconds = maxBurstSeconds; } @Override void doSetRate(double permitsPerSecond, double stableIntervalMicros) { double oldMaxPermits = this.maxPermits; maxPermits = maxBurstSeconds * permitsPerSecond; if (oldMaxPermits == Double.POSITIVE_INFINITY) { // if we don't special-case this, we would get storedPermits == NaN, below storedPermits = maxPermits; } else { storedPermits = (oldMaxPermits == 0.0) ? 0.0 // initial state : storedPermits * maxPermits / oldMaxPermits; } } @Override long storedPermitsToWaitTime(double storedPermits, double permitsToTake) { return 0L; } @Override double coolDownIntervalMicros() { return stableIntervalMicros; } } /** The currently stored permits. */ double storedPermits; /** The maximum number of stored permits. */ double maxPermits; /** * The interval between two unit requests, at our stable rate. E.g., a stable rate of 5 permits * per second has a stable interval of 200ms. */ double stableIntervalMicros; /** * The time when the next request (no matter its size) will be granted. After granting a request, * this is pushed further in the future. Large requests push this further than small requests. */ private long nextFreeTicketMicros = 0L; // could be either in the past or future private SmoothRateLimiter(SleepingStopwatch stopwatch) { super(stopwatch); } @Override final void doSetRate(double permitsPerSecond, long nowMicros) { resync(nowMicros); double stableIntervalMicros = SECONDS.toMicros(1L) / permitsPerSecond; this.stableIntervalMicros = stableIntervalMicros; doSetRate(permitsPerSecond, stableIntervalMicros); } abstract void doSetRate(double permitsPerSecond, double stableIntervalMicros); @Override final double doGetRate() { return SECONDS.toMicros(1L) / stableIntervalMicros; } @Override final long queryEarliestAvailable(long nowMicros) { return nextFreeTicketMicros; } @Override final long reserveEarliestAvailable(int requiredPermits, long nowMicros) { resync(nowMicros); long returnValue = nextFreeTicketMicros; double storedPermitsToSpend = min(requiredPermits, this.storedPermits); double freshPermits = requiredPermits - storedPermitsToSpend; long waitMicros = storedPermitsToWaitTime(this.storedPermits, storedPermitsToSpend) + (long) (freshPermits * stableIntervalMicros); this.nextFreeTicketMicros = LongMath.saturatedAdd(nextFreeTicketMicros, waitMicros); this.storedPermits -= storedPermitsToSpend; return returnValue; } /** * Translates a specified portion of our currently stored permits which we want to spend/acquire, * into a throttling time. Conceptually, this evaluates the integral of the underlying function we * use, for the range of [(storedPermits - permitsToTake), storedPermits]. * * <p>This always holds: {@code 0 <= permitsToTake <= storedPermits} */ abstract long storedPermitsToWaitTime(double storedPermits, double permitsToTake); /** * Returns the number of microseconds during cool down that we have to wait to get a new permit. */ abstract double coolDownIntervalMicros(); /** Updates {@code storedPermits} and {@code nextFreeTicketMicros} based on the current time. */ void resync(long nowMicros) { // if nextFreeTicket is in the past, resync to now if (nowMicros > nextFreeTicketMicros) { double newPermits = (nowMicros - nextFreeTicketMicros) / coolDownIntervalMicros(); storedPermits = min(maxPermits, storedPermits + newPermits); nextFreeTicketMicros = nowMicros; } } }
SmoothBursty
java
quarkusio__quarkus
tcks/microprofile-rest-client-reactive/src/test/java/io/quarkus/tck/restclient/cdi/CDIInterceptorTest.java
{ "start": 790, "end": 2793 }
class ____ extends Arquillian { @Inject @RestClient private ClientWithURIAndInterceptor client; @Deployment public static WebArchive createDeployment() { String simpleName = CDIInterceptorTest.class.getSimpleName(); JavaArchive jar = ShrinkWrap.create(JavaArchive.class, simpleName + ".jar") .addClasses(ClientWithURIAndInterceptor.class, Loggable.class, LoggableInterceptor.class, ReturnWithURLRequestFilter.class) .addAsManifestResource(new StringAsset( "<beans xmlns=\"http://java.sun.com/xml/ns/javaee\"" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:schemaLocation=\"" + " http://java.sun.com/xml/ns/javaee" + " http://java.sun.com/xml/ns/javaee/beans_1_0.xsd\">" + " <interceptors>" + " <class>io.quarkus.tck.restclient.cdi.LoggableInterceptor</class>" + " </interceptors>" + "</beans>"), "beans.xml"); return ShrinkWrap.create(WebArchive.class, simpleName + ".war") .addAsLibrary(jar) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } @AfterTest public void cleanUp() { LoggableInterceptor.reset(); } @Test public void testInterceptorInvoked() throws Exception { String expectedResponse = "GET http://localhost:5017/myBaseUri/hello"; assertEquals(client.get(), expectedResponse); assertTrue(ClientWithURIAndInterceptor.class.isAssignableFrom(LoggableInterceptor.getInvocationClass()), "Invalid declaring
CDIInterceptorTest
java
apache__camel
components/camel-bean/src/main/java/org/apache/camel/component/bean/BeanPropertiesFunction.java
{ "start": 1231, "end": 2500 }
class ____ implements PropertiesFunction, CamelContextAware { private CamelContext camelContext; @Override public String getName() { return "bean"; } @Override public String apply(String remainder) { if (StringHelper.countChar(remainder, '.') != 1 || remainder.startsWith(".") || remainder.endsWith(".")) { throw new IllegalArgumentException("BeanName and methodName should be separated by a dot."); } String[] beanNameAndMethodName = remainder.split("\\."); String beanName = beanNameAndMethodName[0]; String methodName = beanNameAndMethodName[1]; Object bean = CamelContextHelper.mandatoryLookup(camelContext, beanName); String answer = ""; try { answer += camelContext.getTypeConverter().convertTo(String.class, ObjectHelper.invokeMethodSafe(methodName, bean)); } catch (Exception e) { throw RuntimeCamelException.wrapRuntimeCamelException(e); } return answer; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public CamelContext getCamelContext() { return camelContext; } }
BeanPropertiesFunction
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/collection/spi/PersistentMap.java
{ "start": 12616, "end": 12936 }
class ____ implements DelayedOperation<E> { @Override public void operate() { map.clear(); } @Override public E getAddedInstance() { return null; } @Override public E getOrphan() { throw new UnsupportedOperationException( "queued clear cannot be used with orphan delete" ); } } abstract
Clear
java
spring-projects__spring-security
crypto/src/main/java/org/springframework/security/crypto/password/PasswordEncoderUtils.java
{ "start": 930, "end": 1570 }
class ____ { private PasswordEncoderUtils() { } /** * Constant time comparison to prevent against timing attacks. * @param expected * @param actual * @return */ static boolean equals(String expected, @Nullable String actual) { byte[] expectedBytes = bytesUtf8(expected); byte[] actualBytes = bytesUtf8(actual); return MessageDigest.isEqual(expectedBytes, actualBytes); } private static byte @Nullable [] bytesUtf8(@Nullable String s) { // need to check if Utf8.encode() runs in constant time (probably not). // This may leak length of string. return (s != null) ? Utf8.encode(s) : null; } }
PasswordEncoderUtils
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/RemoveFromClusterNodeLabelsResponsePBImpl.java
{ "start": 1153, "end": 2349 }
class ____ extends RemoveFromClusterNodeLabelsResponse { RemoveFromClusterNodeLabelsResponseProto proto = RemoveFromClusterNodeLabelsResponseProto.getDefaultInstance(); RemoveFromClusterNodeLabelsResponseProto.Builder builder = null; boolean viaProto = false; public RemoveFromClusterNodeLabelsResponsePBImpl() { builder = RemoveFromClusterNodeLabelsResponseProto.newBuilder(); } public RemoveFromClusterNodeLabelsResponsePBImpl( RemoveFromClusterNodeLabelsResponseProto proto) { this.proto = proto; viaProto = true; } public RemoveFromClusterNodeLabelsResponseProto getProto() { proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } @Override public int hashCode() { return getProto().hashCode(); } @Override public boolean equals(Object other) { if (other == null) return false; if (other.getClass().isAssignableFrom(this.getClass())) { return this.getProto().equals(this.getClass().cast(other).getProto()); } return false; } @Override public String toString() { return TextFormat.shortDebugString(getProto()); } }
RemoveFromClusterNodeLabelsResponsePBImpl
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java
{ "start": 24105, "end": 24901 }
class ____ { public void foo(Suit suit) { switch (suit) { case HEART: System.out.println("heart"); if (true) { break; } case DIAMOND: break; case SPADE: case CLUB: System.out.println("everything else"); } } } """) .setArgs("-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion") .doTest(); } @Test public void switchByEnumWithLambda_noError() { helper .addSourceLines( "Test.java", """ import java.util.function.Function;
Test
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java
{ "start": 4160, "end": 4397 }
class ____ implements Converter<Long, Calendar> { @Override public Calendar convert(Long source) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(source); return calendar; } } }
LongToCalendarConverter