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
google__dagger
javatests/dagger/internal/codegen/OptionalBindingTest.java
{ "start": 971, "end": 1650 }
class ____ { @Parameters(name = "{0}") public static ImmutableList<Object[]> parameters() { return CompilerMode.TEST_PARAMETERS; } private final CompilerMode compilerMode; public OptionalBindingTest(CompilerMode compilerMode) { this.compilerMode = compilerMode; } @Test public void provideExplicitOptionalInParent_AndBindsOptionalOfInChild() { Source parent = CompilerTests.javaSource( "test.Parent", "package test;", "", "import dagger.Component;", "import java.util.Optional;", "", "@Component(modules = ParentModule.class)", "
OptionalBindingTest
java
quarkusio__quarkus
integration-tests/hibernate-validator-resteasy-reactive/src/main/java/io/quarkus/it/hibernate/validator/restclient/server/ServerResource.java
{ "start": 342, "end": 692 }
class ____ { @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String doSomething(String parameter) { return parameter; } @GET @Produces(MediaType.APPLICATION_JSON) public RestClientEntity doSomething() { return new RestClientEntity(1, "aa"); } }
ServerResource
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerAbsolutePathDefaultMoveTest.java
{ "start": 1218, "end": 2305 }
class ____ extends ContextTestSupport { private static final String TEST_FILE_NAME = "paris" + UUID.randomUUID() + ".txt"; @Test public void testConsumeFromAbsolutePath() throws Exception { MockEndpoint mock = getMockEndpoint("mock:report"); mock.expectedBodiesReceived("Hello Paris"); mock.expectedFileExists(testFile(".camel/" + TEST_FILE_NAME)); Awaitility.await() .atMost(5, TimeUnit.SECONDS) .pollDelay(250, TimeUnit.MILLISECONDS) .untilAsserted(() -> { template.sendBodyAndHeader(fileUri(), "Hello Paris", Exchange.FILE_NAME, TEST_FILE_NAME); assertMockEndpointsSatisfied(); }); mock.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(fileUri("?initialDelay=0&delay=10")).convertBodyTo(String.class).to("mock:report"); } }; } }
FileConsumerAbsolutePathDefaultMoveTest
java
quarkusio__quarkus
extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/MissingP12KeyStoreFromClassPathTest.java
{ "start": 823, "end": 1614 }
class ____ { private static final String configuration = """ quarkus.tls.key-store.p12.path=/certs/missing.p12 quarkus.tls.key-store.p12.password=password """; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .add(new StringAsset(configuration), "application.properties")) .assertException(t -> { assertThat(t.getMessage()).contains("default", "P12", "file", "missing.p12"); }); @Test void test() throws KeyStoreException, CertificateParsingException { fail("Should not be called as the extension should fail before."); } }
MissingP12KeyStoreFromClassPathTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/accessibility/referenced/Source.java
{ "start": 248, "end": 538 }
class ____ { private ReferencedSource referencedSource; public ReferencedSource getReferencedSource() { return referencedSource; } public void setReferencedSource( ReferencedSource referencedSource ) { this.referencedSource = referencedSource; } }
Source
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/data/DecimalDataUtils.java
{ "start": 1484, "end": 10637 }
class ____ { private static final MathContext MC_DIVIDE = new MathContext(38, RoundingMode.HALF_UP); public static final DecimalType DECIMAL_SYSTEM_DEFAULT = new DecimalType(DecimalType.MAX_PRECISION, 18); public static double doubleValue(DecimalData decimal) { if (decimal.isCompact()) { return ((double) decimal.longVal) / POW10[decimal.scale]; } else { return decimal.decimalVal.doubleValue(); } } /** * Returns the signum function of this decimal. (The return value is -1 if this decimal is * negative; 0 if this decimal is zero; and 1 if this decimal is positive.) * * @return the signum function of this decimal. */ public static int signum(DecimalData decimal) { if (decimal.isCompact()) { return Long.signum(decimal.toUnscaledLong()); } else { return decimal.toBigDecimal().signum(); } } public static DecimalData negate(DecimalData decimal) { if (decimal.isCompact()) { return new DecimalData(decimal.precision, decimal.scale, -decimal.longVal, null); } else { return new DecimalData( decimal.precision, decimal.scale, -1, decimal.decimalVal.negate()); } } public static DecimalData abs(DecimalData decimal) { if (decimal.isCompact()) { if (decimal.longVal >= 0) { return decimal; } else { return new DecimalData(decimal.precision, decimal.scale, -decimal.longVal, null); } } else { if (decimal.decimalVal.signum() >= 0) { return decimal; } else { return new DecimalData( decimal.precision, decimal.scale, -1, decimal.decimalVal.negate()); } } } // floor()/ceil() preserve precision, but set scale to 0. // note that result may exceed the original precision. public static DecimalData floor(DecimalData decimal) { BigDecimal bd = decimal.toBigDecimal().setScale(0, RoundingMode.FLOOR); return fromBigDecimal(bd, bd.precision(), 0); } public static DecimalData ceil(DecimalData decimal) { BigDecimal bd = decimal.toBigDecimal().setScale(0, RoundingMode.CEILING); return fromBigDecimal(bd, bd.precision(), 0); } public static DecimalData add(DecimalData v1, DecimalData v2, int precision, int scale) { if (v1.isCompact() && v2.isCompact() && v1.scale == v2.scale && DecimalData.isCompact(precision)) { assert scale == v1.scale; // no need to rescale try { long ls = Math.addExact(v1.longVal, v2.longVal); // checks overflow return new DecimalData(precision, scale, ls, null); } catch (ArithmeticException e) { // overflow, fall through } } BigDecimal bd = v1.toBigDecimal().add(v2.toBigDecimal()); return fromBigDecimal(bd, precision, scale); } public static DecimalData subtract(DecimalData v1, DecimalData v2, int precision, int scale) { if (v1.isCompact() && v2.isCompact() && v1.scale == v2.scale && DecimalData.isCompact(precision)) { assert scale == v1.scale; // no need to rescale try { long ls = Math.subtractExact(v1.longVal, v2.longVal); // checks overflow return new DecimalData(precision, scale, ls, null); } catch (ArithmeticException e) { // overflow, fall through } } BigDecimal bd = v1.toBigDecimal().subtract(v2.toBigDecimal()); return fromBigDecimal(bd, precision, scale); } public static DecimalData multiply(DecimalData v1, DecimalData v2, int precision, int scale) { BigDecimal bd = v1.toBigDecimal().multiply(v2.toBigDecimal()); return fromBigDecimal(bd, precision, scale); } public static DecimalData divide(DecimalData v1, DecimalData v2, int precision, int scale) { BigDecimal bd = v1.toBigDecimal().divide(v2.toBigDecimal(), MC_DIVIDE); return fromBigDecimal(bd, precision, scale); } public static DecimalData mod(DecimalData v1, DecimalData v2, int precision, int scale) { BigDecimal bd = v1.toBigDecimal().remainder(v2.toBigDecimal(), MC_DIVIDE); return fromBigDecimal(bd, precision, scale); } /** * Returns a {@code DecimalData} whose value is the integer part of the quotient {@code (this / * divisor)} rounded down. * * @param value value by which this {@code DecimalData} is to be divided. * @param divisor value by which this {@code DecimalData} is to be divided. * @return The integer part of {@code this / divisor}. * @throws ArithmeticException if {@code divisor==0} */ public static DecimalData divideToIntegralValue( DecimalData value, DecimalData divisor, int precision, int scale) { BigDecimal bd = value.toBigDecimal().divideToIntegralValue(divisor.toBigDecimal()); return fromBigDecimal(bd, precision, scale); } // cast decimal to integral or floating data types, by SQL standard. // to cast to integer, rounding-DOWN is performed, and overflow will just return null. // to cast to floats, overflow will not happen, because precision<=38. public static long castToIntegral(DecimalData dec) { BigDecimal bd = dec.toBigDecimal(); // rounding down. This is consistent with float=>int, // and consistent with SQLServer, Spark. bd = bd.setScale(0, RoundingMode.DOWN); return bd.longValue(); } public static DecimalData castToDecimal(DecimalData dec, int precision, int scale) { return fromBigDecimal(dec.toBigDecimal(), precision, scale); } public static DecimalData castFrom(DecimalData dec, int precision, int scale) { return fromBigDecimal(dec.toBigDecimal(), precision, scale); } public static DecimalData castFrom(String string, int precision, int scale) { return fromBigDecimal(new BigDecimal(string), precision, scale); } public static DecimalData castFrom(double val, int p, int s) { return fromBigDecimal(BigDecimal.valueOf(val), p, s); } public static DecimalData castFrom(long val, int p, int s) { return fromBigDecimal(BigDecimal.valueOf(val), p, s); } public static boolean castToBoolean(DecimalData dec) { return dec.toBigDecimal().compareTo(BigDecimal.ZERO) != 0; } /** * SQL <code>SIGN</code> operator applied to BigDecimal values. preserve precision and scale. */ public static DecimalData sign(DecimalData b0) { if (b0.isCompact()) { return new DecimalData(b0.precision, b0.scale, signum(b0) * POW10[b0.scale], null); } else { return fromBigDecimal(BigDecimal.valueOf(signum(b0)), b0.precision, b0.scale); } } public static int compare(DecimalData b1, DecimalData b2) { return b1.compareTo(b2); } public static int compare(DecimalData b1, long n2) { if (!b1.isCompact()) { return b1.decimalVal.compareTo(BigDecimal.valueOf(n2)); } if (b1.scale == 0) { return Long.compare(b1.longVal, n2); } long i1 = b1.longVal / POW10[b1.scale]; if (i1 == n2) { long l2 = n2 * POW10[b1.scale]; // won't overflow return Long.compare(b1.longVal, l2); } else { return i1 > n2 ? +1 : -1; } } public static int compare(DecimalData b1, double n2) { return Double.compare(doubleValue(b1), n2); } public static int compare(long n1, DecimalData b2) { return -compare(b2, n1); } public static int compare(double n1, DecimalData b2) { return -compare(b2, n1); } /** SQL <code>ROUND</code> operator applied to BigDecimal values. */ public static DecimalData sround(DecimalData b0, int r) { if (r >= b0.scale) { return b0; } BigDecimal b2 = b0.toBigDecimal() .movePointRight(r) .setScale(0, RoundingMode.HALF_UP) .movePointLeft(r); int p = b0.precision; int s = b0.scale; if (r < 0) { return fromBigDecimal(b2, Math.min(38, 1 + p - s), 0); } else { // 0 <= r < s return fromBigDecimal(b2, 1 + p - s + r, r); } } public static long power10(int n) { return POW10[n]; } public static boolean is32BitDecimal(int precision) { return precision <= MAX_INT_DIGITS; } public static boolean is64BitDecimal(int precision) { return precision <= MAX_LONG_DIGITS && precision > MAX_INT_DIGITS; } public static boolean isByteArrayDecimal(int precision) { return precision > MAX_LONG_DIGITS; } }
DecimalDataUtils
java
quarkusio__quarkus
extensions/cache/runtime/src/main/java/io/quarkus/cache/CacheManager.java
{ "start": 1020, "end": 1460 }
interface ____ { /** * Gets a collection of all cache names. * * @return names of all caches */ Collection<String> getCacheNames(); /** * Gets the cache identified by the given name. * * @param name cache name * @return an {@link Optional} containing the identified cache if it exists, or an empty {@link Optional} otherwise */ Optional<Cache> getCache(String name); }
CacheManager
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire.java
{ "start": 1264, "end": 1468 }
class ____ extends AbstractDTO { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } } }
MyDTO
java
elastic__elasticsearch
x-pack/plugin/sql/jdbc/src/main/java/org/elasticsearch/xpack/sql/jdbc/JdbcDateUtils.java
{ "start": 753, "end": 900 }
class ____ code * from {@code org.elasticsearch.xpack.sql.util.DateUtils} and {@code org.elasticsearch.xpack.sql.proto.StringUtils}. */ final
borrows
java
apache__camel
dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/IngressTrait.java
{ "start": 1857, "end": 5284 }
class ____ extends BaseTrait { public static final int IngressTrait = 2400; public static final String DEFAULT_INGRESS_HOST = ""; public static final String DEFAULT_INGRESS_PATH = "/"; public static final String DEFAULT_INGRESS_CLASS_NAME = "nginx"; public static final Ingress.PathType DEFAULT_INGRESS_PATH_TYPE = Ingress.PathType.PREFIX; public IngressTrait() { super("ingress", IngressTrait); } @Override public boolean configure(Traits traitConfig, TraitContext context) { if (context.getIngress().isPresent()) { return false; } // must be explicitly enabled if (traitConfig.getIngress() == null || !Optional.ofNullable(traitConfig.getIngress().getEnabled()).orElse(false)) { return false; } // configured service return context.getService().isPresent(); } @Override public void apply(Traits traitConfig, TraitContext context) { Ingress ingressTrait = Optional.ofNullable(traitConfig.getIngress()).orElseGet(Ingress::new); Container containerTrait = Optional.ofNullable(traitConfig.getContainer()).orElseGet(Container::new); IngressBuilder ingressBuilder = new IngressBuilder(); ingressBuilder.withNewMetadata() .withName(context.getName()) .endMetadata(); if (ingressTrait.getAnnotations() != null) { ingressBuilder.editMetadata().withAnnotations(ingressTrait.getAnnotations()).endMetadata(); } HTTPIngressPath path = new HTTPIngressPathBuilder() .withPath(Optional.ofNullable(ingressTrait.getPath()).orElse(DEFAULT_INGRESS_PATH)) .withPathType(Optional.ofNullable(ingressTrait.getPathType()).orElse(DEFAULT_INGRESS_PATH_TYPE).getValue()) .withNewBackend() .withNewService() .withName(context.getName()) .withNewPort() .withName(Optional.ofNullable(containerTrait.getServicePortName()).orElse(DEFAULT_CONTAINER_PORT_NAME)) .endPort() .endService() .endBackend() .build(); var ingressHost = Optional.ofNullable(ingressTrait.getHost()).orElse(DEFAULT_INGRESS_HOST); IngressRule rule = new IngressRuleBuilder() .withHost(ingressHost) .withNewHttp() .withPaths(path) .endHttp() .build(); ingressBuilder .withNewSpec() .withIngressClassName(Optional.ofNullable(ingressTrait.getIngressClass()).orElse(DEFAULT_INGRESS_CLASS_NAME)) .withRules(rule) .endSpec(); if (ingressTrait.getTlsSecretName() != null) { if (ingressTrait.getTlsHosts() == null && !ingressHost.isEmpty()) { ingressTrait.setTlsHosts(List.of(ingressHost)); } IngressTLS tls = new IngressTLSBuilder() .withHosts(ingressTrait.getTlsHosts()) .withSecretName(ingressTrait.getTlsSecretName()) .build(); ingressBuilder.editSpec().withTls(tls).endSpec(); } context.add(ingressBuilder); } @Override public boolean accept(ClusterType clusterType) { return ClusterType.OPENSHIFT != clusterType; } }
IngressTrait
java
dropwizard__dropwizard
dropwizard-validation/src/main/java/io/dropwizard/validation/InterpolationHelper.java
{ "start": 472, "end": 1750 }
class ____ { /** * A constant representing the '&#123;' character. */ public static final char BEGIN_TERM = '{'; /** * A constant representing the '&#125;' character. */ public static final char END_TERM = '}'; /** * A constant representing the '&#36;' character. */ public static final char EL_DESIGNATOR = '$'; /** * A constant representing the '&#92;' character. */ public static final char ESCAPE_CHARACTER = '\\'; private static final Pattern ESCAPE_MESSAGE_PARAMETER_PATTERN = Pattern.compile("([\\" + ESCAPE_CHARACTER + BEGIN_TERM + END_TERM + EL_DESIGNATOR + "])"); private InterpolationHelper() { } /** * Escapes a string with the {@link #ESCAPE_MESSAGE_PARAMETER_PATTERN}. * * @param messageParameter the string to escape * @return the escaped string or {@code null}, if the input was {@code null} */ @Nullable public static String escapeMessageParameter(@Nullable String messageParameter) { if (messageParameter == null) { return null; } return ESCAPE_MESSAGE_PARAMETER_PATTERN.matcher(messageParameter).replaceAll(Matcher.quoteReplacement(String.valueOf(ESCAPE_CHARACTER)) + "$1"); } }
InterpolationHelper
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/primary/FindSingleByTypeTest.java
{ "start": 1403, "end": 3186 }
class ____ extends ContextTestSupport { private AbstractApplicationContext applicationContext; @Override @BeforeEach public void setUp() throws Exception { super.setUp(); if (context != null) { context.stop(); } applicationContext = new ClassPathXmlApplicationContext("org/apache/camel/spring/primary/findBySingle.xml"); context = applicationContext.getBean("myCamel", ModelCamelContext.class); } @Override @AfterEach public void tearDown() throws Exception { // we're done so let's properly close the application context IOHelper.close(applicationContext); super.tearDown(); } @Test public void testFindSingle() { // should find primary Customer c = context.getRegistry().findSingleByType(Customer.class); Assertions.assertNotNull(c); Assertions.assertEquals("Donald", c.name()); // should not find anything Object o = context.getRegistry().findSingleByType(UuidGenerator.class); Assertions.assertNull(o); } @Test public void testFindByType() { // should find primary Set<Customer> set = context.getRegistry().findByType(Customer.class); // should find both beans Assertions.assertEquals(2, set.size()); } @Test public void testFindSingleMandatory() { // should find primary Customer c = context.getRegistry().mandatoryFindSingleByType(Customer.class); Assertions.assertEquals("Donald", c.name()); // should not find anything Assertions.assertThrows(NoSuchBeanTypeException.class, () -> context.getRegistry().mandatoryFindSingleByType(UuidGenerator.class)); } }
FindSingleByTypeTest
java
quarkusio__quarkus
independent-projects/bootstrap/core/src/test/java/io/quarkus/bootstrap/resolver/test/ConditionalDependenciesDirectDependencyOnTransitiveDeploymentArtifactTestCase.java
{ "start": 267, "end": 2840 }
class ____ extends CollectDependenciesBase { @Override protected void setupDependencies() { final TsQuarkusExt quarkusCore = new TsQuarkusExt("quarkus-core"); install(quarkusCore); TsArtifact nettyNioClient = TsArtifact.jar("netty-nio-client"); final TsQuarkusExt nettyClientInternalExt = new TsQuarkusExt("netty-client-internal"); nettyClientInternalExt.addDependency(quarkusCore); nettyClientInternalExt.getRuntime().addDependency(nettyNioClient, true); nettyClientInternalExt.setDependencyCondition(nettyNioClient); install(nettyClientInternalExt, false); addCollectedDep(nettyClientInternalExt.getRuntime(), DependencyFlags.RUNTIME_CP | DependencyFlags.DEPLOYMENT_CP | DependencyFlags.RUNTIME_EXTENSION_ARTIFACT); addCollectedDeploymentDep(nettyClientInternalExt.getDeployment()); final TsQuarkusExt commonExt = new TsQuarkusExt("common"); commonExt.addDependency(quarkusCore); commonExt.getRuntime().addDependency(nettyNioClient, true); commonExt.getRuntime().addDependency(nettyClientInternalExt.getRuntime(), true); commonExt.getDeployment().addDependency(nettyClientInternalExt.getDeployment(), true); commonExt.setConditionalDeps(nettyClientInternalExt); install(commonExt, false); addCollectedDep(commonExt.getRuntime(), DependencyFlags.RUNTIME_CP | DependencyFlags.DEPLOYMENT_CP | DependencyFlags.RUNTIME_EXTENSION_ARTIFACT); addCollectedDeploymentDep(commonExt.getDeployment()); final TsQuarkusExt sqsExt = new TsQuarkusExt("sqs"); sqsExt.addDependency(quarkusCore); sqsExt.getRuntime().addDependency(commonExt.getRuntime()); sqsExt.getRuntime().addDependency(nettyNioClient, true); sqsExt.getDeployment().addFirstDependency(commonExt.getDeployment()); addCollectedDep(sqsExt.getRuntime(), DependencyFlags.RUNTIME_CP | DependencyFlags.DEPLOYMENT_CP | DependencyFlags.RUNTIME_EXTENSION_ARTIFACT); addCollectedDeploymentDep(sqsExt.getDeployment()); final TsQuarkusExt messagingSqsExt = new TsQuarkusExt("messaging-sqs"); messagingSqsExt.addDependency(quarkusCore); messagingSqsExt.addDependency(sqsExt); messagingSqsExt.getDeployment().addDependency(commonExt.getDeployment()); // this line breaks it installAsDep(messagingSqsExt); installAsDep(nettyNioClient); } }
ConditionalDependenciesDirectDependencyOnTransitiveDeploymentArtifactTestCase
java
spring-projects__spring-boot
module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryTracingProperties.java
{ "start": 997, "end": 1194 }
class ____ { /** * Span export configuration. */ private final Export export = new Export(); public Export getExport() { return this.export; } public static
OpenTelemetryTracingProperties
java
apache__dubbo
dubbo-plugin/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/MethodValidated.java
{ "start": 1535, "end": 1600 }
interface ____ { Class<?>[] value() default {}; }
MethodValidated
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/schedulers/Schedulers.java
{ "start": 17964, "end": 23777 }
class ____ been initialized, you can override the returned {@code Scheduler} instance * via the {@link RxJavaPlugins#setSingleSchedulerHandler(io.reactivex.rxjava3.functions.Function)} method. * <p> * It is possible to create a fresh instance of this scheduler with a custom {@link ThreadFactory}, via the * {@link RxJavaPlugins#createSingleScheduler(ThreadFactory)} method. Note that such custom * instances require a manual call to {@link Scheduler#shutdown()} to allow the JVM to exit or the * (J2EE) container to unload properly. * <p>Operators on the base reactive classes that use this scheduler are marked with the * &#64;{@link io.reactivex.rxjava3.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.rxjava3.annotations.SchedulerSupport#SINGLE SINGLE}) * annotation. * @return a {@code Scheduler} that shares a single backing thread. * @since 2.0 */ @NonNull public static Scheduler single() { return RxJavaPlugins.onSingleScheduler(SINGLE); } /** * Wraps an {@link Executor} into a new {@link Scheduler} instance and delegates {@code schedule()} * calls to it. * <p> * If the provided executor doesn't support any of the more specific standard Java executor * APIs, tasks scheduled by this scheduler can't be interrupted when they are * executing but only prevented from running prior to that. In addition, tasks scheduled with * a time delay or periodically will use the {@link #single()} scheduler for the timed waiting * before posting the actual task to the given executor. * <p> * Tasks submitted to the {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} of this {@code Scheduler} are also not interruptible. Use the * {@link #from(Executor, boolean)} overload to enable task interruption via this wrapper. * <p> * If the provided executor supports the standard Java {@link ExecutorService} API, * tasks scheduled by this scheduler can be cancelled/interrupted by calling * {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with * a time delay or periodically will use the {@link #single()} scheduler for the timed waiting * before posting the actual task to the given executor. * <p> * If the provided executor supports the standard Java {@link ScheduledExecutorService} API, * tasks scheduled by this scheduler can be cancelled/interrupted by calling * {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with * a time delay or periodically will use the provided executor. Note, however, if the provided * {@code ScheduledExecutorService} instance is not single threaded, tasks scheduled * with a time delay close to each other may end up executing in different order than * the original schedule() call was issued. This limitation may be lifted in a future patch. * <p> * The implementation of the Worker of this wrapper {@code Scheduler} is eager and will execute as many * non-delayed tasks as it can, which may result in a longer than expected occupation of a * thread of the given backing {@code Executor}. In other terms, it does not allow per-{@link Runnable} fairness * in case the worker runs on a shared underlying thread of the {@code Executor}. * See {@link #from(Executor, boolean, boolean)} to create a wrapper that uses the underlying {@code Executor} * more fairly. * <p> * Starting, stopping and restarting this scheduler is not supported (no-op) and the provided * executor's lifecycle must be managed externally: * <pre><code> * ExecutorService exec = Executors.newSingleThreadedExecutor(); * try { * Scheduler scheduler = Schedulers.from(exec); * Flowable.just(1) * .subscribeOn(scheduler) * .map(v -&gt; v + 1) * .observeOn(scheduler) * .blockingSubscribe(System.out::println); * } finally { * exec.shutdown(); * } * </code></pre> * <p> * Note that the provided {@code Executor} should avoid throwing a {@link RejectedExecutionException} * (for example, by shutting it down prematurely or using a bounded-queue {@code ExecutorService}) * because such circumstances prevent RxJava from progressing flow-related activities correctly. * If the {@link Executor#execute(Runnable)} or {@link ExecutorService#submit(Callable)} throws, * the {@code RejectedExecutionException} is routed to the global error handler via * {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-related problems, it is recommended * all flows using the returned {@code Scheduler} to be canceled/disposed before the underlying * {@code Executor} is shut down. To avoid problems due to the {@code Executor} having a bounded-queue, * it is recommended to rephrase the flow to utilize backpressure as the means to limit outstanding work. * <p> * This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} instances, although * not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or * execute those tasks "unexpectedly". * <p> * Note that this method returns a new {@code Scheduler} instance, even for the same {@code Executor} instance. * <p> * It is possible to wrap an {@code Executor} into a {@code Scheduler} without triggering the initialization of all the * standard schedulers by using the {@link RxJavaPlugins#createExecutorScheduler(Executor, boolean, boolean)} method * before the {@code Schedulers}
has
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/transaction/batch/AbstractBatchingTest.java
{ "start": 1300, "end": 1950 }
class ____ extends BatchBuilderImpl { private final boolean throwError; public BatchBuilderLocal() { this( false ); } public BatchBuilderLocal(boolean throwError) { super( 50 ); this.throwError = throwError; } @Override public Batch buildBatch( BatchKey key, Integer explicitBatchSize, Supplier<PreparedStatementGroup> statementGroupSupplier, JdbcCoordinator jdbcCoordinator) { batchWrapper = new BatchWrapper( throwError, super.buildBatch( key, explicitBatchSize, statementGroupSupplier, jdbcCoordinator ), jdbcCoordinator ); return batchWrapper; } } public static
BatchBuilderLocal
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/async/impl/TestNMClientAsync.java
{ "start": 32276, "end": 32746 }
class ____ extends NMClientAsyncImpl { private CyclicBarrier barrierA; private CyclicBarrier barrierB; protected MockNMClientAsync2(CyclicBarrier barrierA, CyclicBarrier barrierB, CyclicBarrier barrierC) throws YarnException, IOException { super(MockNMClientAsync2.class.getName(), mockNMClient(0), new TestCallbackHandler2(barrierC)); this.barrierA = barrierA; this.barrierB = barrierB; } private
MockNMClientAsync2
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/PendingTaskManagerId.java
{ "start": 960, "end": 1204 }
class ____ extends AbstractID { private static final long serialVersionUID = 1L; private PendingTaskManagerId() {} public static PendingTaskManagerId generate() { return new PendingTaskManagerId(); } }
PendingTaskManagerId
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/conditional/GreatestSerializationTests.java
{ "start": 564, "end": 811 }
class ____ extends AbstractVarargsSerializationTests<Greatest> { @Override protected Greatest create(Source source, Expression first, List<Expression> rest) { return new Greatest(source, first, rest); } }
GreatestSerializationTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/persister/internal/PersisterFactoryImpl.java
{ "start": 1212, "end": 5375 }
class ____ implements PersisterFactory, ServiceRegistryAwareService { /** * The constructor signature for {@link EntityPersister} implementations */ public static final Class<?>[] ENTITY_PERSISTER_CONSTRUCTOR_ARGS = new Class[] { PersistentClass.class, EntityDataAccess.class, NaturalIdDataAccess.class, RuntimeModelCreationContext.class }; /** * The constructor signature for {@link CollectionPersister} implementations */ public static final Class<?>[] COLLECTION_PERSISTER_CONSTRUCTOR_ARGS = new Class[] { Collection.class, CollectionDataAccess.class, RuntimeModelCreationContext.class }; private PersisterClassResolver persisterClassResolver; @Override public void injectServices(ServiceRegistryImplementor serviceRegistry) { this.persisterClassResolver = serviceRegistry.getService( PersisterClassResolver.class ); } @Override public EntityPersister createEntityPersister( PersistentClass entityBinding, EntityDataAccess entityCacheAccessStrategy, NaturalIdDataAccess naturalIdCacheAccessStrategy, RuntimeModelCreationContext creationContext) { final var persisterClass = persisterClassResolver.getEntityPersisterClass( entityBinding ); final var constructor = resolveEntityPersisterConstructor( persisterClass ); try { return constructor.newInstance( entityBinding, entityCacheAccessStrategy, naturalIdCacheAccessStrategy, creationContext ); } catch (MappingException e) { throw e; } catch (InvocationTargetException e) { final var target = e.getTargetException(); if ( target instanceof HibernateException hibernateException ) { throw hibernateException; } else { throw new MappingException( String.format( Locale.ROOT, "Could not instantiate persister %s (%s)", persisterClass.getName(), entityBinding.getEntityName() ), target ); } } catch (Exception e) { throw new MappingException( String.format( Locale.ROOT, "Could not instantiate persister %s (%s)", persisterClass.getName(), entityBinding.getEntityName() ), e ); } } private Constructor<? extends EntityPersister> resolveEntityPersisterConstructor(Class<? extends EntityPersister> persisterClass) { try { return persisterClass.getConstructor( ENTITY_PERSISTER_CONSTRUCTOR_ARGS ); } catch (NoSuchMethodException noConstructorException) { throw new MappingException( "Could not find appropriate constructor for " + persisterClass.getName(), noConstructorException ); } } @Override public CollectionPersister createCollectionPersister( Collection collectionBinding, @Nullable CollectionDataAccess cacheAccessStrategy, RuntimeModelCreationContext creationContext) { final var persisterClass = persisterClassResolver.getCollectionPersisterClass( collectionBinding ); final var constructor = resolveCollectionPersisterConstructor( persisterClass ); try { return constructor.newInstance( collectionBinding, cacheAccessStrategy, creationContext ); } catch (MappingException e) { throw e; } catch (InvocationTargetException e) { final Throwable target = e.getTargetException(); if ( target instanceof HibernateException hibernateException ) { throw hibernateException; } else { throw new MappingException( String.format( "Could not instantiate collection persister implementor `%s` for collection-role `%s`", persisterClass.getName(), collectionBinding.getRole() ), target ); } } catch (Exception e) { throw new MappingException( "Could not instantiate collection persister " + persisterClass.getName(), e ); } } private Constructor<? extends CollectionPersister> resolveCollectionPersisterConstructor(Class<? extends CollectionPersister> persisterClass) { try { return persisterClass.getConstructor( COLLECTION_PERSISTER_CONSTRUCTOR_ARGS ); } catch (NoSuchMethodException noConstructorException) { throw new MappingException( "Could not find appropriate constructor for " + persisterClass.getName(), noConstructorException ); } } }
PersisterFactoryImpl
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/enrich/EnrichLookupService.java
{ "start": 7729, "end": 8363 }
class ____ extends AbstractLookupService.Request { private final String matchType; private final String matchField; Request( String sessionId, String index, DataType inputDataType, String matchType, String matchField, Page inputPage, List<NamedExpression> extractFields, Source source ) { super(sessionId, index, index, inputDataType, inputPage, extractFields, source); this.matchType = matchType; this.matchField = matchField; } } protected static
Request
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/FetchGraphCollectionOrderByAndCriteriaJoinTest.java
{ "start": 8211, "end": 8917 }
class ____ { @Id Long id; Long ordinal; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") private Level2 parent; public Level3() { } public Level3(Level2 parent, Long id, Long ordinal) { this.parent = parent; this.id = id; this.ordinal = ordinal; parent.getChildren().add( this ); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Level2 getParent() { return parent; } public void setParent(Level2 parent) { this.parent = parent; } public Long getOrdinal() { return ordinal; } @Override public String toString() { return "Level3 #" + id + " $" + ordinal; } } }
Level3
java
apache__camel
components/camel-ai/camel-torchserve/src/test/java/org/apache/camel/component/torchserve/ManagementTest.java
{ "start": 1539, "end": 10229 }
class ____ extends TorchServeTestSupport { private static final String TEST_MODEL = "squeezenet1_1"; private static final String TEST_MODEL_VERSION = "1.0"; private static final String ADDED_MODEL_URL = "https://torchserve.pytorch.org/mar_files/mnist_v2.mar"; private static final String ADDED_MODEL = "mnist_v2"; private static final String ADDED_MODEL_VERSION = "2.0"; @Override protected CamelContext createCamelContext() throws Exception { var context = super.createCamelContext(); var component = context.getComponent("torchserve", TorchServeComponent.class); var configuration = component.getConfiguration(); configuration.setManagementAddress(mockServer.baseUrl()); return context; } @Test void testRegister() throws Exception { mockServer.stubFor(post(urlPathEqualTo("/models")) .willReturn(okJson("{ \"status\": \"registered\" }"))); var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().constant("registered"); template.sendBody("direct:register", null); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testScaleWorker() throws Exception { mockServer.stubFor(put(urlPathEqualTo("/models/" + ADDED_MODEL)) .willReturn(okJson("{ \"status\": \"processing\" }"))); var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().constant("processing"); template.sendBody("direct:scale-worker", null); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testScaleWorker_headers() throws Exception { mockServer.stubFor(put(urlPathEqualTo("/models/" + ADDED_MODEL)) .willReturn(okJson("{ \"status\": \"processing\" }"))); var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().constant("processing"); template.send("direct:scale-worker_headers", exchange -> { exchange.getMessage().setHeader(TorchServeConstants.MODEL_NAME, ADDED_MODEL); }); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testDescribe() throws Exception { var mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); template.sendBody("direct:list", null); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testDescribe_version() throws Exception { var mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); template.sendBody("direct:list", null); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testUnregister() throws Exception { mockServer.stubFor(delete("/models/" + ADDED_MODEL) .willReturn(okJson("{ \"status\": \"unregistered\" }"))); var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().constant("unregistered"); template.sendBody("direct:unregister", null); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testUnregister_headers() throws Exception { mockServer.stubFor(delete("/models/" + ADDED_MODEL) .willReturn(okJson("{ \"status\": \"unregistered\" }"))); var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().constant("unregistered"); template.send("direct:unregister_headers", exchange -> { exchange.getMessage().setHeader(TorchServeConstants.MODEL_NAME, ADDED_MODEL); }); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testUnregister_version() throws Exception { mockServer.stubFor(delete("/models/" + ADDED_MODEL + "/" + ADDED_MODEL_VERSION) .willReturn(okJson("{ \"status\": \"unregistered\" }"))); var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().constant("unregistered"); template.sendBody("direct:unregister_version", null); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testUnregister_versionHeaders() throws Exception { mockServer.stubFor(delete("/models/" + ADDED_MODEL + "/" + ADDED_MODEL_VERSION) .willReturn(okJson("{ \"status\": \"unregistered\" }"))); var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().constant("unregistered"); template.send("direct:unregister_headers", exchange -> { exchange.getMessage().setHeader(TorchServeConstants.MODEL_NAME, ADDED_MODEL); exchange.getMessage().setHeader(TorchServeConstants.MODEL_VERSION, ADDED_MODEL_VERSION); }); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testList() throws Exception { mockServer.stubFor(get(urlPathEqualTo("/models")) .willReturn(okJson( "{ \"models\": [ { \"modelName\": \"squeezenet1_1\", \"modelUrl\": \"squeezenet1_1.mar\" } ] }"))); var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().body(ModelList.class); template.sendBody("direct:list", null); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testSetDefault() throws Exception { mockServer.stubFor(put("/models/" + TEST_MODEL + "/" + TEST_MODEL_VERSION + "/set-default") .willReturn(okJson("{ \"status\": \"Default vesion succsesfully updated\" }"))); var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().constant("Default vesion succsesfully updated"); template.sendBody("direct:set-default", null); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testSetDefault_headers() throws Exception { mockServer.stubFor(put("/models/" + TEST_MODEL + "/" + TEST_MODEL_VERSION + "/set-default") .willReturn(okJson("{ \"status\": \"Default vesion succsesfully updated\" }"))); var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().constant("Default vesion succsesfully updated"); template.send("direct:set-default_headers", exchange -> { exchange.getMessage().setHeader(TorchServeConstants.MODEL_NAME, TEST_MODEL); exchange.getMessage().setHeader(TorchServeConstants.MODEL_VERSION, TEST_MODEL_VERSION); }); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:register") .toF("torchserve:management/register?url=%s", ADDED_MODEL_URL) .to("mock:result"); from("direct:scale-worker") .toF("torchserve:management/scale-worker?modelName=%s", ADDED_MODEL) .to("mock:result"); from("direct:scale-worker_headers") .to("torchserve:management/scale-worker") .to("mock:result"); from("direct:describe") .to("torchserve:management/describe") .to("mock:result"); from("direct:unregister") .toF("torchserve:management/unregister?modelName=%s", ADDED_MODEL) .to("mock:result"); from("direct:unregister_version") .toF("torchserve:management/unregister?modelName=%s&modelVersion=%s", ADDED_MODEL, ADDED_MODEL_VERSION) .to("mock:result"); from("direct:unregister_headers") .to("torchserve:management/unregister") .to("mock:result"); from("direct:list") .to("torchserve:management/list") .to("mock:result"); from("direct:set-default") .toF("torchserve:management/set-default?modelName=%s&modelVersion=%s", TEST_MODEL, TEST_MODEL_VERSION) .to("mock:result"); from("direct:set-default_headers") .to("torchserve:management/set-default") .to("mock:result"); } }; } }
ManagementTest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/BasicAuthTest.java
{ "start": 4019, "end": 4374 }
class ____ { @Route(path = "/open") void hello(RoutingContext context) { context.response().setStatusCode(200).end("ok"); } @Route(path = "/secured") @RolesAllowed("admin") void secure(RoutingContext context) { context.response().setStatusCode(200).end("ok"); } } }
Resource
java
spring-projects__spring-boot
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/exchanges/HttpExchange.java
{ "start": 7580, "end": 9827 }
class ____ { private final URI uri; private final @Nullable String remoteAddress; private final String method; private final Map<String, List<String>> headers; private Request(RecordableHttpRequest request, Set<Include> includes) { this.uri = request.getUri(); this.remoteAddress = (includes.contains(Include.REMOTE_ADDRESS)) ? request.getRemoteAddress() : null; this.method = request.getMethod(); this.headers = Collections.unmodifiableMap(filterHeaders(request.getHeaders(), includes)); } /** * Creates a fully-configured {@code Request} instance. Primarily for use by * {@link HttpExchangeRepository} implementations when recreating a request from a * persistent store. * @param uri the URI of the request * @param remoteAddress remote address from which the request was sent, if known * @param method the HTTP method of the request * @param headers the request headers */ public Request(URI uri, String remoteAddress, String method, Map<String, List<String>> headers) { this.uri = uri; this.remoteAddress = remoteAddress; this.method = method; this.headers = Collections.unmodifiableMap(new LinkedHashMap<>(headers)); } private Map<String, List<String>> filterHeaders(Map<String, List<String>> headers, Set<Include> includes) { HeadersFilter filter = new HeadersFilter(includes, Include.REQUEST_HEADERS); filter.excludeUnless(HttpHeaders.COOKIE, Include.COOKIE_HEADERS); filter.excludeUnless(HttpHeaders.AUTHORIZATION, Include.AUTHORIZATION_HEADER); return filter.apply(headers); } /** * Return the HTTP method requested. * @return the HTTP method */ public String getMethod() { return this.method; } /** * Return the URI requested. * @return the URI */ public URI getUri() { return this.uri; } /** * Return the request headers. * @return the request headers */ public Map<String, List<String>> getHeaders() { return this.headers; } /** * Return the remote address that made the request. * @return the remote address */ public @Nullable String getRemoteAddress() { return this.remoteAddress; } } /** * The response that finished the exchange. */ public static final
Request
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/network/Selector.java
{ "start": 49528, "end": 51380 }
class ____ implements ChannelMetadataRegistry { private CipherInformation cipherInformation; private ClientInformation clientInformation; @Override public void registerCipherInformation(final CipherInformation cipherInformation) { if (this.cipherInformation != null) { if (this.cipherInformation.equals(cipherInformation)) return; sensors.connectionsByCipher.decrement(this.cipherInformation); } this.cipherInformation = cipherInformation; sensors.connectionsByCipher.increment(cipherInformation); } @Override public CipherInformation cipherInformation() { return cipherInformation; } @Override public void registerClientInformation(final ClientInformation clientInformation) { if (this.clientInformation != null) { if (this.clientInformation.equals(clientInformation)) return; sensors.connectionsByClient.decrement(this.clientInformation); } this.clientInformation = clientInformation; sensors.connectionsByClient.increment(clientInformation); } @Override public ClientInformation clientInformation() { return clientInformation; } @Override public void close() { if (this.cipherInformation != null) { sensors.connectionsByCipher.decrement(this.cipherInformation); this.cipherInformation = null; } if (this.clientInformation != null) { sensors.connectionsByClient.decrement(this.clientInformation); this.clientInformation = null; } } }
SelectorChannelMetadataRegistry
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/DefaultApplicationContext.java
{ "start": 3276, "end": 4193 }
class ____ extends DefaultBeanContext implements ConfigurableApplicationContext, PropertyResolverDelegate { private final ApplicationContextConfiguration configuration; private final Environment environment; /** * True if the {@link #environment} was created by this context. */ private final boolean environmentManaged; /** * Construct a new ApplicationContext for the given environment name. * * @param environmentNames The environment names */ public DefaultApplicationContext(@NonNull String... environmentNames) { this(ClassPathResourceLoader.defaultLoader(DefaultApplicationContext.class.getClassLoader()), environmentNames); } /** * Construct a new ApplicationContext for the given environment name and classloader. * * @param environmentNames The environment names * @param resourceLoader The
DefaultApplicationContext
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/customize/DubboSpringInitCustomizerTest.java
{ "start": 1623, "end": 4685 }
class ____ { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); SysProps.setProperty("dubbo.registry.address", ZookeeperRegistryCenterConfig.getConnectionAddress()); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); SysProps.clear(); } @Test void testReloadSpringContext() { ClassPathXmlApplicationContext providerContext1 = null; ClassPathXmlApplicationContext providerContext2 = null; ApplicationModel applicationModel = new FrameworkModel().newApplication(); applicationModel.getDefaultModule(); try { // start spring context 1 ModuleModel moduleModel1 = applicationModel.newModule(); DubboSpringInitCustomizerHolder.get().addCustomizer(context -> { context.setModuleModel(moduleModel1); }); providerContext1 = new ClassPathXmlApplicationContext("dubbo-provider-v1.xml", getClass()); ModuleModel moduleModelFromSpring1 = providerContext1.getBean(ModuleModel.class); Assertions.assertSame(moduleModel1, moduleModelFromSpring1); String serviceKey1 = HelloService.class.getName() + ":1.0.0"; ServiceDescriptor serviceDescriptor1 = moduleModelFromSpring1.getServiceRepository().lookupService(serviceKey1); Assertions.assertNotNull(serviceDescriptor1); // close spring context 1 providerContext1.close(); Assertions.assertTrue(moduleModel1.isDestroyed()); Assertions.assertFalse(moduleModel1.getApplicationModel().isDestroyed()); providerContext1 = null; ModuleModel moduleModel2 = applicationModel.newModule(); DubboSpringInitCustomizerHolder.get().addCustomizer(context -> { context.setModuleModel(moduleModel2); }); // load spring context 2 providerContext2 = new ClassPathXmlApplicationContext("dubbo-provider-v2.xml", getClass()); ModuleModel moduleModelFromSpring2 = providerContext2.getBean(ModuleModel.class); Assertions.assertSame(moduleModel2, moduleModelFromSpring2); Assertions.assertNotSame(moduleModelFromSpring1, moduleModelFromSpring2); String serviceKey2 = HelloService.class.getName() + ":2.0.0"; ServiceDescriptor serviceDescriptor2 = moduleModelFromSpring2.getServiceRepository().lookupService(serviceKey2); Assertions.assertNotNull(serviceDescriptor2); Assertions.assertNotSame(serviceDescriptor1, serviceDescriptor2); providerContext2.close(); providerContext2 = null; } finally { if (providerContext1 != null) { providerContext1.close(); } if (providerContext2 != null) { providerContext2.close(); } applicationModel.destroy(); } } }
DubboSpringInitCustomizerTest
java
junit-team__junit5
junit-jupiter-params/src/main/java/org/junit/jupiter/params/provider/EnumArgumentsProvider.java
{ "start": 2570, "end": 3531 }
enum ____.".formatted( from, to)); return EnumSet.range(from, to); } @SuppressWarnings({ "unchecked", "rawtypes" }) private <E extends Enum<E>> Class<E> determineEnumClass(ParameterDeclarations parameters, EnumSource enumSource) { Class enumClass = enumSource.value(); if (enumClass.equals(NullEnum.class)) { enumClass = parameters.getFirst() // .map(ParameterDeclaration::getParameterType).map(parameterType -> { Preconditions.condition(Enum.class.isAssignableFrom(parameterType), () -> "First parameter must reference an Enum type (alternatively, use the annotation's 'value' attribute to specify the type explicitly): " + parameters.getSourceElementDescription()); return (Class<E>) parameterType; }).orElseThrow( () -> new PreconditionViolationException("There must be at least one declared parameter for " + parameters.getSourceElementDescription())); } return enumClass; } }
constants
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/connector/secrets/action/GetConnectorSecretResponseBWCSerializingTests.java
{ "start": 623, "end": 1837 }
class ____ extends AbstractBWCWireSerializationTestCase<GetConnectorSecretResponse> { @Override protected Writeable.Reader<GetConnectorSecretResponse> instanceReader() { return GetConnectorSecretResponse::new; } @Override protected GetConnectorSecretResponse createTestInstance() { return ConnectorSecretsTestUtils.getRandomGetConnectorSecretResponse(); } @Override protected GetConnectorSecretResponse mutateInstance(GetConnectorSecretResponse instance) throws IOException { String id = instance.id(); String value = instance.value(); switch (randomIntBetween(0, 1)) { case 0 -> id = randomValueOtherThan(id, () -> randomAlphaOfLengthBetween(1, 10)); case 1 -> value = randomValueOtherThan(value, () -> randomAlphaOfLengthBetween(1, 10)); default -> throw new AssertionError("Illegal randomisation branch"); } return new GetConnectorSecretResponse(id, value); } @Override protected GetConnectorSecretResponse mutateInstanceForVersion(GetConnectorSecretResponse instance, TransportVersion version) { return instance; } }
GetConnectorSecretResponseBWCSerializingTests
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/internals/ClusterResourceListeners.java
{ "start": 1007, "end": 2305 }
class ____ { private final List<ClusterResourceListener> clusterResourceListeners; public ClusterResourceListeners() { this.clusterResourceListeners = new ArrayList<>(); } /** * Add only if the candidate implements {@link ClusterResourceListener}. * @param candidate Object which might implement {@link ClusterResourceListener} */ public void maybeAdd(Object candidate) { if (candidate instanceof ClusterResourceListener) { clusterResourceListeners.add((ClusterResourceListener) candidate); } } /** * Add all items who implement {@link ClusterResourceListener} from the list. * @param candidateList List of objects which might implement {@link ClusterResourceListener} */ public void maybeAddAll(List<?> candidateList) { for (Object candidate : candidateList) { this.maybeAdd(candidate); } } /** * Send the updated cluster metadata to all {@link ClusterResourceListener}. * @param cluster Cluster metadata */ public void onUpdate(ClusterResource cluster) { for (ClusterResourceListener clusterResourceListener : clusterResourceListeners) { clusterResourceListener.onUpdate(cluster); } } }
ClusterResourceListeners
java
google__guice
core/test/com/google/inject/internal/OptionalBinderTest.java
{ "start": 47865, "end": 48206 }
class ____ * can change depending on the order the module intance is created. */ private static String getShortName(Module module) { String fullName = module.getClass().getName(); return fullName.substring(fullName.lastIndexOf(".") + 1); } @RealOptionalBinder.Actual("foo") @RealOptionalBinder.Default("foo") static
that
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ShouldHaveNoSuppressedExceptions_create_Test.java
{ "start": 977, "end": 1781 }
class ____ { @Test void should_fail_if_throwable_has_suppressed_exceptions() { // GIVEN Throwable actual = new Throwable(); actual.addSuppressed(new IllegalArgumentException("Suppressed Message")); // WHEN String message = shouldHaveNoSuppressedExceptions(actual).create(); // THEN then(message).isEqualTo(format("%nExpecting actual throwable not to have any suppressed exceptions but had:%n" + " %s%n%n" + "actual throwable was:%n" + " %s", STANDARD_REPRESENTATION.toStringOf(actual.getSuppressed()), STANDARD_REPRESENTATION.toStringOf(actual))); } }
ShouldHaveNoSuppressedExceptions_create_Test
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java
{ "start": 5790, "end": 6485 }
class ____ { /** * This is a mapping from "context name" (in general use, the name of a setting key) * to a configuration. * This allows us to easily answer the question "What is the configuration for ssl in realm XYZ?" * Multiple "context names" may map to the same configuration (either by object-identity or by object-equality). * For example "xpack.http.ssl" may exist as a name in this map and have the global ssl configuration as a value */ private final Map<String, SslConfiguration> configurations; /** * This is a mapping from "context name" (aka "profile name") to the extension
LoadedSslConfigurations
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/cors/CorsUtilsTests.java
{ "start": 1001, "end": 2145 }
class ____ { @Test void isCorsRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.ORIGIN, "https://domain.com"); assertThat(CorsUtils.isCorsRequest(request)).isTrue(); } @Test void isNotCorsRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); assertThat(CorsUtils.isCorsRequest(request)).isFalse(); } @Test void isPreFlightRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod(HttpMethod.OPTIONS.name()); request.addHeader(HttpHeaders.ORIGIN, "https://domain.com"); request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"); assertThat(CorsUtils.isPreFlightRequest(request)).isTrue(); } @Test void isNotPreFlightRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); assertThat(CorsUtils.isPreFlightRequest(request)).isFalse(); request = new MockHttpServletRequest(); request.setMethod(HttpMethod.OPTIONS.name()); request.addHeader(HttpHeaders.ORIGIN, "https://domain.com"); assertThat(CorsUtils.isPreFlightRequest(request)).isFalse(); } }
CorsUtilsTests
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/fs/TestGlobPaths.java
{ "start": 29979, "end": 33563 }
class ____ extends FSTestWrapperGlobTest { TestGlobWithSymlinksToSymlinks(boolean useFc) { super(useFc); } void run() throws Exception { // Test that globbing through a symlink to a symlink to a directory // fully resolves wrap.mkdir(new Path(USER_DIR + "/alpha"), FsPermission.getDirDefault(), false); wrap.createSymlink(new Path(USER_DIR + "/alpha"), new Path(USER_DIR + "/alphaLink"), false); wrap.createSymlink(new Path(USER_DIR + "/alphaLink"), new Path(USER_DIR + "/alphaLinkLink"), false); wrap.mkdir(new Path(USER_DIR + "/alpha/beta"), FsPermission.getDirDefault(), false); // Test glob through symlink to a symlink to a directory FileStatus statuses[] = wrap.globStatus(new Path(USER_DIR + "/alphaLinkLink"), new AcceptAllPathFilter()); assertEquals(1, statuses.length); assertEquals(USER_DIR + "/alphaLinkLink", statuses[0].getPath() .toUri().getPath()); statuses = wrap.globStatus(new Path(USER_DIR + "/alphaLinkLink/*"), new AcceptAllPathFilter()); assertEquals(1, statuses.length); assertEquals(USER_DIR + "/alphaLinkLink/beta", statuses[0] .getPath().toUri().getPath()); // Test glob of dangling symlink (theta does not actually exist) wrap.createSymlink(new Path(USER_DIR + "theta"), new Path(USER_DIR + "/alpha/kappa"), false); statuses = wrap.globStatus(new Path(USER_DIR + "/alpha/kappa/kappa"), new AcceptAllPathFilter()); assertNull(statuses); // Test glob of symlinks wrap.createFile(USER_DIR + "/alpha/beta/gamma"); wrap.createSymlink(new Path(USER_DIR + "gamma"), new Path(USER_DIR + "/alpha/beta/gammaLink"), false); wrap.createSymlink(new Path(USER_DIR + "gammaLink"), new Path(USER_DIR + "/alpha/beta/gammaLinkLink"), false); wrap.createSymlink(new Path(USER_DIR + "gammaLinkLink"), new Path( USER_DIR + "/alpha/beta/gammaLinkLinkLink"), false); statuses = wrap.globStatus(new Path(USER_DIR + "/alpha/*/gammaLinkLinkLink"), new AcceptAllPathFilter()); assertEquals(1, statuses.length); assertEquals(USER_DIR + "/alpha/beta/gammaLinkLinkLink", statuses[0].getPath().toUri().getPath()); statuses = wrap.globStatus(new Path(USER_DIR + "/alpha/beta/*"), new AcceptAllPathFilter()); assertEquals(USER_DIR + "/alpha/beta/gamma;" + USER_DIR + "/alpha/beta/gammaLink;" + USER_DIR + "/alpha/beta/gammaLinkLink;" + USER_DIR + "/alpha/beta/gammaLinkLinkLink", TestPath.mergeStatuses(statuses)); // Let's create two symlinks that point to each other, and glob on them. wrap.createSymlink(new Path(USER_DIR + "tweedledee"), new Path(USER_DIR + "/tweedledum"), false); wrap.createSymlink(new Path(USER_DIR + "tweedledum"), new Path(USER_DIR + "/tweedledee"), false); statuses = wrap.globStatus( new Path(USER_DIR + "/tweedledee/unobtainium"), new AcceptAllPathFilter()); assertNull(statuses); } } @Disabled @Test public void testGlobWithSymlinksToSymlinksOnFS() throws Exception { testOnFileSystem(new TestGlobWithSymlinksToSymlinks(false)); } @Disabled @Test public void testGlobWithSymlinksToSymlinksOnFC() throws Exception { testOnFileContext(new TestGlobWithSymlinksToSymlinks(true)); } /** * Test globbing symlinks with a custom PathFilter */ private
TestGlobWithSymlinksToSymlinks
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 91132, "end": 91209 }
interface ____ { int something(); } @AutoValue abstract static
Parent2
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandler.java
{ "start": 9711, "end": 10510 }
class ____ implements Converter<RedirectUriParameters, Mono<String>> { @Override public Mono<String> convert(RedirectUriParameters redirectUriParameters) { // @formatter:off return Mono.just(redirectUriParameters.authentication) .flatMap((authentication) -> { URI endSessionEndpoint = endSessionEndpoint(redirectUriParameters.clientRegistration); if (endSessionEndpoint == null) { return Mono.empty(); } String idToken = idToken(authentication); String postLogoutRedirectUri = postLogoutRedirectUri( redirectUriParameters.serverWebExchange.getRequest(), redirectUriParameters.clientRegistration); return Mono.just(endpointUri(endSessionEndpoint, idToken, postLogoutRedirectUri)); }); // @formatter:on } } }
DefaultRedirectUriResolver
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/legacy/sources/DefinedFieldMapping.java
{ "start": 1998, "end": 2980 }
interface ____ { /** * Returns the mapping for the fields of the {@link TableSource}'s {@link TableSchema} to the * fields of its produced {@link DataType}. * * <p>The mapping is done based on field names, e.g., a mapping "name" -> "f1" maps the schema * field "name" to the field "f1" of the produced data type, for example in this case the second * field of a {@link org.apache.flink.api.java.tuple.Tuple}. * * <p>The returned mapping must map all fields (except proctime and rowtime fields) to the * produced data type. It can also provide a mapping for fields which are not in the {@link * TableSchema} to make fields in the physical {@link DataType} accessible for a {@code * TimestampExtractor}. * * @return A mapping from {@link TableSchema} fields to {@link DataType} fields or null if no * mapping is necessary. */ @Nullable Map<String, String> getFieldMapping(); }
DefinedFieldMapping
java
apache__camel
core/camel-management/src/test/java/org/apache/camel/management/ManagedStickyLoadBalancerTest.java
{ "start": 1376, "end": 3330 }
class ____ extends ManagementTestSupport { @Test public void testManageStickyLoadBalancer() throws Exception { template.sendBodyAndHeader("direct:start", "Hello World", "num", "123"); // get the stats for the route MBeanServer mbeanServer = getMBeanServer(); // get the object name for the delayer ObjectName on = getCamelObjectName(TYPE_PROCESSOR, "mysend"); // should be on route1 String routeId = (String) mbeanServer.getAttribute(on, "RouteId"); assertEquals("route1", routeId); String camelId = (String) mbeanServer.getAttribute(on, "CamelId"); assertEquals(context.getManagementName(), camelId); String state = (String) mbeanServer.getAttribute(on, "State"); assertEquals(ServiceStatus.Started.name(), state); Integer size = (Integer) mbeanServer.getAttribute(on, "Size"); assertEquals(2, size.intValue()); String lan = (String) mbeanServer.getAttribute(on, "ExpressionLanguage"); assertEquals("header", lan); String uri = (String) mbeanServer.getAttribute(on, "Expression"); assertEquals("num", uri); String last = (String) mbeanServer.getAttribute(on, "LastChosenProcessorId"); assertTrue("foo".equals(last) || "bar".equals(last)); template.sendBodyAndHeader("direct:start", "Bye World", "num", "123"); String last2 = (String) mbeanServer.getAttribute(on, "LastChosenProcessorId"); assertEquals(last, last2, "Should be sticky"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .loadBalance().sticky(header("num")).id("mysend") .to("mock:foo").id("foo").to("mock:bar").id("bar"); } }; } }
ManagedStickyLoadBalancerTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/RestrictedApiCheckerTest.java
{ "start": 7048, "end": 7671 }
class ____ { void foo() { // BUG: Diagnostic contains: lorem RestrictedApiMethods.restrictedStaticMethod(); // BUG: Diagnostic contains: lorem RestrictedApiMethods.accept(RestrictedApiMethods::restrictedStaticMethod); } } """) .expectResult(Result.ERROR) .doTest(); } @Test public void restrictedConstructorProhibited() { helper .addSourceLines( "Testcase.java", """ package com.google.errorprone.bugpatterns.testdata;
Testcase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/CorrelatedPluralJoinInheritanceTest.java
{ "start": 5604, "end": 5705 }
class ____ extends DataEntity { } @Entity( name = "ContinuousData" ) public abstract static
BatchData
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/support/AnnotationSupport.java
{ "start": 6877, "end": 8341 }
class ____ which to search for the annotation; may be {@code null} * @param annotationType the annotation type to search for; never {@code null} * @param searchOption the {@code SearchOption} to use; never {@code null} * @return an {@code Optional} containing the annotation; never {@code null} but * potentially empty * @since 1.8 * @see SearchOption * @see #findAnnotation(AnnotatedElement, Class) * @deprecated Use {@link #findAnnotation(AnnotatedElement, Class)} * (for {@code SearchOption.DEFAULT}) or * {@link #findAnnotation(Class, Class, List)} (for * {@code SearchOption.INCLUDE_ENCLOSING_CLASSES}) instead */ @Deprecated(since = "1.12") @API(status = DEPRECATED, since = "1.12") @SuppressWarnings("deprecation") public static <A extends Annotation> Optional<A> findAnnotation(@Nullable Class<?> clazz, Class<A> annotationType, SearchOption searchOption) { Preconditions.notNull(searchOption, "SearchOption must not be null"); return AnnotationUtils.findAnnotation(clazz, annotationType, searchOption == SearchOption.INCLUDE_ENCLOSING_CLASSES); } /** * Find the first annotation of the specified type that is either * <em>directly present</em>, <em>meta-present</em>, or <em>indirectly * present</em> on the supplied class. * * <p>If the annotation is neither <em>directly present</em> nor <em>meta-present</em> * on the class, this method will additionally search on interfaces implemented * by the
on
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/mutable/PrintAtomicVsMutable.java
{ "start": 1060, "end": 1653 }
class ____ { public static void main(final String[] args) { final MutableInt mInt = new MutableInt(); final int max = 100_000_000; System.out.println("MutableInt " + DurationUtils.of(() -> { for (int i = 0; i < max; i++) { mInt.incrementAndGet(); } })); final AtomicInteger aInt = new AtomicInteger(); System.out.println("AtomicInteger " + DurationUtils.of(() -> { for (int i = 0; i < max; i++) { aInt.incrementAndGet(); } })); } }
PrintAtomicVsMutable
java
resilience4j__resilience4j
resilience4j-retry/src/main/java/io/github/resilience4j/retry/MaxRetriesExceededException.java
{ "start": 240, "end": 1356 }
class ____ extends RuntimeException { private final transient String causingRetryName; private MaxRetriesExceededException(String causingRetryName, String message, boolean writeableStackTrace) { super(message, null, false, writeableStackTrace); this.causingRetryName = causingRetryName; } /** * Static method to construct a {@link MaxRetriesExceededException} * @param retry the Retry which failed */ public static MaxRetriesExceededException createMaxRetriesExceededException(Retry retry) { boolean writeStackTrace = retry.getRetryConfig().isWritableStackTraceEnabled(); String message = String.format( "Retry '%s' has exhausted all attempts (%d)", retry.getName(), retry.getRetryConfig().getMaxAttempts() ); return new MaxRetriesExceededException(retry.getName(), message, writeStackTrace); } /** * @return the name of the {@link Retry} that caused this exception */ public String getCausingRetryName() { return causingRetryName; } }
MaxRetriesExceededException
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/MonoNext.java
{ "start": 1056, "end": 1478 }
class ____<T> extends MonoFromFluxOperator<T, T> { MonoNext(Flux<? extends T> source) { super(source); } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) { return new NextSubscriber<>(actual); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } static final
MonoNext
java
apache__hadoop
hadoop-tools/hadoop-datajoin/src/main/java/org/apache/hadoop/contrib/utils/join/ResetableIterator.java
{ "start": 1146, "end": 1294 }
interface ____ extends Iterator { public void reset(); public void add(Object item); public void close() throws IOException; }
ResetableIterator
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java
{ "start": 29764, "end": 29881 }
interface ____ { } @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Qualifier public @
TestQualifier
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/aot/hint/annotation/Reflective.java
{ "start": 1711, "end": 2117 }
interface ____ { /** * Alias for {@link #processors()}. */ @AliasFor("processors") Class<? extends ReflectiveProcessor>[] value() default SimpleReflectiveProcessor.class; /** * {@link ReflectiveProcessor} implementations to invoke against the * annotated element. */ @AliasFor("value") Class<? extends ReflectiveProcessor>[] processors() default SimpleReflectiveProcessor.class; }
Reflective
java
qos-ch__slf4j
jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLocationAwareLog.java
{ "start": 1173, "end": 9098 }
class ____ implements Log, Serializable { private static final long serialVersionUID = -2379157579039314822L; // used to store this logger's name to recreate it after serialization protected String name; // in both Log4jLogger and Jdk14Logger classes in the original JCL, the // logger instance is transient private final transient LocationAwareLogger logger; private static final String FQCN = SLF4JLocationAwareLog.class.getName(); public SLF4JLocationAwareLog(LocationAwareLogger logger) { this.logger = logger; this.name = logger.getName(); } /** * Delegates to the <code>isTraceEnabled<code> method of the wrapped * <code>org.slf4j.Logger</code> instance. */ public boolean isTraceEnabled() { return logger.isTraceEnabled(); } /** * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance. */ public boolean isDebugEnabled() { return logger.isDebugEnabled(); } /** * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance. */ public boolean isInfoEnabled() { return logger.isInfoEnabled(); } /** * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance. */ public boolean isWarnEnabled() { return logger.isWarnEnabled(); } /** * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance. */ public boolean isErrorEnabled() { return logger.isErrorEnabled(); } /** * Delegates to the <code>isErrorEnabled<code> method of the wrapped * <code>org.slf4j.Logger</code> instance. */ public boolean isFatalEnabled() { return logger.isErrorEnabled(); } /** * Converts the input parameter to String and then delegates to the debug * method of the wrapped <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} */ public void trace(Object message) { if (isTraceEnabled()) { logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, null); } } /** * Converts the first input parameter to String and then delegates to the * debug method of the wrapped <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} * @param t * the exception to log */ public void trace(Object message, Throwable t) { if (isTraceEnabled()) { logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, t); } } /** * Converts the input parameter to String and then delegates to the wrapped * <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} */ public void debug(Object message) { if (isDebugEnabled()) { logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, null); } } /** * Converts the first input parameter to String and then delegates to the * wrapped <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} * @param t * the exception to log */ public void debug(Object message, Throwable t) { if (isDebugEnabled()) { logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, t); } } /** * Converts the input parameter to String and then delegates to the wrapped * <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} */ public void info(Object message) { if (isInfoEnabled()) { logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, null); } } /** * Converts the first input parameter to String and then delegates to the * wrapped <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} * @param t * the exception to log */ public void info(Object message, Throwable t) { if (isInfoEnabled()) { logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, t); } } /** * Converts the input parameter to String and then delegates to the wrapped * <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} */ public void warn(Object message) { if (isWarnEnabled()) { logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, null); } } /** * Converts the first input parameter to String and then delegates to the * wrapped <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} * @param t * the exception to log */ public void warn(Object message, Throwable t) { if (isWarnEnabled()) { logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, t); } } /** * Converts the input parameter to String and then delegates to the wrapped * <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} */ public void error(Object message) { if (isErrorEnabled()) { logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null); } } /** * Converts the first input parameter to String and then delegates to the * wrapped <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} * @param t * the exception to log */ public void error(Object message, Throwable t) { if (isErrorEnabled()) { logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t); } } /** * Converts the input parameter to String and then delegates to the error * method of the wrapped <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} */ public void fatal(Object message) { if (isErrorEnabled()) { logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null); } } /** * Converts the first input parameter to String and then delegates to the * error method of the wrapped <code>org.slf4j.Logger</code> instance. * * @param message * the message to log. Converted to {@link String} * @param t * the exception to log */ public void fatal(Object message, Throwable t) { if (isErrorEnabled()) { logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t); } } /** * Replace this instance with a homonymous (same name) logger returned by * LoggerFactory. Note that this method is only called during deserialization. * * @return logger with same name as returned by LoggerFactory * @throws ObjectStreamException */ protected Object readResolve() throws ObjectStreamException { Logger logger = LoggerFactory.getLogger(this.name); return new SLF4JLocationAwareLog((LocationAwareLogger) logger); } }
SLF4JLocationAwareLog
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/aot/AotTestAttributesFactory.java
{ "start": 1206, "end": 2263 }
class ____ running in {@linkplain AotDetector#useGeneratedArtifacts() * AOT execution mode} and otherwise creates a new map for storing attributes * during the AOT processing phase. */ static Map<String, String> getAttributes() { Map<String, String> attrs = attributes; if (attrs == null) { synchronized (AotTestAttributesFactory.class) { attrs = attributes; if (attrs == null) { attrs = (AotDetector.useGeneratedArtifacts() ? loadAttributesMap() : new ConcurrentHashMap<>()); attributes = attrs; } } } return attrs; } /** * Reset the factory. * <p>Only for internal use. */ static void reset() { synchronized (AotTestAttributesFactory.class) { attributes = null; } } @SuppressWarnings("unchecked") private static Map<String, String> loadAttributesMap() { String className = AotTestAttributesCodeGenerator.GENERATED_ATTRIBUTES_CLASS_NAME; String methodName = AotTestAttributesCodeGenerator.GENERATED_ATTRIBUTES_METHOD_NAME; return GeneratedMapUtils.loadMap(className, methodName); } }
when
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleInternalHelper.java
{ "start": 1427, "end": 1893 }
enum ____ implements Function<SingleSource, Publisher> { INSTANCE; @SuppressWarnings("unchecked") @Override public Publisher apply(SingleSource v) { return new SingleToFlowable(v); } } @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T> Function<SingleSource<? extends T>, Publisher<? extends T>> toFlowable() { return (Function)ToFlowable.INSTANCE; } static final
ToFlowable
java
elastic__elasticsearch
libs/h3/src/test/java/org/elasticsearch/h3/FastMathTests.java
{ "start": 972, "end": 5175 }
class ____ extends ESTestCase { // accuracy for cos(x) static double COS_DELTA = 1E-15; // accuracy for sin(x) static double SIN_DELTA = 1E-15; // accuracy for asin(x) static double ASIN_DELTA = 1E-14; // accuracy for acos(x) static double ACOS_DELTA = 1E-14; // accuracy for tan(x) static double TAN_DELTA = 1E-14; // accuracy for atan(x) static double ATAN_DELTA = 1E-14; // accuracy for atan2(x) static double ATAN2_DELTA = 1E-14; public void testSin() { doTest(Math::sin, FastMath::sin, d -> SIN_DELTA, () -> randomDoubleBetween(-2 * Math.PI, 2 * Math.PI, true)); } public void testCos() { doTest(Math::cos, FastMath::cos, d -> COS_DELTA, () -> randomDoubleBetween(-2 * Math.PI, 2 * Math.PI, true)); } public void testTan() { doTest( Math::tan, FastMath::tan, d -> Math.max(TAN_DELTA, Math.abs(Math.tan(d)) * TAN_DELTA), () -> randomDoubleBetween(-2 * Math.PI, 2 * Math.PI, true) ); } public void testAsin() { doTest(Math::asin, FastMath::asin, d -> ASIN_DELTA, () -> randomDoubleBetween(-2, 2, true)); } public void testAcos() { doTest(Math::acos, FastMath::acos, d -> ACOS_DELTA, () -> randomDoubleBetween(-2, 2, true)); } public void testAtan() { doTest( Math::atan, FastMath::atan, d -> ATAN_DELTA, () -> randomDoubleBetween(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, true) ); } private void doTest(DoubleUnaryOperator expected, DoubleUnaryOperator actual, DoubleUnaryOperator delta, DoubleSupplier supplier) { assertEquals(expected.applyAsDouble(Double.NaN), actual.applyAsDouble(Double.NaN), delta.applyAsDouble(Double.NaN)); assertEquals( expected.applyAsDouble(Double.NEGATIVE_INFINITY), actual.applyAsDouble(Double.NEGATIVE_INFINITY), delta.applyAsDouble(Double.POSITIVE_INFINITY) ); assertEquals( expected.applyAsDouble(Double.POSITIVE_INFINITY), actual.applyAsDouble(Double.POSITIVE_INFINITY), delta.applyAsDouble(Double.POSITIVE_INFINITY) ); assertEquals( expected.applyAsDouble(Double.MAX_VALUE), actual.applyAsDouble(Double.MAX_VALUE), delta.applyAsDouble(Double.MAX_VALUE) ); assertEquals( expected.applyAsDouble(Double.MIN_VALUE), actual.applyAsDouble(Double.MIN_VALUE), delta.applyAsDouble(Double.MIN_VALUE) ); assertEquals(expected.applyAsDouble(0), actual.applyAsDouble(0), delta.applyAsDouble(0)); for (int i = 0; i < 10000; i++) { double d = supplier.getAsDouble(); assertEquals(expected.applyAsDouble(d), actual.applyAsDouble(d), delta.applyAsDouble(d)); } } public void testAtan2() { assertEquals(Math.atan2(Double.NaN, Double.NaN), FastMath.atan2(Double.NaN, Double.NaN), ATAN2_DELTA); assertEquals( Math.atan2(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY), FastMath.atan2(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY), ATAN2_DELTA ); assertEquals( Math.atan2(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY), FastMath.atan2(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY), ATAN2_DELTA ); assertEquals(Math.atan2(Double.MAX_VALUE, Double.MAX_VALUE), FastMath.atan2(Double.MAX_VALUE, Double.MAX_VALUE), ATAN2_DELTA); assertEquals(Math.atan2(Double.MIN_VALUE, Double.MIN_VALUE), FastMath.atan2(Double.MIN_VALUE, Double.MIN_VALUE), ATAN2_DELTA); assertEquals(Math.atan2(0, 0), FastMath.atan2(0, 0), ATAN2_DELTA); for (int i = 0; i < 10000; i++) { double x = randomDoubleBetween(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, true); double y = randomDoubleBetween(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, true); assertEquals(Math.atan2(x, y), FastMath.atan2(x, y), ATAN2_DELTA); } } }
FastMathTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/http/HttpServerTransport.java
{ "start": 857, "end": 1215 }
interface ____ extends LifecycleComponent, ReportingService<HttpInfo> { String HTTP_PROFILE_NAME = ".http"; String HTTP_SERVER_WORKER_THREAD_NAME_PREFIX = "http_server_worker"; BoundTransportAddress boundAddress(); @Override HttpInfo info(); HttpStats stats(); /** * Dispatches HTTP requests. */
HttpServerTransport
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/support/descriptor/MethodSource.java
{ "start": 6746, "end": 8471 }
class ____ name: " + this.className, cause)); // @formatter:on } return this.javaClass; } private Method lazyLoadJavaMethod() { if (this.javaMethod == null) { Class<?> javaClass = getJavaClass(); if (StringUtils.isNotBlank(this.methodParameterTypes)) { this.javaMethod = ReflectionSupport.findMethod(javaClass, this.methodName, this.methodParameterTypes).orElseThrow( () -> new PreconditionViolationException( "Could not find method with name [%s] and parameter types [%s] in class [%s].".formatted( this.methodName, this.methodParameterTypes, javaClass.getName()))); } else { this.javaMethod = ReflectionSupport.findMethod(javaClass, this.methodName).orElseThrow( () -> new PreconditionViolationException( "Could not find method with name [%s] in class [%s].".formatted(this.methodName, javaClass.getName()))); } } return this.javaMethod; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MethodSource that = (MethodSource) o; return Objects.equals(this.className, that.className)// && Objects.equals(this.methodName, that.methodName)// && Objects.equals(this.methodParameterTypes, that.methodParameterTypes); } @Override public int hashCode() { return Objects.hash(this.className, this.methodName, this.methodParameterTypes); } @Override public String toString() { // @formatter:off return new ToStringBuilder(this) .append("className", this.className) .append("methodName", this.methodName) .append("methodParameterTypes", this.methodParameterTypes) .toString(); // @formatter:on } }
with
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java
{ "start": 13438, "end": 13929 }
class ____ { public void doTest() { Client client = new Client(); client.millis(42); } } """) .doTest(); } @Test public void staticMethod_withStaticImport_withImport() { refactoringTestHelper .addInputLines( "Client.java", """ package com.google.test; import com.google.errorprone.annotations.InlineMe; public final
Caller
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/JobID.java
{ "start": 1394, "end": 3991 }
class ____ extends AbstractID { private static final long serialVersionUID = 1L; /** Creates a new (statistically) random JobID. */ public JobID() { super(); } /** * Creates a new JobID, using the given lower and upper parts. * * @param lowerPart The lower 8 bytes of the ID. * @param upperPart The upper 8 bytes of the ID. */ public JobID(long lowerPart, long upperPart) { super(lowerPart, upperPart); } /** * Creates a new JobID from the given byte sequence. The byte sequence must be exactly 16 bytes * long. The first eight bytes make up the lower part of the ID, while the next 8 bytes make up * the upper part of the ID. * * @param bytes The byte sequence. */ public JobID(byte[] bytes) { super(bytes); } // ------------------------------------------------------------------------ // Static factory methods // ------------------------------------------------------------------------ /** * Creates a new (statistically) random JobID. * * @return A new random JobID. */ public static JobID generate() { return new JobID(); } /** * Creates a new JobID from the given byte sequence. The byte sequence must be exactly 16 bytes * long. The first eight bytes make up the lower part of the ID, while the next 8 bytes make up * the upper part of the ID. * * @param bytes The byte sequence. * @return A new JobID corresponding to the ID encoded in the bytes. */ public static JobID fromByteArray(byte[] bytes) { return new JobID(bytes); } public static JobID fromByteBuffer(ByteBuffer buf) { long lower = buf.getLong(); long upper = buf.getLong(); return new JobID(lower, upper); } /** * Parses a JobID from the given string. * * @param hexString string representation of a JobID * @return Parsed JobID * @throws IllegalArgumentException if the JobID could not be parsed from the given string */ public static JobID fromHexString(String hexString) { try { return new JobID(StringUtils.hexStringToByte(hexString)); } catch (Exception e) { throw new IllegalArgumentException( "Cannot parse JobID from \"" + hexString + "\". The expected format is " + "[0-9a-fA-F]{32}, e.g. fd72014d4c864993a2e5a9287b4a9c5d.", e); } } }
JobID
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java
{ "start": 166365, "end": 166662 }
class ____<K> implements GenericInterface2<K>, BeanNameAware { private String name; @Override public void setBeanName(String name) { this.name = name; } @Override public String doSomethingMoreGeneric(K o) { return this.name + " " + o; } } public static
GenericInterface2Bean
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/ITestAbfsHugeFiles.java
{ "start": 2034, "end": 5115 }
class ____ extends AbstractAbfsScaleTest { private static final int ONE_MB = 1024 * 1024; private static final int EIGHT_MB = 8 * ONE_MB; // Configurable huge file upload: "fs.azure.scale.test.huge.upload", // default is 2 * DEFAULT_WRITE_BUFFER_SIZE(8M). private static final int HUGE_FILE; // Set the HUGE_FILE. static { HUGE_FILE = getTestPropertyInt(new Configuration(), AZURE_SCALE_HUGE_FILE_UPLOAD, AZURE_SCALE_HUGE_FILE_UPLOAD_DEFAULT); } // Writing block size to be used in this test. private int size; // Block Factory to be used in this test. private String blockFactoryName; public static Collection<Object[]> sizes() { return Arrays.asList(new Object[][] { { DEFAULT_WRITE_BUFFER_SIZE, DataBlocks.DATA_BLOCKS_BUFFER_DISK }, { HUGE_FILE, DataBlocks.DATA_BLOCKS_BUFFER_DISK }, { DEFAULT_WRITE_BUFFER_SIZE, DataBlocks.DATA_BLOCKS_BUFFER_ARRAY }, { HUGE_FILE, DataBlocks.DATA_BLOCKS_BUFFER_ARRAY }, { DEFAULT_WRITE_BUFFER_SIZE, DataBlocks.DATA_BLOCKS_BYTEBUFFER }, { HUGE_FILE, DataBlocks.DATA_BLOCKS_BYTEBUFFER }, }); } public ITestAbfsHugeFiles(int size, String blockFactoryName) throws Exception { this.size = size; this.blockFactoryName = blockFactoryName; } @BeforeEach public void setUp() throws Exception { Configuration configuration = getRawConfiguration(); configuration.unset(DATA_BLOCKS_BUFFER); configuration.set(DATA_BLOCKS_BUFFER, blockFactoryName); super.setup(); } /** * Testing Huge files written at once on AbfsOutputStream. */ @Test public void testHugeFileWrite() throws IOException { AzureBlobFileSystem fs = getFileSystem(); Path filePath = path(getMethodName()); final byte[] b = new byte[size]; new Random().nextBytes(b); try (FSDataOutputStream out = fs.create(filePath)) { out.write(b); } // Verify correct length was uploaded. Don't want to verify contents // here, as this would increase the test time significantly. assertEquals(size, fs.getFileStatus(filePath).getLen(), "Mismatch in content length of file uploaded"); } /** * Testing Huge files written in chunks of 8M in lots of writes. */ @Test public void testLotsOfWrites() throws IOException { assume("If the size isn't a multiple of 8M this test would not pass, so " + "skip", size % EIGHT_MB == 0); AzureBlobFileSystem fs = getFileSystem(); Path filePath = path(getMethodName()); final byte[] b = new byte[size]; new Random().nextBytes(b); try (FSDataOutputStream out = fs.create(filePath)) { int offset = 0; for (int i = 0; i < size / EIGHT_MB; i++) { out.write(b, offset, EIGHT_MB); offset += EIGHT_MB; } } // Verify correct length was uploaded. Don't want to verify contents // here, as this would increase the test time significantly. assertEquals(size, fs.getFileStatus(filePath).getLen(), "Mismatch in content length of file uploaded"); } }
ITestAbfsHugeFiles
java
quarkusio__quarkus
extensions/panache/hibernate-orm-panache/runtime/src/main/java/io/quarkus/hibernate/orm/panache/runtime/AdditionalJpaOperations.java
{ "start": 1176, "end": 6537 }
class ____ { @SuppressWarnings("rawtypes") public static PanacheQuery<?> find(AbstractJpaOperations<?> jpaOperations, Class<?> entityClass, String query, String countQuery, Sort sort, Map<String, Object> params) { String findQuery = createFindQuery(entityClass, query, jpaOperations.paramCount(params)); Session session = jpaOperations.getSession(entityClass); SelectionQuery hibernateQuery = session.createSelectionQuery(sort != null ? findQuery + toOrderBy(sort) : findQuery); JpaOperations.bindParameters(hibernateQuery, params); return new CustomCountPanacheQuery(session, hibernateQuery, countQuery, params); } public static PanacheQuery<?> find(AbstractJpaOperations<?> jpaOperations, Class<?> entityClass, String query, String countQuery, Sort sort, Parameters parameters) { return find(jpaOperations, entityClass, query, countQuery, sort, parameters.map()); } @SuppressWarnings("rawtypes") public static PanacheQuery<?> find(AbstractJpaOperations<?> jpaOperations, Class<?> entityClass, String query, String countQuery, Sort sort, Object... params) { String findQuery = createFindQuery(entityClass, query, jpaOperations.paramCount(params)); Session session = jpaOperations.getSession(entityClass); SelectionQuery hibernateQuery = session.createSelectionQuery(sort != null ? findQuery + toOrderBy(sort) : findQuery); JpaOperations.bindParameters(hibernateQuery, params); return new CustomCountPanacheQuery(session, hibernateQuery, countQuery, params); } public static long deleteAllWithCascade(AbstractJpaOperations<?> jpaOperations, Class<?> entityClass) { Session session = jpaOperations.getSession(entityClass); //detecting the case where there are cascade-delete associations, and do the bulk delete query otherwise. if (deleteOnCascadeDetected(jpaOperations, entityClass)) { int count = 0; List<?> objects = jpaOperations.listAll(entityClass); for (Object entity : objects) { session.remove(entity); count++; } return count; } return jpaOperations.deleteAll(entityClass); } /** * Detects if cascading delete is needed. The delete-cascading is needed when associations with cascade delete enabled * {@link jakarta.persistence.OneToMany#cascade()} and also on entities containing a collection of elements * {@link jakarta.persistence.ElementCollection} * * @param entityClass * @return true if cascading delete is needed. False otherwise */ private static boolean deleteOnCascadeDetected(AbstractJpaOperations<?> jpaOperations, Class<?> entityClass) { Session session = jpaOperations.getSession(entityClass); Metamodel metamodel = session.getMetamodel(); EntityType<?> entity1 = metamodel.entity(entityClass); Set<Attribute<?, ?>> declaredAttributes = ((EntityTypeImpl) entity1).getDeclaredAttributes(); CascadeStyle[] propertyCascadeStyles = session.unwrap(SessionImplementor.class) .getEntityPersister(entityClass.getName(), null) .getPropertyCascadeStyles(); boolean doCascade = Arrays.stream(propertyCascadeStyles) .anyMatch(cascadeStyle -> cascadeStyle.doCascade(CascadingActions.DELETE)); boolean hasElementCollection = declaredAttributes.stream() .anyMatch(attribute -> attribute.getPersistentAttributeType() .equals(Attribute.PersistentAttributeType.ELEMENT_COLLECTION)); return doCascade || hasElementCollection; } public static <PanacheQueryType> long deleteWithCascade(AbstractJpaOperations<PanacheQueryType> jpaOperations, Class<?> entityClass, String query, Object... params) { Session session = jpaOperations.getSession(entityClass); if (deleteOnCascadeDetected(jpaOperations, entityClass)) { int count = 0; List<?> objects = jpaOperations.list(jpaOperations.find(entityClass, query, params)); for (Object entity : objects) { session.remove(entity); count++; } return count; } return jpaOperations.delete(entityClass, query, params); } public static <PanacheQueryType> long deleteWithCascade(AbstractJpaOperations<PanacheQueryType> jpaOperations, Class<?> entityClass, String query, Map<String, Object> params) { Session session = jpaOperations.getSession(entityClass); if (deleteOnCascadeDetected(jpaOperations, entityClass)) { int count = 0; List<?> objects = jpaOperations.list(jpaOperations.find(entityClass, query, params)); for (Object entity : objects) { session.remove(entity); count++; } return count; } return jpaOperations.delete(entityClass, query, params); } public static long deleteWithCascade(AbstractJpaOperations<?> jpaOperations, Class<?> entityClass, String query, Parameters params) { return deleteWithCascade(jpaOperations, entityClass, query, params.map()); } }
AdditionalJpaOperations
java
apache__camel
components/camel-oauth/src/test/java/org/apache/camel/test/oauth/OAuthCodeFlowServletTest.java
{ "start": 1709, "end": 3624 }
class ____ extends AbstractOAuthCodeFlowTest { static Undertow server; @BeforeAll static void setUp() throws Exception { server = createUndertowServer(); server.start(); } @AfterAll static void tearDown() { if (server != null) { server.stop(); } } @Override CamelContext createCamelContext() throws Exception { var context = new DefaultCamelContext(); PropertiesComponent props = context.getPropertiesComponent(); props.addInitialProperty(CAMEL_OAUTH_BASE_URI, KEYCLOAK_REALM_URL); props.addInitialProperty(CAMEL_OAUTH_CLIENT_ID, TEST_CLIENT_ID); props.addInitialProperty(CAMEL_OAUTH_CLIENT_SECRET, TEST_CLIENT_SECRET); props.addInitialProperty(CAMEL_OAUTH_REDIRECT_URI, APP_BASE_URL + "auth"); props.addInitialProperty(CAMEL_OAUTH_LOGOUT_REDIRECT_URI, APP_BASE_URL); return context; } @Override void addOAuthCodeFlowRoutes(CamelContext context) throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("servlet:/") .setBody(simple("resource:classpath:index.html")); from("servlet:/static/styles.css") .setBody(simple("resource:classpath:styles.css")); from("servlet:/auth") .process(new OAuthCodeFlowCallback()); from("servlet:/protected") .process(new OAuthCodeFlowProcessor()) .setBody(simple("resource:classpath:protected.html")); from("servlet:/logout") .process(new OAuthLogoutProcessor()) .process(exc -> exc.getContext().getGlobalOptions().put("OAuthLogout", "ok")); } }); } }
OAuthCodeFlowServletTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/param/MySqlParameterizedOutputVisitorTest_71.java
{ "start": 344, "end": 1196 }
class ____ extends TestCase { public void test_in() throws Exception { String sql = "SELECT (3, 4) IN ((1, 2), (3, 4)) FROM dual"; List<Object> params = new ArrayList<Object>(); String psql = ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.MYSQL, params, VisitorFeature.OutputParameterizedUnMergeShardingTable, VisitorFeature.OutputParameterizedQuesUnMergeInList ); assertEquals("SELECT (?, ?) IN ((?, ?), (?, ?))\n" + "FROM dual", psql); assertEquals("[3,4,1,2,3,4]", JSON.toJSONString(params)); String rsql = ParameterizedOutputVisitorUtils.restore(psql, JdbcConstants.MYSQL, params); assertEquals("SELECT (3, 4) IN ((1, 2), (3, 4))\n" + "FROM dual", rsql); } }
MySqlParameterizedOutputVisitorTest_71
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnicodeDirectionalityCharactersTest.java
{ "start": 1434, "end": 1740 }
class ____ { final int noUnicodeHereBoss = 1; } """) .doTest(); } @Test public void positive() { helper .addSourceLines( "Test.java", """ // BUG: Diagnostic contains: /** \u202a */
Test
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ReturnValueIgnored.java
{ "start": 2825, "end": 19403 }
class ____ extends AbstractReturnValueIgnored { /** * A set of types which this checker should examine method calls on. * * <p>There are also some high-priority return value ignored checks in SpotBugs for various * threading constructs which do not return the same type as the receiver. This check does not * deal with them, since the fix is less straightforward. See a list of the SpotBugs checks here: * https://github.com/spotbugs/spotbugs/blob/master/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/CheckReturnAnnotationDatabase.java */ private static final ImmutableSet<String> TYPES_TO_CHECK = ImmutableSet.of("java.math.BigInteger", "java.math.BigDecimal", "java.nio.file.Path"); /** * Matches method invocations in which the method being called is on an instance of a type in the * TYPES_TO_CHECK set and returns the same type (e.g. String.trim() returns a String). */ private static final Matcher<ExpressionTree> RETURNS_SAME_TYPE = allOf( not(kindIs(Kind.NEW_CLASS)), // Constructor calls don't have a "receiver" (tree, state) -> { Type receiverType = getReceiverType(tree); return TYPES_TO_CHECK.contains(receiverType.toString()) && isSameType(receiverType, getReturnType(tree), state); }); /** * This matcher allows the following methods in {@code java.time} (and {@code org.threeten.bp}): * * <ul> * <li>any methods named {@code parse} * <li>any static method named {@code of} * <li>any static method named {@code from} * <li>any instance method starting with {@code append} on {@link * java.time.format.DateTimeFormatterBuilder} * <li>{@link java.time.temporal.ChronoField#checkValidIntValue} * <li>{@link java.time.temporal.ChronoField#checkValidValue} * <li>{@link java.time.temporal.ValueRange#checkValidValue} * </ul> */ private static final Matcher<ExpressionTree> ALLOWED_JAVA_TIME_METHODS = anyOf( staticMethod().anyClass().named("parse"), instanceMethod().anyClass().named("parse"), staticMethod().anyClass().named("of"), staticMethod().anyClass().named("from"), staticMethod().onClassAny("java.time.ZoneId", "org.threeten.bp.ZoneId").named("ofOffset"), instanceMethod() .onExactClassAny( "java.time.format.DateTimeFormatterBuilder", "org.threeten.bp.format.DateTimeFormatterBuilder") .withNameMatching(Pattern.compile("^(append|parse|pad|optional).*")), instanceMethod() .onExactClassAny( "java.time.temporal.ChronoField", "org.threeten.bp.temporal.ChronoField") .named("checkValidIntValue"), instanceMethod() .onExactClassAny( "java.time.temporal.ChronoField", "org.threeten.bp.temporal.ChronoField") .named("checkValidValue"), instanceMethod() .onExactClassAny( "java.time.temporal.ValueRange", "org.threeten.bp.temporal.ValueRange") .named("checkValidValue")); /** * {@link java.time} (and by extension {@code org.threeten.bp}) types are immutable. The only * methods we allow ignoring the return value on are the {@code parse}-style APIs since folks * often use it for validation. */ private static boolean javaTimeTypes(ExpressionTree tree, VisitorState state) { // don't analyze the library or its tests as they do weird things if (packageStartsWith("java.time").matches(tree, state) || packageStartsWith("org.threeten.bp").matches(tree, state)) { return false; } Symbol symbol = getSymbol(tree); if (symbol instanceof MethodSymbol) { String qualifiedName = enclosingPackage(symbol.owner).getQualifiedName().toString(); return (qualifiedName.startsWith("java.time") || qualifiedName.startsWith("org.threeten.bp")) && symbol.getModifiers().contains(Modifier.PUBLIC) && !ALLOWED_JAVA_TIME_METHODS.matches(tree, state); } return false; } /** * Methods in {@link java.util.function} are pure, and their return values should not be * discarded. */ private static boolean functionalMethod(ExpressionTree tree, VisitorState state) { Symbol symbol = getSymbol(tree); return symbol instanceof MethodSymbol && enclosingPackage(symbol.owner).getQualifiedName().contentEquals("java.util.function"); } /** * The return value of stream methods should always be checked (except for forEach and * forEachOrdered, which are void-returning and won't be checked by AbstractReturnValueIgnored). */ private static final Matcher<ExpressionTree> STREAM_METHODS = instanceMethod().onDescendantOf("java.util.stream.BaseStream"); /** * The return values of {@link java.util.Arrays} methods should always be checked (except for * void-returning ones, which won't be checked by AbstractReturnValueIgnored). */ private static final Matcher<ExpressionTree> ARRAYS_METHODS = staticMethod().onClass("java.util.Arrays"); /** * The return values of {@link java.lang.String} methods should always be checked (except for * void-returning ones, which won't be checked by AbstractReturnValueIgnored). */ private static final Matcher<ExpressionTree> STRING_METHODS = anyMethod().onClass("java.lang.String"); private static final ImmutableSet<String> PRIMITIVE_TYPES = ImmutableSet.of( "java.lang.Boolean", "java.lang.Byte", "java.lang.Character", "java.lang.Double", "java.lang.Float", "java.lang.Integer", "java.lang.Long", "java.lang.Short"); /** All methods on the primitive wrapper types. */ private static final Matcher<ExpressionTree> PRIMITIVE_NON_PARSING_METHODS = anyMethod().onClass(isExactTypeAny(PRIMITIVE_TYPES)); /** * Parsing-style methods on the primitive wrapper types (e.g., {@link * java.lang.Integer#decode(String)}). */ // TODO(kak): Instead of special casing the parsing style methods, we could consider looking for a // surrounding try/catch block (which folks use to validate input data). private static final Matcher<ExpressionTree> PRIMITIVE_PARSING_METHODS = anyOf( staticMethod().onClass("java.lang.Character").namedAnyOf("toChars", "codePointCount"), staticMethod().onClassAny(PRIMITIVE_TYPES).named("decode"), staticMethod() .onClassAny(PRIMITIVE_TYPES) .withNameMatching(Pattern.compile("^parse[A-z]*")), staticMethod() .onClassAny(PRIMITIVE_TYPES) .named("valueOf") .withParameters("java.lang.String"), staticMethod() .onClassAny(PRIMITIVE_TYPES) .named("valueOf") .withParameters("java.lang.String", "int")); // TODO(kak): we may want to change this to an opt-out list per class (e.g., check _all_ of the // methods on `java.util.Collection`, except this set. That would be much more future-proof. // However, we need to make sure we're only checking the APIs defined on the interface, and not // all methods on the descendant type. /** APIs to check on the {@link java.util.Collection} interface. */ private static final Matcher<ExpressionTree> COLLECTION_METHODS = anyOf( instanceMethod() .onDescendantOf("java.util.Collection") .named("contains") .withParameters("java.lang.Object"), instanceMethod() .onDescendantOf("java.util.Collection") .named("containsAll") .withParameters("java.util.Collection"), instanceMethod() .onDescendantOf("java.util.Collection") .named("isEmpty") .withNoParameters(), instanceMethod().onDescendantOf("java.util.Collection").named("size").withNoParameters(), instanceMethod() .onDescendantOf("java.util.Collection") .named("stream") .withNoParameters(), instanceMethod() .onDescendantOf("java.util.Collection") .named("toArray") .withNoParameters(), instanceMethod() .onDescendantOf("java.util.Collection") .named("toArray") .withParameters("java.util.function.IntFunction")); /** APIs to check on the {@link java.util.Map} interface. */ // TODO(b/188207175): consider adding Map.get() and Map.getOrDefault() private static final Matcher<ExpressionTree> MAP_METHODS = anyOf( instanceMethod() .onDescendantOf("java.util.Map") .namedAnyOf("containsKey", "containsValue") .withParameters("java.lang.Object"), instanceMethod() .onDescendantOf("java.util.Map") .namedAnyOf("isEmpty", "size", "entrySet", "keySet", "values"), staticMethod().onClass("java.util.Map").namedAnyOf("of", "copyOf", "entry", "ofEntries")); /** APIs to check on the {@link java.util.Map.Entry} interface. */ private static final Matcher<ExpressionTree> MAP_ENTRY_METHODS = anyOf( staticMethod().onClass("java.util.Map.Entry"), instanceMethod().onDescendantOf("java.util.Map.Entry").namedAnyOf("getKey", "getValue")); /** APIs to check on the {@link java.lang.Iterable} interface. */ private static final Matcher<ExpressionTree> ITERABLE_METHODS = anyOf( instanceMethod() .onDescendantOf("java.lang.Iterable") .named("iterator") .withNoParameters(), instanceMethod() .onDescendantOf("java.lang.Iterable") .named("spliterator") .withNoParameters()); /** APIs to check on the {@link java.util.Iterator} interface. */ private static final Matcher<ExpressionTree> ITERATOR_METHODS = instanceMethod().onDescendantOf("java.util.Iterator").named("hasNext").withNoParameters(); private static final Matcher<ExpressionTree> COLLECTOR_METHODS = anyOf( anyMethod().onClass("java.util.stream.Collector"), anyMethod().onClass("java.util.stream.Collectors")); /** * The return values of primitive types (e.g., {@link java.lang.Integer}) should always be checked * (except for parsing-type methods and void-returning methods, which won't be checked by * AbstractReturnValueIgnored). */ private static final Matcher<ExpressionTree> PRIMITIVE_METHODS = allOf(not(PRIMITIVE_PARSING_METHODS), PRIMITIVE_NON_PARSING_METHODS); /** * The return values of {@link java.util.Optional} methods should always be checked (except for * void-returning ones, which won't be checked by AbstractReturnValueIgnored). */ private static final Matcher<ExpressionTree> OPTIONAL_METHODS = anyMethod().onClass("java.util.Optional"); /** * The return values of {@link java.util.concurrent.TimeUnit} methods should always be checked. */ private static final Matcher<ExpressionTree> TIME_UNIT_METHODS = anyMethod().onClass("java.util.concurrent.TimeUnit"); /** APIs to check on {@code JodaTime} types. */ // TODO(kak): there's a ton more we could do here private static final Matcher<ExpressionTree> JODA_TIME_METHODS = anyOf( instanceMethod() .onDescendantOf("org.joda.time.ReadableInstant") .named("getMillis") .withNoParameters(), instanceMethod() .onDescendantOf("org.joda.time.ReadableDuration") .named("getMillis") .withNoParameters()); private static final String PROTO_MESSAGE = "com.google.protobuf.MessageLite"; /** * The return values of {@code ProtoMessage.newBuilder()}, {@code protoBuilder.build()} and {@code * protoBuilder.buildPartial()} should always be checked. */ private static final Matcher<ExpressionTree> PROTO_METHODS = anyOf( staticMethod().onDescendantOf(PROTO_MESSAGE).named("newBuilder"), instanceMethod() .onDescendantOf(PROTO_MESSAGE + ".Builder") .namedAnyOf("build", "buildPartial")); private static final Matcher<ExpressionTree> CLASS_METHODS = allOf( anyMethod().onClass("java.lang.Class"), not(staticMethod().onClass("java.lang.Class").named("forName")), not(instanceMethod().onExactClass("java.lang.Class").named("getMethod"))); private static final Matcher<ExpressionTree> OBJECT_METHODS = anyOf( instanceMethod() .onDescendantOf("java.lang.Object") .namedAnyOf("getClass", "hashCode", "clone", "toString") .withNoParameters(), instanceMethod() .onDescendantOf("java.lang.Object") .namedAnyOf("equals") .withParameters("java.lang.Object")); private static final Matcher<ExpressionTree> CHAR_SEQUENCE_METHODS = anyMethod().onClass("java.lang.CharSequence"); private static final Matcher<ExpressionTree> ENUM_METHODS = anyMethod().onClass("java.lang.Enum"); private static final Matcher<ExpressionTree> THROWABLE_METHODS = instanceMethod() .onDescendantOf("java.lang.Throwable") .namedAnyOf( "getCause", "getLocalizedMessage", "getMessage", "getStackTrace", "getSuppressed"); private static final Matcher<ExpressionTree> OBJECTS_METHODS = allOf( staticMethod().onClass("java.util.Objects"), not( staticMethod() .onClass("java.util.Objects") .namedAnyOf( "checkFromIndexSize", "checkFromToIndex", "checkIndex", "requireNonNull", "requireNonNullElse", "requireNonNullElseGet"))); /** * Constructors of Guice modules must always be used (likely a sign they were not properly * installed). */ private static final Matcher<ExpressionTree> MODULE_CONSTRUCTORS = constructor().forClass(isDescendantOf("com.google.inject.Module")); private static final Matcher<? super ExpressionTree> SPECIALIZED_MATCHER = anyOf( // keep-sorted start ARRAYS_METHODS, CHAR_SEQUENCE_METHODS, COLLECTION_METHODS, COLLECTOR_METHODS, ENUM_METHODS, ITERABLE_METHODS, ITERATOR_METHODS, JODA_TIME_METHODS, MAP_ENTRY_METHODS, MAP_METHODS, MODULE_CONSTRUCTORS, OBJECTS_METHODS, OBJECT_METHODS, OPTIONAL_METHODS, PRIMITIVE_METHODS, PROTO_METHODS, RETURNS_SAME_TYPE, ReturnValueIgnored::functionalMethod, ReturnValueIgnored::javaTimeTypes, STREAM_METHODS, STRING_METHODS, THROWABLE_METHODS, TIME_UNIT_METHODS // keep-sorted end ); private static final ImmutableBiMap<String, Matcher<ExpressionTree>> FLAG_MATCHERS = ImmutableBiMap.of("ReturnValueIgnored:ClassMethods", CLASS_METHODS); private final Matcher<ExpressionTree> matcher; @Inject ReturnValueIgnored(ErrorProneFlags flags, ConstantExpressions constantExpressions) { super(constantExpressions); this.matcher = createMatcher(flags); } private static Matcher<ExpressionTree> createMatcher(ErrorProneFlags flags) { ImmutableSet.Builder<Matcher<? super ExpressionTree>> builder = ImmutableSet.builder(); builder.add(SPECIALIZED_MATCHER); FLAG_MATCHERS.keySet().stream() .filter(flagName -> flags.getBoolean(flagName).orElse(true)) .map(FLAG_MATCHERS::get) .forEach(builder::add); return anyOf(builder.build()); } @Override public Matcher<? super ExpressionTree> specializedMatcher() { return matcher; } @Override public ImmutableMap<String, ?> getMatchMetadata(ExpressionTree tree, VisitorState state) { return FLAG_MATCHERS.values().stream() .filter(matcher -> matcher.matches(tree, state)) .findFirst() .map(FLAG_MATCHERS.inverse()::get) .map(flag -> ImmutableMap.of("flag", flag)) .orElse(ImmutableMap.of()); } @Override protected String getMessage(Name name) { return String.format("Return value of '%s' must be used", name); } }
ReturnValueIgnored
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/DeepInheritanceWithNonEntitiesProxyTest.java
{ "start": 64287, "end": 64865 }
class ____ extends AAEntity { private Boolean fieldInNonEntityAAAEntitySuperclass; public NonEntityAAAEntitySuperclass(String id) { super( id ); } protected NonEntityAAAEntitySuperclass() { } public Boolean getFieldInNonEntityAAAEntitySuperclass() { return fieldInNonEntityAAAEntitySuperclass; } public void setFieldInNonEntityAAAEntitySuperclass(Boolean fieldInNonEntityAAAEntitySuperclass) { this.fieldInNonEntityAAAEntitySuperclass = fieldInNonEntityAAAEntitySuperclass; } } @Entity(name="AAAEntity") public static
NonEntityAAAEntitySuperclass
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationMetaAnnotationTests.java
{ "start": 1956, "end": 2068 }
interface ____ { @AliasFor(annotation = Configuration.class) String value() default ""; } }
TestConfiguration
java
google__auto
value/src/main/java/com/google/auto/value/processor/ForwardingClassGenerator.java
{ "start": 2264, "end": 2393 }
class ____, say {@code Forwarder}, that is basically what you would get if you could * compile this: * * <pre>{@code * final
file
java
greenrobot__greendao
greendao-api/src/main/java/org/greenrobot/greendao/annotation/ToMany.java
{ "start": 312, "end": 791 }
interface ____ { /** * Name of the property inside the target entity which holds id of the source (current) entity * Required unless no {@link JoinProperty} or {@link JoinEntity} is specified */ String referencedJoinProperty() default ""; /** * Array of matching source -&gt; target properties * Required unless {@link #referencedJoinProperty()} or {@link JoinEntity} is specified */ JoinProperty[] joinProperties() default {}; }
ToMany
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/locking/warning/LockNoneWarningTest.java
{ "start": 2508, "end": 2775 }
class ____ implements Serializable { @Id String name; @Column(name = "i_comment") String comment; @OneToMany(mappedBy = "item", fetch = FetchType.EAGER) Set<Bid> bids = new HashSet<Bid>(); } @Entity(name = "Bid") @Table(name = "BID") public static
Item
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/stream/compact/CompactWriter.java
{ "start": 1021, "end": 1248 }
interface ____<T> { void write(T record) throws IOException; /** Commits the pending file, making it visible. */ void commit() throws IOException; /** Factory to create {@link CompactWriter}. */
CompactWriter
java
spring-projects__spring-boot
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java
{ "start": 16364, "end": 16667 }
class ____ { @Bean OverriddenOperationWebEndpointExtension overriddenOperationExtension() { return new OverriddenOperationWebEndpointExtension(); } } @Configuration(proxyBeanMethods = false) @Import(TestEndpointConfiguration.class) static
OverriddenOperationWebEndpointExtensionConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/formulajoin/AssociationFormulaTest.java
{ "start": 1110, "end": 6428 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { Child child = new Child( new EmbeddableId( "test", 2 ), "c1" ); Parent parent = new Parent( new EmbeddableId( "test", 1 ), "p1", child ); Parent parent2 = new Parent( new EmbeddableId( "null", 3 ), "p2" ); scope.inTransaction( session -> { session.persist( parent ); session.persist( parent2 ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test public void testJoin(SessionFactoryScope scope) { scope.inTransaction( session -> { Parent loaded = session.createQuery( "select e from Parent e inner join e.child o", Parent.class ).uniqueResult(); assertThat( loaded ).isNotNull(); assertThat( loaded.getId().getId2() ).isEqualTo( 1 ); assertThat( loaded.getChild().getId().getId2() ).isEqualTo( 2 ); assertThat( Hibernate.isInitialized( loaded.getChild() ) ).isFalse(); Hibernate.initialize( loaded.getChild() ); } ); } @Test public void testJoinFetch(SessionFactoryScope scope) { scope.inTransaction( session -> { Parent loaded = session.createQuery( "select e from Parent e inner join fetch e.child o", Parent.class ).uniqueResult(); assertThat( loaded ).isNotNull(); assertThat( loaded.getId().getId2() ).isEqualTo( 1 ); assertThat( Hibernate.isInitialized( loaded.getChild() ) ).isTrue(); assertThat( loaded.getChild().getId().getId2() ).isEqualTo( 2 ); } ); } @Test public void testSelect(SessionFactoryScope scope) { scope.inTransaction( session -> { Parent loaded = session.createQuery( "from Parent e where e.child is null", Parent.class ) .uniqueResult(); assertThat( loaded ).isNotNull(); assertThat( loaded.getId().getId2() ).isEqualTo( 3 ); assertThat( loaded.getChild() ).isNull(); } ); scope.inTransaction( session -> { Parent loaded = session.createQuery( "from Parent e where e.child.id.id2 is null", Parent.class ) .uniqueResult(); assertThat( loaded ).isNotNull(); assertThat( loaded.getId().getId2() ).isEqualTo( 3 ); assertThat( loaded.getChild() ).isNull(); } ); scope.inTransaction( session -> { Child child = new Child( new EmbeddableId( "test", 2 ), "c2" ); Parent loaded = session.createQuery( "from Parent e where e.child = :child", Parent.class ) .setParameter( "child", child ) .uniqueResult(); assertThat( loaded ).isNotNull(); assertThat( loaded.getId().getId2() ).isEqualTo( 1 ); assertThat( loaded.getChild() ).isNotNull(); assertThat( loaded.getChild().getId().getId2() ).isEqualTo( 2 ); } ); } @Test public void testUpdate(SessionFactoryScope scope) { scope.inTransaction( session -> { Parent loaded = session.createQuery( "from Parent e where e.id.id2 = 1", Parent.class ) .uniqueResult(); assertThat( loaded ).isNotNull(); assertThat( loaded.getChild() ).isNotNull(); Child child = new Child( new EmbeddableId( "test", 3 ), "c3" ); loaded.setChild( child ); } ); scope.inTransaction( session -> { Parent loaded = session.createQuery( "from Parent e where e.id.id2 = 3", Parent.class ) .uniqueResult(); assertThat( loaded ).isNotNull(); assertThat( loaded.getChild() ).isNull(); Child child = new Child( new EmbeddableId( "test", 4 ), "c4" ); loaded.setChild( child ); } ); } @Test public void testDelete(SessionFactoryScope scope) { scope.inTransaction( session -> { Child child = new Child( new EmbeddableId( "test", 2 ), "c2" ); assertThat( session.createMutationQuery( "delete Parent e where e.child = :child" ) .setParameter( "child", child ) .executeUpdate() ).isEqualTo( 1 ); Parent loaded = session.createQuery( "from Parent e where e.id.id2 = 1", Parent.class ) .uniqueResult(); assertThat( loaded ).isNull(); } ); } // @Test // public void testUpdateHql(SessionFactoryScope scope) { // scope.inTransaction( // session -> { // Child child = new Child( new EmbeddableId( "null", 4 ), "c4" ); // assertThat( // session.createQuery( "update Parent e set e.child = :child where e.id.id2 = 3" ) // .setParameter( "child", child ) // .executeUpdate() // ).isEqualTo( 1 ); // Parent loaded = session.createQuery( "from Parent e where e.id.id2 = 3", Parent.class ) // .uniqueResult(); // assertThat( loaded ).isNotNull(); // assertThat( loaded.getChild().getId().getId2() ).isEqualTo( 4 ); // } // ); // } // // @Test // public void testUpdateHqlNull(SessionFactoryScope scope) { // scope.inTransaction( // session -> { // assertThat( // session.createQuery( "update Parent e set e.child = null where e.id.id2 = 1" ) // .executeUpdate() // ).isEqualTo( 1 ); // Parent loaded = session.createQuery( "from Parent e where e.id.id2 = 1", Parent.class ) // .uniqueResult(); // assertThat( loaded ).isNotNull(); // assertThat( loaded.getChild().getId().getId2() ).isEqualTo( 4 ); // } // ); // } @Embeddable public static
AssociationFormulaTest
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/ClassUtils.java
{ "start": 4475, "end": 4675 }
interface ____ was found for the key. */ private static final Map<Method, Method> interfaceMethodCache = new ConcurrentReferenceHashMap<>(256); /** * Cache for equivalent methods on a public
method
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/WireTapBeanTest.java
{ "start": 1097, "end": 2012 }
class ____ extends ContextTestSupport { protected MockEndpoint tap; protected MockEndpoint result; @Test public void testSend() throws Exception { result.expectedBodiesReceived("Bye World"); tap.expectedBodiesReceived("World"); template.sendBody("direct:start", "World"); assertMockEndpointsSatisfied(); } @Override @BeforeEach public void setUp() throws Exception { super.setUp(); tap = getMockEndpoint("mock:tap"); result = getMockEndpoint("mock:result"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:start").to("log:foo").wireTap("seda:tap").bean(MyBean.class).to("mock:result"); from("seda:tap").to("mock:tap"); } }; } public static
WireTapBeanTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/idclass/IdClassWithEagerManyToOneTest.java
{ "start": 5974, "end": 6735 }
class ____ { @Id @ManyToOne private Subsystem subsystem; @Id private String username; private String name; public SystemUser(Subsystem subsystem, String username, String name) { this.subsystem = subsystem; this.username = username; this.name = name; } private SystemUser() { } public Subsystem getSubsystem() { return subsystem; } public void setSubsystem(Subsystem subsystem) { this.subsystem = subsystem; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity(name = "Subsystem") public static
SystemUser
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/aop/introduction/with_around/MyBean3.java
{ "start": 702, "end": 1043 }
class ____ { private Long id; private String name; public MyBean3() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
MyBean3
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabase.java
{ "start": 1050, "end": 1168 }
interface ____ extends DataSource { /** * Shut down this embedded database. */ void shutdown(); }
EmbeddedDatabase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/EmbeddableWithParentWithInheritanceTest.java
{ "start": 2305, "end": 2789 }
class ____ { Long id; String description; public Food() { } public String describe() { return "Good food"; } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } @Entity(name = "Roquefort") @DiscriminatorValue("ROQUEFORT") public static
Food
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/db2/DB2SelectTest_13.java
{ "start": 1085, "end": 3157 }
class ____ extends DB2Test { public void test_0() throws Exception { String sql = "SELECT WORKDEPT, EMPNO, SALARY, BONUS, COMM "// + " FROM DSN8B10.EMP"// + " WHERE WORKDEPT IN ('D11','D21')" + " FOR UPDATE;"; DB2StatementParser parser = new DB2StatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); DB2SchemaStatVisitor visitor = new DB2SchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(5, visitor.getColumns().size()); assertEquals(1, visitor.getConditions().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("DSN8B10.EMP"))); assertTrue(visitor.getColumns().contains(new Column("DSN8B10.EMP", "WORKDEPT"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "first_name"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "full_name"))); assertEquals("SELECT WORKDEPT, EMPNO, SALARY, BONUS, COMM" + "\nFROM DSN8B10.EMP" + "\nWHERE WORKDEPT IN ('D11', 'D21')" + "\nFOR UPDATE;", // SQLUtils.toSQLString(stmt, JdbcConstants.DB2)); assertEquals("select WORKDEPT, EMPNO, SALARY, BONUS, COMM" + "\nfrom DSN8B10.EMP" + "\nwhere WORKDEPT in ('D11', 'D21')" + "\nfor update;", // SQLUtils.toSQLString(stmt, JdbcConstants.DB2, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); } }
DB2SelectTest_13
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/ParameterMissingNullableTest.java
{ "start": 2181, "end": 2940 }
class ____ { void foo(boolean b, Integer i) { if (b) { // BUG: Diagnostic contains: @Nullable int val = i == null ? 0 : i; if (val < 0) { throw new RuntimeException(); } } } } """) .doTest(); } @Test public void positiveDespiteWhileLoop() { // TODO(cpovirk): This doesn't look "positive" to me. // TODO(cpovirk): Also, I *think* the lack of braces on the while() loop is intentional? aggressiveHelper .addSourceLines( "Foo.java", """ import static com.google.common.base.Preconditions.checkArgument;
Foo
java
quarkusio__quarkus
extensions/vertx-http/deployment-spi/src/main/java/io/quarkus/vertx/http/deployment/spi/RouteBuildItem.java
{ "start": 9489, "end": 10459 }
interface ____ enabled and if the property is set to {@code false}, the route is exposed on the main HTTP * server. * The {@code quarkus.http.non-application-root-path} property is applied in front of the route path (defaults to * {@code /q}). * * @param path the path, must not be {@code null} or empty. * @return the builder to configure the route */ public static Builder newManagementRoute(String path, String managementConfigKey) { return new Builder(RouteType.FRAMEWORK_ROUTE, path, (managementConfigKey == null || isManagement(managementConfigKey))); } private static boolean isManagement(String managementConfigKey) { Config config = ConfigProvider.getConfig(); return config.getValue(managementConfigKey, boolean.class); } public boolean isManagement() { return isManagement; } /** * A builder to configure the route. */ public static
is
java
quarkusio__quarkus
test-framework/junit5-component/src/main/java/io/quarkus/test/component/MockBeanConfigurator.java
{ "start": 314, "end": 1166 }
interface ____<T> { MockBeanConfigurator<T> types(Class<?>... types); MockBeanConfigurator<T> types(java.lang.reflect.Type types); MockBeanConfigurator<T> qualifiers(Annotation... qualifiers); MockBeanConfigurator<T> scope(Class<? extends Annotation> scope); MockBeanConfigurator<T> name(String name); MockBeanConfigurator<T> alternative(boolean alternative); MockBeanConfigurator<T> priority(int priority); MockBeanConfigurator<T> defaultBean(boolean defaultBean); /** * Set the function used to create a new bean instance and register this configurator. * * @param create * @return the test extension */ QuarkusComponentTestExtensionBuilder create(Function<SyntheticCreationalContext<T>, T> create); /** * A Mockito mock object created from the bean
MockBeanConfigurator
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java
{ "start": 1963, "end": 8353 }
class ____ implements Iterable<String> { /** * Name of property to set to specify additionally included active profiles. */ public static final String INCLUDE_PROFILES_PROPERTY_NAME = "spring.profiles.include"; static final ConfigurationPropertyName INCLUDE_PROFILES = ConfigurationPropertyName .of(Profiles.INCLUDE_PROFILES_PROPERTY_NAME); private static final Bindable<MultiValueMap<String, String>> STRING_STRINGS_MAP = Bindable .of(ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class)); private static final Bindable<Set<String>> STRING_SET = Bindable.setOf(String.class); private final MultiValueMap<String, String> groups; private final List<String> activeProfiles; private final List<String> defaultProfiles; /** * Create a new {@link Profiles} instance based on the {@link Environment} and * {@link Binder}. * @param environment the source environment * @param binder the binder for profile properties * @param additionalProfiles any additional active profiles */ Profiles(Environment environment, Binder binder, @Nullable Collection<String> additionalProfiles) { ProfilesValidator validator = ProfilesValidator.get(binder); if (additionalProfiles != null) { validator.validate(additionalProfiles, () -> "Invalid profile property value found in additional profiles"); } this.groups = binder.bind("spring.profiles.group", STRING_STRINGS_MAP, validator) .orElseGet(LinkedMultiValueMap::new); this.activeProfiles = expandProfiles(getActivatedProfiles(environment, binder, validator, additionalProfiles)); this.defaultProfiles = expandProfiles(getDefaultProfiles(environment, binder, validator)); } private List<String> getActivatedProfiles(Environment environment, Binder binder, ProfilesValidator validator, @Nullable Collection<String> additionalProfiles) { return asUniqueItemList(getProfiles(environment, binder, validator, Type.ACTIVE), additionalProfiles); } private List<String> getDefaultProfiles(Environment environment, Binder binder, ProfilesValidator validator) { return asUniqueItemList(getProfiles(environment, binder, validator, Type.DEFAULT)); } private Collection<String> getProfiles(Environment environment, Binder binder, ProfilesValidator validator, Type type) { String environmentPropertyValue = environment.getProperty(type.getName()); Set<String> environmentPropertyProfiles = (!StringUtils.hasLength(environmentPropertyValue)) ? Collections.emptySet() : StringUtils.commaDelimitedListToSet(StringUtils.trimAllWhitespace(environmentPropertyValue)); validator.validate(environmentPropertyProfiles, () -> "Invalid profile property value found in Environment under '%s'".formatted(type.getName())); Set<String> environmentProfiles = new LinkedHashSet<>(Arrays.asList(type.get(environment))); BindResult<Set<String>> boundProfiles = binder.bind(type.getName(), STRING_SET, validator); if (hasProgrammaticallySetProfiles(type, environmentPropertyValue, environmentPropertyProfiles, environmentProfiles)) { if (!type.isMergeWithEnvironmentProfiles() || !boundProfiles.isBound()) { return environmentProfiles; } return boundProfiles.map((bound) -> merge(environmentProfiles, bound)).get(); } return boundProfiles.orElse(type.getDefaultValue()); } private boolean hasProgrammaticallySetProfiles(Type type, @Nullable String environmentPropertyValue, Set<String> environmentPropertyProfiles, Set<String> environmentProfiles) { if (!StringUtils.hasLength(environmentPropertyValue)) { return !type.getDefaultValue().equals(environmentProfiles); } if (type.getDefaultValue().equals(environmentProfiles)) { return false; } return !environmentPropertyProfiles.equals(environmentProfiles); } private Set<String> merge(Set<String> environmentProfiles, Set<String> bound) { Set<String> result = new LinkedHashSet<>(environmentProfiles); result.addAll(bound); return result; } private List<String> expandProfiles(@Nullable List<String> profiles) { Deque<String> stack = new ArrayDeque<>(); asReversedList(profiles).forEach(stack::push); Set<String> expandedProfiles = new LinkedHashSet<>(); while (!stack.isEmpty()) { String current = stack.pop(); if (expandedProfiles.add(current)) { asReversedList(this.groups.get(current)).forEach(stack::push); } } return asUniqueItemList(expandedProfiles); } private List<String> asReversedList(@Nullable List<String> list) { if (CollectionUtils.isEmpty(list)) { return Collections.emptyList(); } List<String> reversed = new ArrayList<>(list); Collections.reverse(reversed); return reversed; } private List<String> asUniqueItemList(Collection<String> profiles) { return asUniqueItemList(profiles, null); } private List<String> asUniqueItemList(Collection<String> profiles, @Nullable Collection<String> additional) { LinkedHashSet<String> uniqueItems = new LinkedHashSet<>(); if (!CollectionUtils.isEmpty(additional)) { uniqueItems.addAll(additional); } uniqueItems.addAll(profiles); return Collections.unmodifiableList(new ArrayList<>(uniqueItems)); } /** * Return an iterator for all {@link #getAccepted() accepted profiles}. */ @Override public Iterator<String> iterator() { return getAccepted().iterator(); } /** * Return the active profiles. * @return the active profiles */ public List<String> getActive() { return this.activeProfiles; } /** * Return the default profiles. * @return the active profiles */ public List<String> getDefault() { return this.defaultProfiles; } /** * Return the accepted profiles. * @return the accepted profiles */ public List<String> getAccepted() { return (!this.activeProfiles.isEmpty()) ? this.activeProfiles : this.defaultProfiles; } /** * Return if the given profile is active. * @param profile the profile to test * @return if the profile is active */ public boolean isAccepted(String profile) { return getAccepted().contains(profile); } @Override public String toString() { ToStringCreator creator = new ToStringCreator(this); creator.append("active", getActive().toString()); creator.append("default", getDefault().toString()); creator.append("accepted", getAccepted().toString()); return creator.toString(); } /** * A profiles type that can be obtained. */ private
Profiles
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/RoleChangeNotifyEntry.java
{ "start": 1107, "end": 3177 }
class ____ { private final BrokerMemberGroup brokerMemberGroup; private final String masterAddress; private final Long masterBrokerId; private final int masterEpoch; private final int syncStateSetEpoch; private final Set<Long> syncStateSet; public RoleChangeNotifyEntry(BrokerMemberGroup brokerMemberGroup, String masterAddress, Long masterBrokerId, int masterEpoch, int syncStateSetEpoch, Set<Long> syncStateSet) { this.brokerMemberGroup = brokerMemberGroup; this.masterAddress = masterAddress; this.masterEpoch = masterEpoch; this.syncStateSetEpoch = syncStateSetEpoch; this.masterBrokerId = masterBrokerId; this.syncStateSet = syncStateSet; } public static RoleChangeNotifyEntry convert(RemotingCommand electMasterResponse) { final ElectMasterResponseHeader header = (ElectMasterResponseHeader) electMasterResponse.readCustomHeader(); BrokerMemberGroup brokerMemberGroup = null; Set<Long> syncStateSet = null; if (electMasterResponse.getBody() != null && electMasterResponse.getBody().length > 0) { ElectMasterResponseBody body = RemotingSerializable.decode(electMasterResponse.getBody(), ElectMasterResponseBody.class); brokerMemberGroup = body.getBrokerMemberGroup(); syncStateSet = body.getSyncStateSet(); } return new RoleChangeNotifyEntry(brokerMemberGroup, header.getMasterAddress(), header.getMasterBrokerId(), header.getMasterEpoch(), header.getSyncStateSetEpoch(), syncStateSet); } public BrokerMemberGroup getBrokerMemberGroup() { return brokerMemberGroup; } public String getMasterAddress() { return masterAddress; } public int getMasterEpoch() { return masterEpoch; } public int getSyncStateSetEpoch() { return syncStateSetEpoch; } public Long getMasterBrokerId() { return masterBrokerId; } public Set<Long> getSyncStateSet() { return syncStateSet; } }
RoleChangeNotifyEntry
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/collection/bag/MultipleBagFetchHqlTest.java
{ "start": 3274, "end": 4144 }
class ____ { @Id private Long id; private String title; @OneToMany(fetch = FetchType.LAZY) private List<PostComment> comments = new ArrayList<PostComment>(); @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "post_tag", joinColumns = @JoinColumn(name = "post_id"), inverseJoinColumns = @JoinColumn(name = "tag_id") ) private List<Tag> tags = new ArrayList<>(); public Post() { } public Post(Long id) { this.id = id; } public Post(String title) { this.title = title; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<Tag> getTags() { return tags; } } @Entity(name = "PostComment") @Table(name = "post_comment") public static
Post
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableBufferBoundary.java
{ "start": 11059, "end": 12772 }
class ____<T, C extends Collection<? super T>> extends AtomicReference<Subscription> implements FlowableSubscriber<Object>, Disposable { private static final long serialVersionUID = -8498650778633225126L; final BufferBoundarySubscriber<T, C, ?, ?> parent; final long index; BufferCloseSubscriber(BufferBoundarySubscriber<T, C, ?, ?> parent, long index) { this.parent = parent; this.index = index; } @Override public void onSubscribe(Subscription s) { SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override public void onNext(Object t) { Subscription s = get(); if (s != SubscriptionHelper.CANCELLED) { lazySet(SubscriptionHelper.CANCELLED); s.cancel(); parent.close(this, index); } } @Override public void onError(Throwable t) { if (get() != SubscriptionHelper.CANCELLED) { lazySet(SubscriptionHelper.CANCELLED); parent.boundaryError(this, t); } else { RxJavaPlugins.onError(t); } } @Override public void onComplete() { if (get() != SubscriptionHelper.CANCELLED) { lazySet(SubscriptionHelper.CANCELLED); parent.close(this, index); } } @Override public void dispose() { SubscriptionHelper.cancel(this); } @Override public boolean isDisposed() { return get() == SubscriptionHelper.CANCELLED; } } }
BufferCloseSubscriber
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableSkipUntil.java
{ "start": 2798, "end": 3800 }
class ____ implements Observer<U> { final ArrayCompositeDisposable frc; final SkipUntilObserver<T> sus; final SerializedObserver<T> serial; Disposable upstream; SkipUntil(ArrayCompositeDisposable frc, SkipUntilObserver<T> sus, SerializedObserver<T> serial) { this.frc = frc; this.sus = sus; this.serial = serial; } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { this.upstream = d; frc.setResource(1, d); } } @Override public void onNext(U t) { upstream.dispose(); sus.notSkipping = true; } @Override public void onError(Throwable t) { frc.dispose(); serial.onError(t); } @Override public void onComplete() { sus.notSkipping = true; } } }
SkipUntil
java
greenrobot__greendao
tests/DaoTestBase/src/main/java/org/greenrobot/greendao/daotest/SimpleEntityNotNullDao.java
{ "start": 786, "end": 6993 }
class ____ { public final static Property Id = new Property(0, long.class, "id", true, "_id"); public final static Property SimpleBoolean = new Property(1, boolean.class, "simpleBoolean", false, "SIMPLE_BOOLEAN"); public final static Property SimpleByte = new Property(2, byte.class, "simpleByte", false, "SIMPLE_BYTE"); public final static Property SimpleShort = new Property(3, short.class, "simpleShort", false, "SIMPLE_SHORT"); public final static Property SimpleInt = new Property(4, int.class, "simpleInt", false, "SIMPLE_INT"); public final static Property SimpleLong = new Property(5, long.class, "simpleLong", false, "SIMPLE_LONG"); public final static Property SimpleFloat = new Property(6, float.class, "simpleFloat", false, "SIMPLE_FLOAT"); public final static Property SimpleDouble = new Property(7, double.class, "simpleDouble", false, "SIMPLE_DOUBLE"); public final static Property SimpleString = new Property(8, String.class, "simpleString", false, "SIMPLE_STRING"); public final static Property SimpleByteArray = new Property(9, byte[].class, "simpleByteArray", false, "SIMPLE_BYTE_ARRAY"); } public SimpleEntityNotNullDao(DaoConfig config) { super(config); } public SimpleEntityNotNullDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(Database db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"SIMPLE_ENTITY_NOT_NULL\" (" + // "\"_id\" INTEGER PRIMARY KEY NOT NULL ," + // 0: id "\"SIMPLE_BOOLEAN\" INTEGER NOT NULL ," + // 1: simpleBoolean "\"SIMPLE_BYTE\" INTEGER NOT NULL ," + // 2: simpleByte "\"SIMPLE_SHORT\" INTEGER NOT NULL ," + // 3: simpleShort "\"SIMPLE_INT\" INTEGER NOT NULL ," + // 4: simpleInt "\"SIMPLE_LONG\" INTEGER NOT NULL ," + // 5: simpleLong "\"SIMPLE_FLOAT\" REAL NOT NULL ," + // 6: simpleFloat "\"SIMPLE_DOUBLE\" REAL NOT NULL ," + // 7: simpleDouble "\"SIMPLE_STRING\" TEXT NOT NULL ," + // 8: simpleString "\"SIMPLE_BYTE_ARRAY\" BLOB NOT NULL );"); // 9: simpleByteArray } /** Drops the underlying database table. */ public static void dropTable(Database db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"SIMPLE_ENTITY_NOT_NULL\""; db.execSQL(sql); } @Override protected final void bindValues(DatabaseStatement stmt, SimpleEntityNotNull entity) { stmt.clearBindings(); stmt.bindLong(1, entity.getId()); stmt.bindLong(2, entity.getSimpleBoolean() ? 1L: 0L); stmt.bindLong(3, entity.getSimpleByte()); stmt.bindLong(4, entity.getSimpleShort()); stmt.bindLong(5, entity.getSimpleInt()); stmt.bindLong(6, entity.getSimpleLong()); stmt.bindDouble(7, entity.getSimpleFloat()); stmt.bindDouble(8, entity.getSimpleDouble()); stmt.bindString(9, entity.getSimpleString()); stmt.bindBlob(10, entity.getSimpleByteArray()); } @Override protected final void bindValues(SQLiteStatement stmt, SimpleEntityNotNull entity) { stmt.clearBindings(); stmt.bindLong(1, entity.getId()); stmt.bindLong(2, entity.getSimpleBoolean() ? 1L: 0L); stmt.bindLong(3, entity.getSimpleByte()); stmt.bindLong(4, entity.getSimpleShort()); stmt.bindLong(5, entity.getSimpleInt()); stmt.bindLong(6, entity.getSimpleLong()); stmt.bindDouble(7, entity.getSimpleFloat()); stmt.bindDouble(8, entity.getSimpleDouble()); stmt.bindString(9, entity.getSimpleString()); stmt.bindBlob(10, entity.getSimpleByteArray()); } @Override public Long readKey(Cursor cursor, int offset) { return cursor.getLong(offset + 0); } @Override public SimpleEntityNotNull readEntity(Cursor cursor, int offset) { SimpleEntityNotNull entity = new SimpleEntityNotNull( // cursor.getLong(offset + 0), // id cursor.getShort(offset + 1) != 0, // simpleBoolean (byte) cursor.getShort(offset + 2), // simpleByte cursor.getShort(offset + 3), // simpleShort cursor.getInt(offset + 4), // simpleInt cursor.getLong(offset + 5), // simpleLong cursor.getFloat(offset + 6), // simpleFloat cursor.getDouble(offset + 7), // simpleDouble cursor.getString(offset + 8), // simpleString cursor.getBlob(offset + 9) // simpleByteArray ); return entity; } @Override public void readEntity(Cursor cursor, SimpleEntityNotNull entity, int offset) { entity.setId(cursor.getLong(offset + 0)); entity.setSimpleBoolean(cursor.getShort(offset + 1) != 0); entity.setSimpleByte((byte) cursor.getShort(offset + 2)); entity.setSimpleShort(cursor.getShort(offset + 3)); entity.setSimpleInt(cursor.getInt(offset + 4)); entity.setSimpleLong(cursor.getLong(offset + 5)); entity.setSimpleFloat(cursor.getFloat(offset + 6)); entity.setSimpleDouble(cursor.getDouble(offset + 7)); entity.setSimpleString(cursor.getString(offset + 8)); entity.setSimpleByteArray(cursor.getBlob(offset + 9)); } @Override protected final Long updateKeyAfterInsert(SimpleEntityNotNull entity, long rowId) { entity.setId(rowId); return rowId; } @Override public Long getKey(SimpleEntityNotNull entity) { if(entity != null) { return entity.getId(); } else { return null; } } @Override public boolean hasKey(SimpleEntityNotNull entity) { throw new UnsupportedOperationException("Unsupported for entities with a non-null key"); } @Override protected final boolean isEntityUpdateable() { return true; } }
Properties
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/permission/PermissionParser.java
{ "start": 1046, "end": 1280 }
class ____ parsing either chmod permissions or umask permissions. * Includes common code needed by either operation as implemented in * UmaskParser and ChmodParser classes. */ @InterfaceAudience.Private @InterfaceStability.Unstable
for
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/InvocationInterceptor.java
{ "start": 2416, "end": 2603 }
class ____ <em>not</em> have been initialized * (static initialization) when this method is invoked. * * <p>By default, the supplied {@link ExtensionContext} represents the test *
may
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/MutableVertexParallelismStore.java
{ "start": 981, "end": 1573 }
interface ____ extends VertexParallelismStore { /** * Sets the parallelism properties for the given vertex. * * @param vertexId vertex to set parallelism for * @param info parallelism information for the given vertex */ void setParallelismInfo(JobVertexID vertexId, VertexParallelismInformation info); /** * Merges the given parallelism store into the current store. * * @param parallelismStore The parallelism store to be merged. */ void mergeParallelismStore(VertexParallelismStore parallelismStore); }
MutableVertexParallelismStore
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/QueueEndpointBuilderFactory.java
{ "start": 1450, "end": 1603 }
interface ____ { /** * Builder for endpoint consumers for the Azure Storage Queue Service component. */ public
QueueEndpointBuilderFactory
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/agent/Agent.java
{ "start": 2121, "end": 9960 }
class ____ { /** * The default Agent port. */ public static final int DEFAULT_PORT = 8888; /** * The workerId to use in exec mode. */ private static final long EXEC_WORKER_ID = 1; /** * The taskId to use in exec mode. */ private static final String EXEC_TASK_ID = "task0"; /** * The platform object to use for this agent. */ private final Platform platform; /** * The time at which this server was started. */ private final long serverStartMs; /** * The WorkerManager. */ private final WorkerManager workerManager; /** * The REST server. */ private final JsonRestServer restServer; private final Time time; /** * Create a new Agent. * * @param platform The platform object to use. * @param scheduler The scheduler to use for this Agent. * @param restServer The REST server to use. * @param resource The AgentRestResource to use. */ public Agent(Platform platform, Scheduler scheduler, JsonRestServer restServer, AgentRestResource resource) { this.platform = platform; this.time = scheduler.time(); this.serverStartMs = time.milliseconds(); this.workerManager = new WorkerManager(platform, scheduler); this.restServer = restServer; resource.setAgent(this); } public int port() { return this.restServer.port(); } public void beginShutdown() throws Exception { restServer.beginShutdown(); workerManager.beginShutdown(); } public void waitForShutdown() throws Exception { restServer.waitForShutdown(); workerManager.waitForShutdown(); } public AgentStatusResponse status() throws Exception { return new AgentStatusResponse(serverStartMs, workerManager.workerStates()); } public UptimeResponse uptime() { return new UptimeResponse(serverStartMs, time.milliseconds()); } public void createWorker(CreateWorkerRequest req) throws Throwable { workerManager.createWorker(req.workerId(), req.taskId(), req.spec()); } public void stopWorker(StopWorkerRequest req) throws Throwable { workerManager.stopWorker(req.workerId(), false); } public void destroyWorker(DestroyWorkerRequest req) throws Throwable { workerManager.stopWorker(req.workerId(), true); } /** * Rebase the task spec time so that it is not earlier than the current time. * This is only needed for tasks passed in with --exec. Normally, the * controller rebases the task spec time. */ TaskSpec rebaseTaskSpecTime(TaskSpec spec) throws Exception { ObjectNode node = JsonUtil.JSON_SERDE.valueToTree(spec); node.set("startMs", new LongNode(Math.max(time.milliseconds(), spec.startMs()))); return JsonUtil.JSON_SERDE.treeToValue(node, TaskSpec.class); } /** * Start a task on the agent, and block until it completes. * * @param spec The task specification. * @param out The output stream to print to. * * @return True if the task run successfully; false otherwise. */ boolean exec(TaskSpec spec, PrintStream out) throws Exception { TaskController controller; try { controller = spec.newController(EXEC_TASK_ID); } catch (Exception e) { out.println("Unable to create the task controller."); e.printStackTrace(out); return false; } Set<String> nodes = controller.targetNodes(platform.topology()); if (!nodes.contains(platform.curNode().name())) { out.println("This task is not configured to run on this node. It runs on node(s): " + String.join(", ", nodes) + ", whereas this node is " + platform.curNode().name()); return false; } KafkaFuture<String> future; try { future = workerManager.createWorker(EXEC_WORKER_ID, EXEC_TASK_ID, spec); } catch (Throwable e) { out.println("createWorker failed"); e.printStackTrace(out); return false; } out.println("Waiting for completion of task:" + JsonUtil.toPrettyJsonString(spec)); String error = future.get(); if (error == null || error.isEmpty()) { out.println("Task succeeded with status " + JsonUtil.toPrettyJsonString(workerManager.workerStates().get(EXEC_WORKER_ID).status())); return true; } else { out.println("Task failed with status " + JsonUtil.toPrettyJsonString(workerManager.workerStates().get(EXEC_WORKER_ID).status()) + " and error " + error); return false; } } public static void main(String[] args) throws Exception { ArgumentParser parser = ArgumentParsers .newArgumentParser("trogdor-agent") .defaultHelp(true) .description("The Trogdor fault injection agent"); parser.addArgument("--agent.config", "-c") .action(store()) .required(true) .type(String.class) .dest("config") .metavar("CONFIG") .help("The configuration file to use."); parser.addArgument("--node-name", "-n") .action(store()) .required(true) .type(String.class) .dest("node_name") .metavar("NODE_NAME") .help("The name of this node."); parser.addArgument("--exec", "-e") .action(store()) .type(String.class) .dest("task_spec") .metavar("TASK_SPEC") .help("Execute a single task spec and then exit. The argument is the task spec to load when starting up, or a path to it."); Namespace res = null; try { res = parser.parseArgs(args); } catch (ArgumentParserException e) { if (args.length == 0) { parser.printHelp(); Exit.exit(0); } else { parser.handleError(e); Exit.exit(1); } } String configPath = res.getString("config"); String nodeName = res.getString("node_name"); String taskSpec = res.getString("task_spec"); Platform platform = Platform.Config.parse(nodeName, configPath); JsonRestServer restServer = new JsonRestServer(Node.Util.getTrogdorAgentPort(platform.curNode())); AgentRestResource resource = new AgentRestResource(); System.out.println("Starting agent process."); final Agent agent = new Agent(platform, Scheduler.SYSTEM, restServer, resource); restServer.start(resource); Exit.addShutdownHook("agent-shutdown-hook", () -> { System.out.println("Running agent shutdown hook."); try { agent.beginShutdown(); agent.waitForShutdown(); } catch (Exception e) { System.out.println("Got exception while running agent shutdown hook. " + e); } }); if (taskSpec != null) { TaskSpec spec = null; try { spec = JsonUtil.objectFromCommandLineArgument(taskSpec, TaskSpec.class); } catch (Exception e) { System.out.println("Unable to parse the supplied task spec."); e.printStackTrace(); Exit.exit(1); } TaskSpec effectiveSpec = agent.rebaseTaskSpecTime(spec); Exit.exit(agent.exec(effectiveSpec, System.out) ? 0 : 1); } agent.waitForShutdown(); } }
Agent
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/jobmanager/Tasks.java
{ "start": 1416, "end": 2494 }
class ____ extends AbstractInvokable { public Forwarder(Environment environment) { super(environment); } @Override public void invoke() throws Exception { final RecordReader<IntValue> reader = new RecordReader<>( getEnvironment().getInputGate(0), IntValue.class, getEnvironment().getTaskManagerInfo().getTmpDirectories()); final RecordWriter<IntValue> writer = new RecordWriterBuilder<IntValue>().build(getEnvironment().getWriter(0)); try { while (true) { final IntValue record = reader.next(); if (record == null) { return; } writer.emit(record); } } finally { writer.close(); } } } /** An {@link AbstractInvokable} that consumes 1 input channel. */ public static
Forwarder
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/HAServiceTarget.java
{ "start": 1593, "end": 7969 }
class ____ { private static final String HOST_SUBST_KEY = "host"; private static final String PORT_SUBST_KEY = "port"; private static final String ADDRESS_SUBST_KEY = "address"; /** * The HAState this service target is intended to be after transition * is complete. */ private HAServiceProtocol.HAServiceState transitionTargetHAStatus; /** * @return the IPC address of the target node. */ public abstract InetSocketAddress getAddress(); /** * Returns an optional separate RPC server address for health checks at the * target node. If defined, then this address is used by the health monitor * for the {@link HAServiceProtocol#monitorHealth()} and * {@link HAServiceProtocol#getServiceStatus()} calls. This can be useful for * separating out these calls onto separate RPC handlers to protect against * resource exhaustion in the main RPC handler pool. If null (which is the * default implementation), then all RPC calls go to the address defined by * {@link #getAddress()}. * * @return IPC address of the lifeline RPC server on the target node, or null * if no lifeline RPC server is used */ public InetSocketAddress getHealthMonitorAddress() { return null; } /** * @return the IPC address of the ZKFC on the target node */ public abstract InetSocketAddress getZKFCAddress(); /** * @return a Fencer implementation configured for this target node */ public abstract NodeFencer getFencer(); /** * @throws BadFencingConfigurationException if the fencing configuration * appears to be invalid. This is divorced from the above * {@link #getFencer()} method so that the configuration can be checked * during the pre-flight phase of failover. */ public abstract void checkFencingConfigured() throws BadFencingConfigurationException; /** * @return a proxy to connect to the target HA Service. * @param timeoutMs timeout in milliseconds. * @param conf Configuration. * @throws IOException raised on errors performing I/O. */ public HAServiceProtocol getProxy(Configuration conf, int timeoutMs) throws IOException { return getProxyForAddress(conf, timeoutMs, getAddress()); } public void setTransitionTargetHAStatus( HAServiceProtocol.HAServiceState status) { this.transitionTargetHAStatus = status; } public HAServiceProtocol.HAServiceState getTransitionTargetHAStatus() { return this.transitionTargetHAStatus; } /** * Returns a proxy to connect to the target HA service for health monitoring. * If {@link #getHealthMonitorAddress()} is implemented to return a non-null * address, then this proxy will connect to that address. Otherwise, the * returned proxy defaults to using {@link #getAddress()}, which means this * method's behavior is identical to {@link #getProxy(Configuration, int)}. * * @param conf configuration. * @param timeoutMs timeout in milliseconds * @return a proxy to connect to the target HA service for health monitoring * @throws IOException if there is an error */ public HAServiceProtocol getHealthMonitorProxy(Configuration conf, int timeoutMs) throws IOException { return getHealthMonitorProxy(conf, timeoutMs, 1); } public HAServiceProtocol getHealthMonitorProxy(Configuration conf, int timeoutMs, int retries) throws IOException { InetSocketAddress addr = getHealthMonitorAddress(); if (addr == null) { addr = getAddress(); } return getProxyForAddress(conf, timeoutMs, retries, addr); } private HAServiceProtocol getProxyForAddress(Configuration conf, int timeoutMs, InetSocketAddress addr) throws IOException { // Lower the timeout by setting retries to 1, so we quickly fail to connect return getProxyForAddress(conf, timeoutMs, 1, addr); } private HAServiceProtocol getProxyForAddress(Configuration conf, int timeoutMs, int retries, InetSocketAddress addr) throws IOException { Configuration confCopy = new Configuration(conf); confCopy.setInt( CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY, retries); SocketFactory factory = NetUtils.getDefaultSocketFactory(confCopy); return new HAServiceProtocolClientSideTranslatorPB( addr, confCopy, factory, timeoutMs); } /** * @return a proxy to the ZKFC which is associated with this HA service. * @param conf configuration. * @param timeoutMs timeout in milliseconds. * @throws IOException raised on errors performing I/O. */ public ZKFCProtocol getZKFCProxy(Configuration conf, int timeoutMs) throws IOException { Configuration confCopy = new Configuration(conf); // Lower the timeout so we quickly fail to connect confCopy.setInt(CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY, 1); SocketFactory factory = NetUtils.getDefaultSocketFactory(confCopy); return new ZKFCProtocolClientSideTranslatorPB( getZKFCAddress(), confCopy, factory, timeoutMs); } public final Map<String, String> getFencingParameters() { Map<String, String> ret = Maps.newHashMap(); addFencingParameters(ret); return ret; } /** * Hook to allow subclasses to add any parameters they would like to * expose to fencing implementations/scripts. Fencing methods are free * to use this map as they see fit -- notably, the shell script * implementation takes each entry, prepends 'target_', substitutes * '_' for '.' and '-', and adds it to the environment of the script. * * Subclass implementations should be sure to delegate to the superclass * implementation as well as adding their own keys. * * @param ret map which can be mutated to pass parameters to the fencer */ protected void addFencingParameters(Map<String, String> ret) { ret.put(ADDRESS_SUBST_KEY, String.valueOf(getAddress())); ret.put(HOST_SUBST_KEY, getAddress().getHostName()); ret.put(PORT_SUBST_KEY, String.valueOf(getAddress().getPort())); } /** * @return true if auto failover should be considered enabled */ public boolean isAutoFailoverEnabled() { return false; } /** * @return true if this target supports the Observer state, false otherwise. */ public boolean supportObserver() { return false; } }
HAServiceTarget
java
apache__kafka
streams/examples/src/test/java/org/apache/kafka/streams/examples/docs/DeveloperGuideTesting.java
{ "start": 2114, "end": 6047 }
class ____ { private TopologyTestDriver testDriver; private TestInputTopic<String, Long> inputTopic; private TestOutputTopic<String, Long> outputTopic; private KeyValueStore<String, Long> store; private final Serde<String> stringSerde = new Serdes.StringSerde(); private final Serde<Long> longSerde = new Serdes.LongSerde(); @BeforeEach public void setup() { final Topology topology = new Topology(); topology.addSource("sourceProcessor", "input-topic"); topology.addProcessor("aggregator", new CustomMaxAggregatorSupplier(), "sourceProcessor"); topology.addStateStore( Stores.keyValueStoreBuilder( Stores.inMemoryKeyValueStore("aggStore"), Serdes.String(), Serdes.Long()).withLoggingDisabled(), // need to disable logging to allow store pre-populating "aggregator"); topology.addSink("sinkProcessor", "result-topic", "aggregator"); // setup test driver final Properties props = new Properties(); props.setProperty(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class.getName()); props.setProperty(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.LongSerde.class.getName()); testDriver = new TopologyTestDriver(topology, props); // setup test topics inputTopic = testDriver.createInputTopic("input-topic", stringSerde.serializer(), longSerde.serializer()); outputTopic = testDriver.createOutputTopic("result-topic", stringSerde.deserializer(), longSerde.deserializer()); // pre-populate store store = testDriver.getKeyValueStore("aggStore"); store.put("a", 21L); } @AfterEach public void tearDown() { testDriver.close(); } @Test public void shouldFlushStoreForFirstInput() { inputTopic.pipeInput("a", 1L); assertThat(outputTopic.readKeyValue(), equalTo(new KeyValue<>("a", 21L))); assertThat(outputTopic.isEmpty(), is(true)); } @Test public void shouldNotUpdateStoreForSmallerValue() { inputTopic.pipeInput("a", 1L); assertThat(store.get("a"), equalTo(21L)); assertThat(outputTopic.readKeyValue(), equalTo(new KeyValue<>("a", 21L))); assertThat(outputTopic.isEmpty(), is(true)); } @Test public void shouldNotUpdateStoreForLargerValue() { inputTopic.pipeInput("a", 42L); assertThat(store.get("a"), equalTo(42L)); assertThat(outputTopic.readKeyValue(), equalTo(new KeyValue<>("a", 42L))); assertThat(outputTopic.isEmpty(), is(true)); } @Test public void shouldUpdateStoreForNewKey() { inputTopic.pipeInput("b", 21L); assertThat(store.get("b"), equalTo(21L)); assertThat(outputTopic.readKeyValue(), equalTo(new KeyValue<>("a", 21L))); assertThat(outputTopic.readKeyValue(), equalTo(new KeyValue<>("b", 21L))); assertThat(outputTopic.isEmpty(), is(true)); } @Test public void shouldPunctuateIfEvenTimeAdvances() { final Instant recordTime = Instant.now(); inputTopic.pipeInput("a", 1L, recordTime); assertThat(outputTopic.readKeyValue(), equalTo(new KeyValue<>("a", 21L))); inputTopic.pipeInput("a", 1L, recordTime); assertThat(outputTopic.isEmpty(), is(true)); inputTopic.pipeInput("a", 1L, recordTime.plusSeconds(10L)); assertThat(outputTopic.readKeyValue(), equalTo(new KeyValue<>("a", 21L))); assertThat(outputTopic.isEmpty(), is(true)); } @Test public void shouldPunctuateIfWallClockTimeAdvances() { testDriver.advanceWallClockTime(Duration.ofSeconds(60)); assertThat(outputTopic.readKeyValue(), equalTo(new KeyValue<>("a", 21L))); assertThat(outputTopic.isEmpty(), is(true)); } public static
DeveloperGuideTesting
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/SqmFieldLiteral.java
{ "start": 1133, "end": 4625 }
class ____<T> extends AbstractSqmExpression<T> implements SqmExpression<T>, SqmBindableType<T>, SqmSelectableNode<T>, SemanticPathPart { private final @Nullable T value; private final JavaType<T> fieldJavaType; private final String fieldName; public SqmFieldLiteral( Field field, JavaType<T> fieldJavaType, NodeBuilder nodeBuilder){ this( extractValue( field ), fieldJavaType, field.getName(), nodeBuilder ); } public SqmFieldLiteral( @Nullable T value, JavaType<T> fieldJavaType, String fieldName, NodeBuilder nodeBuilder) { super( null, nodeBuilder ); this.value = value; this.fieldJavaType = fieldJavaType; this.fieldName = fieldName; } @Override public PersistenceType getPersistenceType() { return BASIC; } // Checker Framework JDK seems to miss @Nullable for Field.get() @SuppressWarnings("argument") private static <T> @Nullable T extractValue(Field field) { try { //noinspection unchecked return (T) field.get( null ); } catch (IllegalAccessException e) { throw new QueryException( "Could not access Field value for SqmFieldLiteral", e ); } } @Override public SqmFieldLiteral<T> copy(SqmCopyContext context) { final SqmFieldLiteral<T> existing = context.getCopy( this ); if ( existing != null ) { return existing; } return context.registerCopy( this, new SqmFieldLiteral<>( value, fieldJavaType, fieldName, nodeBuilder() ) ); } public @Nullable T getValue() { return value; } public String getFieldName() { return fieldName; } @Override public @NonNull SqmBindableType<T> getNodeType() { return this; } @Override public void applyInferableType(@Nullable SqmBindableType<?> type) { } @Override public @NonNull JavaType<T> getExpressibleJavaType() { return fieldJavaType; } @Override public @NonNull JavaType<T> getJavaTypeDescriptor() { return getExpressibleJavaType(); } @Override public @NonNull Class<T> getJavaType() { return getJavaTypeDescriptor().getJavaTypeClass(); } @Override public <X> X accept(SemanticQueryWalker<X> walker) { return walker.visitFieldLiteral( this ); } @Override public void appendHqlString(StringBuilder hql, SqmRenderContext context) { SqmLiteral.appendHqlString( hql, getJavaTypeDescriptor(), getValue() ); } @Override public SemanticPathPart resolvePathPart( String name, boolean isTerminal, SqmCreationState creationState) { throw new UnknownPathException( String.format( Locale.ROOT, "Static field reference [%s#%s] cannot be de-referenced", fieldJavaType.getTypeName(), fieldName ) ); } @Override public SqmPath<?> resolveIndexedAccess( SqmExpression<?> selector, boolean isTerminal, SqmCreationState creationState) { throw new UnknownPathException( String.format( Locale.ROOT, "Static field reference [%s#%s] cannot be de-referenced", fieldJavaType.getTypeName(), fieldName ) ); } @Override public @Nullable SqmDomainType<T> getSqmType() { return null; } @Override public boolean equals(@Nullable Object object) { return object instanceof SqmFieldLiteral<?> that && Objects.equals( value, that.value ); } @Override public int hashCode() { return Objects.hash( value ); } @Override public boolean isCompatible(Object object) { return equals( object ); } @Override public int cacheHashCode() { return hashCode(); } }
SqmFieldLiteral
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MinaEndpointBuilderFactory.java
{ "start": 86851, "end": 87158 }
class ____ extends AbstractEndpointBuilder implements MinaEndpointBuilder, AdvancedMinaEndpointBuilder { public MinaEndpointBuilderImpl(String path) { super(componentName, path); } } return new MinaEndpointBuilderImpl(path); } }
MinaEndpointBuilderImpl
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/TestData.java
{ "start": 6126, "end": 7246 }
class ____ implements MutableObjectIterator<Tuple2<Integer, String>> { private final TupleGenerator generator; private final int numberOfRecords; private int counter; public TupleGeneratorIterator(TupleGenerator generator, int numberOfRecords) { this.generator = generator; this.generator.reset(); this.numberOfRecords = numberOfRecords; this.counter = 0; } @Override public Tuple2<Integer, String> next(Tuple2<Integer, String> target) { if (counter < numberOfRecords) { counter++; return generator.next(target); } else { return null; } } @Override public Tuple2<Integer, String> next() { if (counter < numberOfRecords) { counter++; return generator.next(); } else { return null; } } public void reset() { this.counter = 0; } } public static
TupleGeneratorIterator