language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__camel | components/camel-aws/camel-aws2-ddb/src/generated/java/org/apache/camel/component/aws2/ddb/Ddb2EndpointUriFactory.java | {
"start": 518,
"end": 3200
} | class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":tableName";
private static final Set<String> PROPERTY_NAMES;
private static final Set<String> SECRET_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
Set<String> props = new HashSet<>(25);
props.add("accessKey");
props.add("amazonDDBClient");
props.add("consistentRead");
props.add("enabledInitialDescribeTable");
props.add("keyAttributeName");
props.add("keyAttributeType");
props.add("keyScalarType");
props.add("lazyStartProducer");
props.add("operation");
props.add("overrideEndpoint");
props.add("profileCredentialsName");
props.add("proxyHost");
props.add("proxyPort");
props.add("proxyProtocol");
props.add("readCapacity");
props.add("region");
props.add("secretKey");
props.add("sessionToken");
props.add("tableName");
props.add("trustAllCertificates");
props.add("uriEndpointOverride");
props.add("useDefaultCredentialsProvider");
props.add("useProfileCredentialsProvider");
props.add("useSessionCredentials");
props.add("writeCapacity");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
Set<String> secretProps = new HashSet<>(3);
secretProps.add("accessKey");
secretProps.add("secretKey");
secretProps.add("sessionToken");
SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps);
MULTI_VALUE_PREFIXES = Collections.emptyMap();
}
@Override
public boolean isEnabled(String scheme) {
return "aws2-ddb".equals(scheme);
}
@Override
public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "tableName", null, true, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public Set<String> secretPropertyNames() {
return SECRET_PROPERTY_NAMES;
}
@Override
public Map<String, String> multiValuePrefixes() {
return MULTI_VALUE_PREFIXES;
}
@Override
public boolean isLenientProperties() {
return false;
}
}
| Ddb2EndpointUriFactory |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/support/ValuesSource.java | {
"start": 29952,
"end": 31206
} | class ____ extends ValuesSource {
private final RangeType rangeType;
protected final IndexFieldData<?> indexFieldData;
public Range(IndexFieldData<?> indexFieldData, RangeType rangeType) {
this.indexFieldData = indexFieldData;
this.rangeType = rangeType;
}
@Override
public SortedBinaryDocValues bytesValues(LeafReaderContext context) {
return indexFieldData.load(context).getBytesValues();
}
@Override
public DocValueBits docsWithValue(LeafReaderContext context) throws IOException {
final SortedBinaryDocValues bytes = bytesValues(context);
return org.elasticsearch.index.fielddata.FieldData.docsWithValue(bytes);
}
@Override
public Function<Rounding, Prepared> roundingPreparer(AggregationContext context) throws IOException {
// TODO lookup the min and max rounding when appropriate
return Rounding::prepareForUnknown;
}
public RangeType rangeType() {
return rangeType;
}
}
/**
* {@linkplain ValuesSource} for fields who's values are best thought of
* as points on a globe.
*/
public abstract static | Range |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/streaming/runtime/util/ReceiveCheckNoOpSink.java | {
"start": 1208,
"end": 1538
} | class ____<T> extends RichSinkFunction<T> {
private List<T> received;
public void invoke(T tuple) {
received.add(tuple);
}
public void open(OpenContext openContext) {
received = new ArrayList<T>();
}
public void close() {
assertTrue(received.size() > 0);
}
}
| ReceiveCheckNoOpSink |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/formula/FormulaGeneratedTest.java | {
"start": 2749,
"end": 3198
} | class ____ {
@Id
private long id;
private BigDecimal unitPrice;
private int quantity = 1;
@Generated
@Formula(value = "'new'")
private String status;
@Generated(event = {EventType.INSERT, EventType.UPDATE})
@Formula(value = "quantity*unitPrice")
private BigDecimal total;
public OrderLine() {}
public OrderLine(BigDecimal unitPrice, int quantity) {
this.unitPrice = unitPrice;
this.quantity = quantity;
}
}
}
| OrderLine |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/samples/ZookeeperDubboSpringProviderBootstrap.java | {
"start": 1831,
"end": 2180
} | class ____ implements DemoService {
@Override
public String sayName(String name) {
RpcContext rpcContext = RpcContext.getServiceContext();
return format("[%s:%s] Say - %s", rpcContext.getLocalHost(), rpcContext.getLocalPort(), name);
}
@Override
public Box getBox() {
return null;
}
}
| DefaultDemoService |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/BonitaComponentBuilderFactory.java | {
"start": 1838,
"end": 3940
} | interface ____ extends ComponentBuilder<BonitaComponent> {
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default BonitaComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default BonitaComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
| BonitaComponentBuilder |
java | spring-projects__spring-boot | loader/spring-boot-loader/src/test/java/org/springframework/boot/loader/net/protocol/nested/NestedLocationTests.java | {
"start": 1371,
"end": 4999
} | class ____ {
@TempDir
File temp;
@BeforeAll
static void registerHandlers() {
Handlers.register();
}
@Test
void createWhenPathIsNullThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> new NestedLocation(null, "nested.jar"))
.withMessageContaining("'path' must not be null");
}
@Test
void createWhenNestedEntryNameIsNull() {
NestedLocation location = new NestedLocation(Path.of("test.jar"), null);
assertThat(location.path().toString()).contains("test.jar");
assertThat(location.nestedEntryName()).isNull();
}
@Test
void createWhenNestedEntryNameIsEmpty() {
NestedLocation location = new NestedLocation(Path.of("test.jar"), "");
assertThat(location.path().toString()).contains("test.jar");
assertThat(location.nestedEntryName()).isNull();
}
@Test
void fromUrlWhenUrlIsNullThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> NestedLocation.fromUrl(null))
.withMessageContaining("'url' must not be null");
}
@Test
void fromUrlWhenNotNestedProtocolThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> NestedLocation.fromUrl(new URL("file://test.jar")))
.withMessageContaining("must use 'nested' protocol");
}
@Test
void fromUrlWhenNoPathThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> NestedLocation.fromUrl(new URL("nested:")))
.withMessageContaining("'location' must not be empty");
}
@Test
void fromUrlWhenNoSeparator() throws Exception {
File file = new File(this.temp, "test.jar");
NestedLocation location = NestedLocation.fromUrl(new URL("nested:" + file.getAbsolutePath() + "/"));
assertThat(location.path()).isEqualTo(file.toPath());
assertThat(location.nestedEntryName()).isNull();
}
@Test
void fromUrlReturnsNestedLocation() throws Exception {
File file = new File(this.temp, "test.jar");
NestedLocation location = NestedLocation
.fromUrl(new URL("nested:" + file.getAbsolutePath() + "/!lib/nested.jar"));
assertThat(location.path()).isEqualTo(file.toPath());
assertThat(location.nestedEntryName()).isEqualTo("lib/nested.jar");
}
@Test
void fromUriWhenUrlIsNullThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> NestedLocation.fromUri(null))
.withMessageContaining("'uri' must not be null");
}
@Test
void fromUriWhenNotNestedProtocolThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> NestedLocation.fromUri(new URI("file://test.jar")))
.withMessageContaining("must use 'nested' scheme");
}
@Test
@Disabled
void fromUriWhenNoSeparator() throws Exception {
NestedLocation location = NestedLocation.fromUri(new URI("nested:test.jar!nested.jar"));
assertThat(location.path().toString()).contains("test.jar!nested.jar");
assertThat(location.nestedEntryName()).isNull();
}
@Test
void fromUriReturnsNestedLocation() throws Exception {
File file = new File(this.temp, "test.jar");
NestedLocation location = NestedLocation
.fromUri(new URI("nested:" + file.getAbsoluteFile().toURI().getPath() + "/!lib/nested.jar"));
assertThat(location.path()).isEqualTo(file.toPath());
assertThat(location.nestedEntryName()).isEqualTo("lib/nested.jar");
}
@Test
@EnabledOnOs(OS.WINDOWS)
void windowsUncPathIsHandledCorrectly() throws MalformedURLException {
NestedLocation location = NestedLocation.fromUrl(
new URL("nested://localhost/c$/dev/temp/demo/build/libs/demo-0.0.1-SNAPSHOT.jar/!BOOT-INF/classes/"));
assertThat(location.path()).asString()
.isEqualTo("\\\\localhost\\c$\\dev\\temp\\demo\\build\\libs\\demo-0.0.1-SNAPSHOT.jar");
}
}
| NestedLocationTests |
java | eclipse-vertx__vert.x | vertx-core/src/test/java/io/vertx/tests/streams/ReadStreamReduceTest.java | {
"start": 679,
"end": 1745
} | class ____ extends AsyncTestBase {
private FakeStream<Object> dst;
private Object o1 = new Object();
private Object o2 = new Object();
private Object o3 = new Object();
@Override
protected void setUp() throws Exception {
super.setUp();
dst = new FakeStream<>();
}
@Test
public void testCollect() {
Future<List<Object>> list = dst.collect(Collectors.toList());
assertFalse(list.isComplete());
dst.write(o1);
assertFalse(list.isComplete());
dst.write(o2);
assertFalse(list.isComplete());
dst.write(o3);
dst.end();
assertTrue(list.succeeded());
assertEquals(Arrays.asList(o1, o2, o3), list.result());
}
@Test
public void testFailure() {
Future<List<Object>> list = dst.collect(Collectors.toList());
assertFalse(list.isComplete());
dst.write(o1);
assertFalse(list.isComplete());
dst.write(o2);
assertFalse(list.isComplete());
Throwable err = new Throwable();
dst.fail(err);
assertTrue(list.failed());
assertSame(err, list.cause());
}
}
| ReadStreamReduceTest |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/logging/log4j/Log4jImpl.java | {
"start": 917,
"end": 966
} | class ____ remove future.
*/
@Deprecated
public | will |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/CommonClientConfigs.java | {
"start": 13776,
"end": 14275
} | class ____ list serde for key that implements the <code>org.apache.kafka.common.serialization.Serde</code> interface. "
+ "This configuration will be read if and only if <code>default.key.serde</code> configuration is set to <code>org.apache.kafka.common.serialization.Serdes.ListSerde</code>";
public static final String DEFAULT_LIST_VALUE_SERDE_INNER_CLASS = "default.list.value.serde.inner";
public static final String DEFAULT_LIST_VALUE_SERDE_INNER_CLASS_DOC = "Default inner | of |
java | apache__maven | impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnup/goals/AbstractUpgradeGoalTest.java | {
"start": 2810,
"end": 4528
} | class ____ {
@Test
@DisplayName("should use explicit model version when provided")
void shouldUseExplicitModelVersionWhenProvided() {
UpgradeContext context = createMockContext(tempDir, TestUtils.createOptionsWithModelVersion("4.1.0"));
String result = upgradeGoal.testDoUpgradeLogic(context, "4.1.0");
assertEquals("4.1.0", result);
}
@Test
@DisplayName("should use 4.1.0 when --all option is specified")
void shouldUse410WhenAllOptionSpecified() {
UpgradeContext context = createMockContext(tempDir, TestUtils.createOptionsWithAll(true));
String result = upgradeGoal.testDoUpgradeLogic(context, "4.1.0");
assertEquals("4.1.0", result);
}
@Test
@DisplayName("should default to 4.0.0 when no specific options provided")
void shouldDefaultTo400WhenNoSpecificOptions() {
UpgradeContext context = createMockContext(tempDir, createDefaultOptions());
String result = upgradeGoal.testDoUpgradeLogic(context, "4.0.0");
assertEquals("4.0.0", result);
}
@Test
@DisplayName("should prioritize explicit model over --all option")
void shouldPrioritizeExplicitModelOverAllOption() {
UpgradeContext context =
createMockContext(tempDir, TestUtils.createOptions(true, null, null, null, "4.0.0"));
String result = upgradeGoal.testDoUpgradeLogic(context, "4.0.0");
assertEquals("4.0.0", result, "Explicit model should take precedence over --all");
}
}
@Nested
@DisplayName("Plugin Options Handling")
| TargetModelVersionTests |
java | apache__camel | core/camel-management/src/test/java/org/apache/camel/management/LoadTripletTest.java | {
"start": 1177,
"end": 2592
} | class ____ {
@Test
public void testConstantUpdate() {
LoadTriplet t = new LoadTriplet();
t.update(1);
assertEquals(1.0, t.getLoad1(), Math.ulp(1.0) * 5);
assertEquals(1.0, t.getLoad5(), Math.ulp(1.0) * 5);
assertEquals(1.0, t.getLoad15(), Math.ulp(1.0) * 5);
for (int i = 0; i < 100; i++) {
t.update(1);
}
assertEquals(1.0, t.getLoad1(), Math.ulp(1.0) * 5);
assertEquals(1.0, t.getLoad5(), Math.ulp(1.0) * 5);
assertEquals(1.0, t.getLoad15(), Math.ulp(1.0) * 5);
}
@Test
public void testChargeDischarge() {
LoadTriplet t = new LoadTriplet();
t.update(0);
double last = t.getLoad15();
double lastDiff = Double.MAX_VALUE;
double diff;
for (int i = 0; i < 1000; i++) {
t.update(5);
diff = t.getLoad15() - last;
assertTrue(diff > 0.0);
assertTrue(diff < lastDiff);
lastDiff = diff;
last = t.getLoad15();
}
lastDiff = -Double.MAX_VALUE;
for (int i = 0; i < 1000; i++) {
t.update(0);
diff = t.getLoad15() - last;
assertTrue(diff < 0.0);
assertTrue(diff > lastDiff, String.format("%f is smaller than %f", diff, lastDiff));
lastDiff = diff;
last = t.getLoad15();
}
}
}
| LoadTripletTest |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/core/security/transport/netty4/SecurityNetty4Transport.java | {
"start": 14967,
"end": 17680
} | class ____ extends ChannelOutboundHandlerAdapter {
private final boolean hostnameVerificationEnabled;
private final SslProfile sslProfile;
private final SSLService sslService;
private final SNIServerName serverName;
private ClientSslHandlerInitializer(
SslProfile sslProfile,
SSLService sslService,
boolean hostnameVerificationEnabled,
SNIServerName serverName
) {
this.sslProfile = sslProfile;
this.hostnameVerificationEnabled = hostnameVerificationEnabled;
this.sslService = sslService;
this.serverName = serverName;
}
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise)
throws Exception {
final SSLEngine sslEngine;
if (hostnameVerificationEnabled) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress;
// we create the socket based on the name given. don't reverse DNS
sslEngine = sslProfile.engine(inetSocketAddress.getHostString(), inetSocketAddress.getPort());
} else {
sslEngine = sslProfile.engine(null, -1);
}
sslEngine.setUseClientMode(true);
if (serverName != null) {
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setServerNames(Collections.singletonList(serverName));
sslEngine.setSSLParameters(sslParameters);
}
final ChannelPromise connectPromise = ctx.newPromise();
final SslHandler sslHandler = new SslHandler(sslEngine);
sslHandler.setHandshakeTimeoutMillis(sslProfile.configuration().handshakeTimeoutMillis());
ctx.pipeline().replace(this, "ssl", sslHandler);
final Future<?> handshakePromise = sslHandler.handshakeFuture();
Netty4Utils.addListener(connectPromise, result -> {
if (result.isSuccess() == false) {
promise.tryFailure(result.cause());
} else {
handshakePromise.addListener(handshakeResult -> {
if (handshakeResult.isSuccess()) {
promise.setSuccess();
} else {
promise.tryFailure(handshakeResult.cause());
}
});
}
});
super.connect(ctx, remoteAddress, localAddress, connectPromise);
}
}
// This | ClientSslHandlerInitializer |
java | apache__camel | components/camel-spring-parent/camel-spring-cloud-config/src/main/java/org/apache/camel/component/spring/cloud/config/SpringCloudConfigPropertiesFunction.java | {
"start": 1405,
"end": 2161
} | class ____ Camel to
* resolve property placeholders using values from Spring Cloud Config.
* <p>
* When a property placeholder with the prefix "spring-config:" is encountered in Camel routes or configuration, this
* function will be called to resolve the property value from Spring Cloud Config sources.
* <p>
* The implementation first attempts to resolve properties through the Spring {@link Environment} if available. If not
* available or the property is not found, it falls back to retrieving the configuration from Spring Config directly.
* <p>
* Usage example in Camel routes or configuration:
*
* <pre>
* {{spring-config:my.property.name}}
* </pre>
*
*/
@org.apache.camel.spi.annotations.PropertiesFunction("spring-config")
public | allows |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/schedulers/TestScheduler.java | {
"start": 1514,
"end": 3901
} | class ____ extends Scheduler {
/** The ordered queue for the runnable tasks. */
final Queue<TimedRunnable> queue = new PriorityBlockingQueue<>(11);
/** Use the {@link RxJavaPlugins#onSchedule(Runnable)} hook when scheduling tasks. */
final boolean useOnScheduleHook;
/** The per-scheduler global order counter. */
long counter;
// Storing time in nanoseconds internally.
volatile long time;
/**
* Creates a new TestScheduler with initial virtual time of zero.
*/
public TestScheduler() {
this(false);
}
/**
* Creates a new TestScheduler with the option to use the
* {@link RxJavaPlugins#onSchedule(Runnable)} hook when scheduling tasks.
* <p>History: 3.0.10 - experimental
* @param useOnScheduleHook if {@code true}, the tasks submitted to this
* TestScheduler is wrapped via the
* {@link RxJavaPlugins#onSchedule(Runnable)} hook
* @since 3.1.0
*/
public TestScheduler(boolean useOnScheduleHook) {
this.useOnScheduleHook = useOnScheduleHook;
}
/**
* Creates a new TestScheduler with the specified initial virtual time.
*
* @param delayTime
* the point in time to move the Scheduler's clock to
* @param unit
* the units of time that {@code delayTime} is expressed in
*/
public TestScheduler(long delayTime, TimeUnit unit) {
this(delayTime, unit, false);
}
/**
* Creates a new TestScheduler with the specified initial virtual time
* and with the option to use the
* {@link RxJavaPlugins#onSchedule(Runnable)} hook when scheduling tasks.
* <p>History: 3.0.10 - experimental
* @param delayTime
* the point in time to move the Scheduler's clock to
* @param unit
* the units of time that {@code delayTime} is expressed in
* @param useOnScheduleHook if {@code true}, the tasks submitted to this
* TestScheduler is wrapped via the
* {@link RxJavaPlugins#onSchedule(Runnable)} hook
* @since 3.1.0
*/
public TestScheduler(long delayTime, TimeUnit unit, boolean useOnScheduleHook) {
time = unit.toNanos(delayTime);
this.useOnScheduleHook = useOnScheduleHook;
}
static final | TestScheduler |
java | spring-projects__spring-framework | spring-core/src/test/java/example/type/AnnotationTypeFilterTestsTypes.java | {
"start": 1391,
"end": 1493
} | class ____ extends SomeComponent {
}
@NonInheritedAnnotation
public static | SomeSubclassOfSomeComponent |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/selection/methodgenerics/wildcards/LifecycleIntersectionMapper.java | {
"start": 433,
"end": 1167
} | interface ____ {
LifecycleIntersectionMapper INSTANCE = Mappers.getMapper( LifecycleIntersectionMapper.class );
@Mapping(target = "realm", ignore = true)
RealmTarget mapRealm(String source);
@Mapping(target = "uniqueRealm", ignore = true)
UniqueRealmTarget mapUniqueRealm(String source);
@Mapping(target = "realm", ignore = true)
@Mapping(target = "uniqueRealm", ignore = true)
BothRealmsTarget mapBothRealms(String source);
@AfterMapping
default <T extends RealmObject & UniqueRealmObject> void afterMapping(String source, @MappingTarget T target) {
target.setRealm( "realm_" + source );
target.setUniqueRealm( "uniqueRealm_" + source );
}
| LifecycleIntersectionMapper |
java | elastic__elasticsearch | libs/core/src/test/java/org/elasticsearch/jdk/JarHellTests.java | {
"start": 1351,
"end": 13026
} | class ____ extends ESTestCase {
URL makeJar(Path dir, String name, Manifest manifest, String... files) throws IOException {
Path jarpath = dir.resolve(name);
ZipOutputStream out;
if (manifest == null) {
out = new JarOutputStream(Files.newOutputStream(jarpath, StandardOpenOption.CREATE));
} else {
out = new JarOutputStream(Files.newOutputStream(jarpath, StandardOpenOption.CREATE), manifest);
}
for (String file : files) {
out.putNextEntry(new ZipEntry(file));
}
out.close();
return jarpath.toUri().toURL();
}
URL makeFile(Path dir, String name) throws IOException {
Path filepath = dir.resolve(name);
Files.newOutputStream(filepath, StandardOpenOption.CREATE).close();
return dir.toUri().toURL();
}
public void testDifferentJars() throws Exception {
Path dir = createTempDir();
Set<URL> jars = asSet(makeJar(dir, "foo.jar", null, "DuplicateClass.class"), makeJar(dir, "bar.jar", null, "DuplicateClass.class"));
try {
JarHell.checkJarHell(jars, logger::debug);
fail("did not get expected exception");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("jar hell!"));
assertTrue(e.getMessage().contains("DuplicateClass"));
assertTrue(e.getMessage().contains("foo.jar"));
assertTrue(e.getMessage().contains("bar.jar"));
}
}
public void testModuleInfo() throws Exception {
Path dir = createTempDir();
JarHell.checkJarHell(
asSet(makeJar(dir, "foo.jar", null, "module-info.class"), makeJar(dir, "bar.jar", null, "module-info.class")),
logger::debug
);
}
public void testModuleInfoPackage() throws Exception {
Path dir = createTempDir();
JarHell.checkJarHell(
asSet(makeJar(dir, "foo.jar", null, "foo/bar/module-info.class"), makeJar(dir, "bar.jar", null, "foo/bar/module-info.class")),
logger::debug
);
}
public void testDirsOnClasspath() throws Exception {
Path dir1 = createTempDir();
Path dir2 = createTempDir();
Set<URL> dirs = asSet(makeFile(dir1, "DuplicateClass.class"), makeFile(dir2, "DuplicateClass.class"));
try {
JarHell.checkJarHell(dirs, logger::debug);
fail("did not get expected exception");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("jar hell!"));
assertTrue(e.getMessage().contains("DuplicateClass"));
assertTrue(e.getMessage().contains(dir1.toString()));
assertTrue(e.getMessage().contains(dir2.toString()));
}
}
public void testDirAndJar() throws Exception {
Path dir1 = createTempDir();
Path dir2 = createTempDir();
Set<URL> dirs = asSet(makeJar(dir1, "foo.jar", null, "DuplicateClass.class"), makeFile(dir2, "DuplicateClass.class"));
try {
JarHell.checkJarHell(dirs, logger::debug);
fail("did not get expected exception");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("jar hell!"));
assertTrue(e.getMessage().contains("DuplicateClass"));
assertTrue(e.getMessage().contains("foo.jar"));
assertTrue(e.getMessage().contains(dir2.toString()));
}
}
public void testNonJDKModuleURLs() throws Throwable {
var bootLayer = ModuleLayer.boot();
Path fooDir = createTempDir();
Path fooJar = PathUtils.get(makeJar(fooDir, "foo.jar", null, "p/Foo.class").toURI());
var fooConfiguration = bootLayer.configuration().resolve(ModuleFinder.of(), ModuleFinder.of(fooJar), List.of("foo"));
Set<URL> urls = JarHell.nonJDKModuleURLs(fooConfiguration).collect(Collectors.toSet());
assertThat(urls.size(), equalTo(1));
assertThat(urls.stream().findFirst().get().toString(), endsWith("foo.jar"));
Path barDir = createTempDir();
Path barJar = PathUtils.get(makeJar(barDir, "bar.jar", null, "q/Bar.class").toURI());
var barConfiguration = fooConfiguration.resolve(ModuleFinder.of(), ModuleFinder.of(barJar), List.of("bar"));
urls = JarHell.nonJDKModuleURLs(barConfiguration).collect(Collectors.toSet());
assertThat(urls.size(), equalTo(2));
assertThat(urls.stream().map(URL::toString).toList(), hasItems(endsWith("foo.jar"), endsWith("bar.jar")));
}
public void testWithinSingleJar() throws Exception {
// the java api for zip file does not allow creating duplicate entries (good!) so
// this bogus jar had to be with https://github.com/jasontedor/duplicate-classes
Set<URL> jars = Collections.singleton(JarHellTests.class.getResource("duplicate-classes.jar"));
try {
JarHell.checkJarHell(jars, logger::debug);
fail("did not get expected exception");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("jar hell!"));
assertTrue(e.getMessage().contains("DuplicateClass"));
assertTrue(e.getMessage().contains("duplicate-classes.jar"));
assertTrue(e.getMessage().contains("exists multiple times in jar"));
}
}
public void testRequiredJDKVersionTooOld() throws Exception {
Path dir = createTempDir();
List<Integer> current = Runtime.version().version();
List<Integer> target = new ArrayList<>(current.size());
for (int i = 0; i < current.size(); i++) {
target.add(current.get(i) + 1);
}
Version targetVersion = Version.parse(Strings.collectionToDelimitedString(target, "."));
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
attributes.put(new Attributes.Name("X-Compile-Target-JDK"), targetVersion.toString());
Set<URL> jars = Collections.singleton(makeJar(dir, "foo.jar", manifest, "Foo.class"));
var e = expectThrows(IllegalStateException.class, () -> JarHell.checkJarHell(jars, logger::debug));
assertThat(e.getMessage(), containsString("requires Java " + targetVersion));
assertThat(e.getMessage(), containsString("your system: " + Runtime.version().toString()));
}
public void testBadJDKVersionInJar() throws Exception {
Path dir = createTempDir();
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
attributes.put(new Attributes.Name("X-Compile-Target-JDK"), "bogus");
Set<URL> jars = Collections.singleton(makeJar(dir, "foo.jar", manifest, "Foo.class"));
var e = expectThrows(IllegalArgumentException.class, () -> JarHell.checkJarHell(jars, logger::debug));
assertThat(e.getMessage(), equalTo("Invalid version string: 'bogus'"));
}
public void testRequiredJDKVersionIsOK() throws Exception {
Path dir = createTempDir();
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
attributes.put(new Attributes.Name("X-Compile-Target-JDK"), "1.7");
Set<URL> jars = Collections.singleton(makeJar(dir, "foo.jar", manifest, "Foo.class"));
JarHell.checkJarHell(jars, logger::debug);
}
public void testInvalidVersions() {
String[] versions = new String[] { "", "1.7.0_80", "1.7." };
for (String version : versions) {
expectThrows(IllegalArgumentException.class, () -> JarHell.checkJavaVersion("foo", version));
}
}
// classpath testing is system specific, so we just write separate tests for *nix and windows cases
/**
* Parse a simple classpath with two elements on unix
*/
public void testParseClassPathUnix() throws Exception {
assumeTrue("test is designed for unix-like systems only", ":".equals(System.getProperty("path.separator")));
assumeTrue("test is designed for unix-like systems only", "/".equals(System.getProperty("file.separator")));
Path element1 = createTempDir();
Path element2 = createTempDir();
Set<URL> expected = asSet(element1.toUri().toURL(), element2.toUri().toURL());
assertEquals(expected, JarHell.parseClassPath(element1.toString() + ":" + element2.toString()));
}
/**
* Make sure an old unix classpath with an empty element (implicitly CWD: i'm looking at you 1.x ES scripts) fails
*/
public void testEmptyClassPathUnix() throws Exception {
assumeTrue("test is designed for unix-like systems only", ":".equals(System.getProperty("path.separator")));
assumeTrue("test is designed for unix-like systems only", "/".equals(System.getProperty("file.separator")));
try {
JarHell.parseClassPath(":/element1:/element2");
fail("should have hit exception");
} catch (IllegalStateException expected) {
assertTrue(expected.getMessage().contains("should not contain empty elements"));
}
}
/**
* Parse a simple classpath with two elements on windows
*/
public void testParseClassPathWindows() throws Exception {
assumeTrue("test is designed for windows-like systems only", ";".equals(System.getProperty("path.separator")));
assumeTrue("test is designed for windows-like systems only", "\\".equals(System.getProperty("file.separator")));
Path element1 = createTempDir();
Path element2 = createTempDir();
Set<URL> expected = asSet(element1.toUri().toURL(), element2.toUri().toURL());
assertEquals(expected, JarHell.parseClassPath(element1.toString() + ";" + element2.toString()));
}
/**
* Make sure an old windows classpath with an empty element (implicitly CWD: i'm looking at you 1.x ES scripts) fails
*/
public void testEmptyClassPathWindows() throws Exception {
assumeTrue("test is designed for windows-like systems only", ";".equals(System.getProperty("path.separator")));
assumeTrue("test is designed for windows-like systems only", "\\".equals(System.getProperty("file.separator")));
try {
JarHell.parseClassPath(";c:\\element1;c:\\element2");
fail("should have hit exception");
} catch (IllegalStateException expected) {
assertTrue(expected.getMessage().contains("should not contain empty elements"));
}
}
/**
* Make sure a "bogus" windows classpath element is accepted, java's classpath parsing accepts it,
* therefore eclipse OSGI code does it :)
*/
public void testCrazyEclipseClassPathWindows() throws Exception {
assumeTrue("test is designed for windows-like systems only", ";".equals(System.getProperty("path.separator")));
assumeTrue("test is designed for windows-like systems only", "\\".equals(System.getProperty("file.separator")));
Set<URL> expected = asSet(
PathUtils.get("c:\\element1").toUri().toURL(),
PathUtils.get("c:\\element2").toUri().toURL(),
PathUtils.get("c:\\element3").toUri().toURL(),
PathUtils.get("c:\\element 4").toUri().toURL()
);
Set<URL> actual = JarHell.parseClassPath("c:\\element1;c:\\element2;/c:/element3;/c:/element 4");
assertEquals(expected, actual);
}
}
| JarHellTests |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/authorization/AuthorizationManagers.java | {
"start": 1029,
"end": 5574
} | class ____ {
/**
* Creates an {@link AuthorizationManager} that grants access if at least one
* {@link AuthorizationManager} granted or abstained, if <code>managers</code> are
* empty then denied decision is returned.
* @param <T> the type of object that is being authorized
* @param managers the {@link AuthorizationManager}s to use
* @return the {@link AuthorizationManager} to use
*/
@SafeVarargs
public static <T> AuthorizationManager<T> anyOf(AuthorizationManager<T>... managers) {
return anyOf(new AuthorizationDecision(false), managers);
}
/**
* Creates an {@link AuthorizationManager} that grants access if at least one
* {@link AuthorizationManager} granted, if <code>managers</code> are empty or
* abstained, a default {@link AuthorizationDecision} is returned.
* @param <T> the type of object that is being authorized
* @param allAbstainDefaultDecision the default decision if all
* {@link AuthorizationManager}s abstained
* @param managers the {@link AuthorizationManager}s to use
* @return the {@link AuthorizationManager} to use
* @since 6.3
*/
@SafeVarargs
public static <T> AuthorizationManager<T> anyOf(AuthorizationDecision allAbstainDefaultDecision,
AuthorizationManager<T>... managers) {
return (AuthorizationManagerCheckAdapter<T>) (Supplier<? extends @Nullable Authentication> authentication,
T object) -> {
List<AuthorizationResult> results = new ArrayList<>();
for (AuthorizationManager<T> manager : managers) {
AuthorizationResult result = manager.authorize(authentication, object);
if (result == null) {
continue;
}
if (result.isGranted()) {
return result;
}
results.add(result);
}
if (results.isEmpty()) {
return allAbstainDefaultDecision;
}
return new CompositeAuthorizationDecision(false, results);
};
}
/**
* Creates an {@link AuthorizationManager} that grants access if all
* {@link AuthorizationManager}s granted or abstained, if <code>managers</code> are
* empty then granted decision is returned.
* @param <T> the type of object that is being authorized
* @param managers the {@link AuthorizationManager}s to use
* @return the {@link AuthorizationManager} to use
*/
@SafeVarargs
public static <T> AuthorizationManager<T> allOf(AuthorizationManager<T>... managers) {
return allOf(new AuthorizationDecision(true), managers);
}
/**
* Creates an {@link AuthorizationManager} that grants access if all
* {@link AuthorizationManager}s granted, if <code>managers</code> are empty or
* abstained, a default {@link AuthorizationDecision} is returned.
* @param <T> the type of object that is being authorized
* @param allAbstainDefaultDecision the default decision if all
* {@link AuthorizationManager}s abstained
* @param managers the {@link AuthorizationManager}s to use
* @return the {@link AuthorizationManager} to use
* @since 6.3
*/
@SafeVarargs
public static <T> AuthorizationManager<T> allOf(AuthorizationDecision allAbstainDefaultDecision,
AuthorizationManager<T>... managers) {
return (AuthorizationManagerCheckAdapter<T>) (Supplier<? extends @Nullable Authentication> authentication,
T object) -> {
List<AuthorizationResult> results = new ArrayList<>();
for (AuthorizationManager<T> manager : managers) {
AuthorizationResult result = manager.authorize(authentication, object);
if (result == null) {
continue;
}
if (!result.isGranted()) {
return result;
}
results.add(result);
}
if (results.isEmpty()) {
return allAbstainDefaultDecision;
}
return new CompositeAuthorizationDecision(true, results);
};
}
/**
* Creates an {@link AuthorizationManager} that reverses whatever decision the given
* {@link AuthorizationManager} granted. If the given {@link AuthorizationManager}
* abstains, then the returned manager also abstains.
* @param <T> the type of object that is being authorized
* @param manager the {@link AuthorizationManager} to reverse
* @return the reversing {@link AuthorizationManager}
* @since 6.3
*/
public static <T> AuthorizationManager<T> not(AuthorizationManager<T> manager) {
return (Supplier<? extends @Nullable Authentication> authentication, T object) -> {
AuthorizationResult result = manager.authorize(authentication, object);
if (result == null) {
return null;
}
return new NotAuthorizationDecision(result);
};
}
private AuthorizationManagers() {
}
@SuppressWarnings("serial")
private static final | AuthorizationManagers |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/support/TransportActionTests.java | {
"start": 1598,
"end": 6171
} | class ____ extends ESTestCase {
private ThreadPool threadPool;
@Before
public void init() throws Exception {
threadPool = new ThreadPool(
Settings.builder().put(Node.NODE_NAME_SETTING.getKey(), "TransportActionTests").build(),
MeterRegistry.NOOP,
new DefaultBuiltInExecutorBuilders()
);
}
@After
public void shutdown() throws Exception {
terminate(threadPool);
}
public void testDirectExecuteRunsOnCallingThread() throws ExecutionException, InterruptedException {
String actionName = randomAlphaOfLength(randomInt(30));
var testExecutor = new Executor() {
@Override
public void execute(Runnable command) {
fail("executeDirect should not run a TransportAction on a different executor");
}
};
var transportAction = getTestTransportAction(actionName, testExecutor);
PlainActionFuture<TestResponse> future = new PlainActionFuture<>();
transportAction.executeDirect(null, new TestRequest(), future);
var response = future.get();
assertThat(response, notNullValue());
assertThat(response.executingThreadName, equalTo(Thread.currentThread().getName()));
assertThat(response.executingThreadId, equalTo(Thread.currentThread().getId()));
}
public void testExecuteRunsOnExecutor() throws ExecutionException, InterruptedException {
String actionName = randomAlphaOfLength(randomInt(30));
boolean[] executedOnExecutor = new boolean[1];
var testExecutor = new Executor() {
@Override
public void execute(Runnable command) {
command.run();
executedOnExecutor[0] = true;
}
};
var transportAction = getTestTransportAction(actionName, testExecutor);
PlainActionFuture<TestResponse> future = new PlainActionFuture<>();
ActionTestUtils.execute(transportAction, null, new TestRequest(), future);
var response = future.get();
assertThat(response, notNullValue());
assertTrue(executedOnExecutor[0]);
}
public void testExecuteWithGenericExecutorRunsOnDifferentThread() throws ExecutionException, InterruptedException {
String actionName = randomAlphaOfLength(randomInt(30));
var transportAction = getTestTransportAction(actionName, threadPool.executor(ThreadPool.Names.GENERIC));
PlainActionFuture<TestResponse> future = new PlainActionFuture<>();
ActionTestUtils.execute(transportAction, null, new TestRequest(), future);
var response = future.get();
assertThat(response, notNullValue());
assertThat(response.executingThreadName, not(equalTo(Thread.currentThread().getName())));
assertThat(response.executingThreadName, containsString("[generic]"));
assertThat(response.executingThreadId, not(equalTo(Thread.currentThread().getId())));
}
public void testExecuteWithDirectExecutorRunsOnCallingThread() throws ExecutionException, InterruptedException {
String actionName = randomAlphaOfLength(randomInt(30));
var transportAction = getTestTransportAction(actionName, EsExecutors.DIRECT_EXECUTOR_SERVICE);
PlainActionFuture<TestResponse> future = new PlainActionFuture<>();
ActionTestUtils.execute(transportAction, null, new TestRequest(), future);
var response = future.get();
assertThat(response, notNullValue());
assertThat(response, notNullValue());
assertThat(response.executingThreadName, equalTo(Thread.currentThread().getName()));
assertThat(response.executingThreadId, equalTo(Thread.currentThread().getId()));
}
private TransportAction<TestRequest, TestResponse> getTestTransportAction(String actionName, Executor executor) {
ActionFilters actionFilters = new ActionFilters(Collections.emptySet());
TransportAction<TestRequest, TestResponse> transportAction = new TransportAction<>(
actionName,
actionFilters,
new TaskManager(Settings.EMPTY, threadPool, Collections.emptySet()),
executor
) {
@Override
protected void doExecute(Task task, TestRequest request, ActionListener<TestResponse> listener) {
listener.onResponse(new TestResponse(Thread.currentThread().getName(), Thread.currentThread().getId()));
}
};
return transportAction;
}
private static | TransportActionTests |
java | hibernate__hibernate-orm | hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/temptable/InformixLocalTemporaryTableStrategy.java | {
"start": 291,
"end": 678
} | class ____ extends StandardLocalTemporaryTableStrategy {
public static final InformixLocalTemporaryTableStrategy INSTANCE = new InformixLocalTemporaryTableStrategy();
@Override
public String getTemporaryTableCreateOptions() {
return "with no log";
}
@Override
public String getTemporaryTableCreateCommand() {
return "create temp table";
}
}
| InformixLocalTemporaryTableStrategy |
java | quarkusio__quarkus | extensions/panache/panache-common/deployment/src/main/java/io/quarkus/panache/common/deployment/EntityModel.java | {
"start": 145,
"end": 633
} | class ____ {
public final String name;
public final String superClassName;
// VERY IMPORTANT: field traversal order should not change
public final Map<String, EntityField> fields = new LinkedHashMap<>();
public EntityModel(ClassInfo classInfo) {
this.name = classInfo.name().toString();
this.superClassName = classInfo.superName().toString();
}
public void addField(EntityField field) {
fields.put(field.name, field);
}
}
| EntityModel |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/asm/Handle.java | {
"start": 2586,
"end": 3145
} | interface ____ not. */
private final boolean isInterface;
/**
* Constructs a new field or method handle.
*
* @param tag the kind of field or method designated by this Handle. Must be {@link
* Opcodes#H_GETFIELD}, {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link
* Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC},
* {@link Opcodes#H_INVOKESPECIAL}, {@link Opcodes#H_NEWINVOKESPECIAL} or {@link
* Opcodes#H_INVOKEINTERFACE}.
* @param owner the internal name of the | or |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/event/ApplicationEvents.java | {
"start": 1038,
"end": 2748
} | class ____ annotated or meta-annotated with
* {@link RecordApplicationEvents @RecordApplicationEvents}.</li>
* <li>Ensure that the {@link ApplicationEventsTestExecutionListener} is
* registered. Note, however, that it is registered by default and only needs
* to be manually registered if you have custom configuration via
* {@link org.springframework.test.context.TestExecutionListeners @TestExecutionListeners}
* that does not include the default listeners.</li>
* <li>With JUnit Jupiter, declare a parameter of type {@code ApplicationEvents}
* in a {@code @Test}, {@code @BeforeEach}, or {@code @AfterEach} method. Since
* {@code ApplicationEvents} is scoped to the lifecycle of the current test method,
* this is the recommended approach.</li>
* <li>Alternatively, you can annotate a field of type {@code ApplicationEvents} with
* {@link org.springframework.beans.factory.annotation.Autowired @Autowired} and
* use that instance of {@code ApplicationEvents} in your test and lifecycle methods.</li>
* </ul>
*
* <p>NOTE: {@code ApplicationEvents} is registered with the {@code ApplicationContext} as a
* {@linkplain org.springframework.beans.factory.config.ConfigurableListableBeanFactory#registerResolvableDependency
* resolvable dependency} which is scoped to the lifecycle of the current test method.
* Consequently, {@code ApplicationEvents} cannot be accessed outside the lifecycle of a
* test method and cannot be {@code @Autowired} into the constructor of a test class.
*
* @author Sam Brannen
* @author Oliver Drotbohm
* @since 5.3.3
* @see RecordApplicationEvents
* @see ApplicationEventsTestExecutionListener
* @see org.springframework.context.ApplicationEvent
*/
public | is |
java | apache__kafka | connect/runtime/src/test/java/org/apache/kafka/connect/runtime/WorkerTaskTest.java | {
"start": 11648,
"end": 11712
} | class ____ extends SinkTask {
}
private static | TestSinkTask |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/DynamicDispatchFunction.java | {
"start": 994,
"end": 5165
} | class ____ implements SqmFunctionDescriptor, ArgumentsValidator {
private final SqmFunctionRegistry functionRegistry;
private final String[] functionNames;
private final FunctionKind functionKind;
public DynamicDispatchFunction(SqmFunctionRegistry functionRegistry, String... functionNames) {
this.functionRegistry = functionRegistry;
this.functionNames = functionNames;
this.functionKind = functionKind( functionRegistry, functionNames );
}
private static FunctionKind functionKind(SqmFunctionRegistry functionRegistry, String[] functionNames) {
FunctionKind functionKind = null;
// Sanity check
for ( String overload : functionNames ) {
final var functionDescriptor = functionRegistry.findFunctionDescriptor( overload );
if ( functionDescriptor == null ) {
throw new IllegalArgumentException( "No function registered under the name '" + overload + "'" );
}
if ( functionKind == null ) {
functionKind = functionDescriptor.getFunctionKind();
}
else if ( functionKind != functionDescriptor.getFunctionKind() ) {
throw new IllegalArgumentException( "Function has function kind " + functionDescriptor.getFunctionKind()
+ ", but other overloads have " + functionKind
+ ". An overloaded function needs a single function kind." );
}
}
return functionKind;
}
@Override
public FunctionKind getFunctionKind() {
return functionKind;
}
@Override
public <T> SelfRenderingSqmFunction<T> generateSqmExpression(
List<? extends SqmTypedNode<?>> arguments,
ReturnableType<T> impliedResultType,
QueryEngine queryEngine) {
return validateGetFunction( arguments, queryEngine )
.generateSqmExpression( arguments, impliedResultType, queryEngine );
}
@Override
public <T> SelfRenderingSqmFunction<T> generateAggregateSqmExpression(
List<? extends SqmTypedNode<?>> arguments,
SqmPredicate filter,
ReturnableType<T> impliedResultType,
QueryEngine queryEngine) {
return validateGetFunction( arguments, queryEngine )
.generateAggregateSqmExpression(
arguments,
filter,
impliedResultType,
queryEngine
);
}
@Override
public <T> SelfRenderingSqmFunction<T> generateOrderedSetAggregateSqmExpression(
List<? extends SqmTypedNode<?>> arguments,
SqmPredicate filter,
SqmOrderByClause withinGroupClause,
ReturnableType<T> impliedResultType,
QueryEngine queryEngine) {
return validateGetFunction( arguments, queryEngine )
.generateOrderedSetAggregateSqmExpression(
arguments,
filter,
withinGroupClause,
impliedResultType,
queryEngine
);
}
@Override
public <T> SelfRenderingSqmFunction<T> generateWindowSqmExpression(
List<? extends SqmTypedNode<?>> arguments,
SqmPredicate filter,
Boolean respectNulls,
Boolean fromFirst,
ReturnableType<T> impliedResultType,
QueryEngine queryEngine) {
return validateGetFunction( arguments, queryEngine )
.generateWindowSqmExpression(
arguments,
filter,
respectNulls,
fromFirst,
impliedResultType,
queryEngine
);
}
@Override
public ArgumentsValidator getArgumentsValidator() {
return this;
}
@Override
public void validate(
List<? extends SqmTypedNode<?>> arguments,
String functionName,
BindingContext bindingContext) {
validateGetFunction( arguments, bindingContext );
}
private SqmFunctionDescriptor validateGetFunction(
List<? extends SqmTypedNode<?>> arguments,
BindingContext bindingContext) {
RuntimeException exception = null;
for ( String overload : functionNames ) {
final var functionDescriptor = functionRegistry.findFunctionDescriptor( overload );
if ( functionDescriptor == null ) {
throw new IllegalArgumentException( "No function registered under the name '" + overload + "'" );
}
try {
functionDescriptor.getArgumentsValidator()
.validate( arguments, overload, bindingContext );
return functionDescriptor;
}
catch (RuntimeException ex) {
if ( exception == null ) {
exception = ex;
}
else {
exception.addSuppressed( ex );
}
}
}
throw exception;
}
}
| DynamicDispatchFunction |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/Compatibility.java | {
"start": 324,
"end": 1760
} | class ____ {
private Compatibility() {
}
private static final Map<Class<?>,Class<?>> primitiveToWrapper;
private static final Map<Class<?>,Class<?>> wrapperToPrimitive;
static {
primitiveToWrapper = new ConcurrentHashMap<>();
wrapperToPrimitive = new ConcurrentHashMap<>();
map( boolean.class, Boolean.class );
map( char.class, Character.class );
map( byte.class, Byte.class );
map( short.class, Short.class );
map( int.class, Integer.class );
map( long.class, Long.class );
map( float.class, Float.class );
map( double.class, Double.class );
}
private static void map(Class<?> primitive, Class<?> wrapper) {
primitiveToWrapper.put( primitive, wrapper );
wrapperToPrimitive.put( wrapper, primitive );
}
public static boolean isWrapper(Class<?> potentialWrapper) {
return wrapperToPrimitive.containsKey( potentialWrapper );
}
public static Class<?> primitiveEquivalent(Class<?> potentialWrapper) {
assert isWrapper( potentialWrapper );
return castNonNull( wrapperToPrimitive.get( potentialWrapper ) );
}
public static Class<?> wrapperEquivalent(Class<?> primitive) {
assert primitive.isPrimitive();
return castNonNull( primitiveToWrapper.get( primitive ) );
}
public static boolean areAssignmentCompatible(Class<?> to, Class<?> from) {
assert to != null;
assert from != null;
if ( from == Void.class && !to.isPrimitive() ) {
// treat Void as the bottom type, the | Compatibility |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/core/RowCallbackHandler.java | {
"start": 1936,
"end": 2690
} | interface ____ {
/**
* Implementations must implement this method to process each row of data
* in the {@link ResultSet}. This method should not call {@code next()} on
* the {@code ResultSet}; it is only supposed to extract values of the current
* row.
* <p>Exactly what the implementation chooses to do is up to it:
* a trivial implementation might simply count rows, while another
* implementation might build an XML document.
* @param rs the {@code ResultSet} to process (pre-initialized for the current row)
* @throws SQLException if an {@code SQLException} is encountered getting
* column values (that is, there's no need to catch {@code SQLException})
*/
void processRow(ResultSet rs) throws SQLException;
}
| RowCallbackHandler |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/internal/ComponentPropertyHolder.java | {
"start": 1863,
"end": 2056
} | class ____ {
* ...
* @Convert(...)
* public String city;
* }
*
* @Entity
* @Convert( attributeName="homeAddress.city", ... )
* | Address |
java | google__dagger | javatests/dagger/internal/codegen/MembersInjectionTest.java | {
"start": 10256,
"end": 11123
} | class ____ {",
" @Inject String string;",
" @Inject Lazy<String> lazyString;",
" @Inject Provider<String> stringProvider;",
"}");
CompilerTests.daggerCompiler(file)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(0);
subject.generatedSource(
goldenFileRule.goldenSource("test/FieldInjection_MembersInjector"));
});
}
@Test
public void nonTypeUseNullableFieldInjection() {
Source file =
CompilerTests.javaSource(
"test.FieldInjection",
"package test;",
"",
"import dagger.Lazy;",
"import javax.inject.Inject;",
"import javax.inject.Provider;",
"",
" | FieldInjection |
java | apache__hadoop | hadoop-maven-plugins/src/main/java/org/apache/hadoop/maven/plugin/versioninfo/VersionInfoMojo.java | {
"start": 7574,
"end": 8769
} | class ____ implements Comparator<File>, Serializable {
private static final long serialVersionUID = 1L;
@Override
public int compare(File lhs, File rhs) {
return normalizePath(lhs).compareTo(normalizePath(rhs));
}
private String normalizePath(File file) {
return file.getPath().toUpperCase(Locale.ENGLISH)
.replaceAll("\\\\", "/");
}
}
/**
* Computes and returns an MD5 checksum of the contents of all files in the
* input Maven FileSet.
*
* @return String containing hexadecimal representation of MD5 checksum
* @throws Exception if there is any error while computing the MD5 checksum
*/
private String computeMD5() throws Exception {
List<File> files = FileSetUtils.convertFileSetToFiles(source);
// File order of MD5 calculation is significant. Sorting is done on
// unix-format names, case-folded, in order to get a platform-independent
// sort and calculate the same MD5 on all platforms.
Collections.sort(files, new MD5Comparator());
byte[] md5 = computeMD5(files);
String md5str = byteArrayToString(md5);
getLog().info("Computed MD5: " + md5str);
return md5str;
}
}
| MD5Comparator |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/deduplicate/ProcTimeDeduplicateFunctionTestBase.java | {
"start": 3492,
"end": 4141
} | class ____ implements FilterCondition {
@Override
public boolean apply(Context ctx, RowData input) {
return input.getInt(2) > 10;
}
@Override
public void open(OpenContext openContext) throws Exception {}
@Override
public void close() throws Exception {}
@Override
public RuntimeContext getRuntimeContext() {
return null;
}
@Override
public IterationRuntimeContext getIterationRuntimeContext() {
return null;
}
@Override
public void setRuntimeContext(RuntimeContext t) {}
}
}
| TestingFilter |
java | quarkusio__quarkus | extensions/kubernetes-config/runtime/src/main/java/io/quarkus/kubernetes/config/runtime/KubernetesConfigSourceFactoryBuilder.java | {
"start": 896,
"end": 1627
} | class ____ implements ConfigurableConfigSourceFactory<KubernetesClientBuildConfig> {
@Override
public Iterable<ConfigSource> getConfigSources(final ConfigSourceContext context,
final KubernetesClientBuildConfig config) {
boolean inAppCDsGeneration = Boolean
.parseBoolean(System.getProperty(ApplicationLifecycleManager.QUARKUS_APPCDS_GENERATE_PROP, "false"));
if (inAppCDsGeneration) {
return Collections.emptyList();
}
KubernetesClient client = KubernetesClientUtils.createClient(config);
return new KubernetesConfigSourceFactory(client).getConfigSources(context);
}
}
}
| KubernetesConfigFactory |
java | spring-projects__spring-boot | module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/JmxEndpointAutoConfiguration.java | {
"start": 6009,
"end": 6821
} | class ____ {
@Bean
@ConditionalOnSingleCandidate(MBeanServer.class)
JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer,
EndpointObjectNameFactory endpointObjectNameFactory, ObjectProvider<JsonMapper> jsonMapper,
JmxEndpointsSupplier jmxEndpointsSupplier) {
JmxOperationResponseMapper responseMapper = new JacksonJmxOperationResponseMapper(
jsonMapper.getIfAvailable());
return new JmxEndpointExporter(mBeanServer, endpointObjectNameFactory, responseMapper,
jmxEndpointsSupplier.getEndpoints());
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
@ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper")
@Deprecated(since = "4.0.0", forRemoval = true)
@SuppressWarnings("removal")
static | JmxJacksonEndpointConfiguration |
java | quarkusio__quarkus | extensions/hibernate-envers/deployment/src/test/java/io/quarkus/hibernate/orm/envers/EnversTestStoreDataAtDeleteResource.java | {
"start": 497,
"end": 2150
} | class ____ {
private static final String NAME = "deleted";
@Inject
EntityManager em;
@Inject
UserTransaction transaction;
@DELETE
public String delete() {
try {
transaction.begin();
MyAuditedEntity entity = new MyAuditedEntity();
entity.setName(NAME);
em.persist(entity);
transaction.commit();
transaction.begin();
em.remove(em.find(MyAuditedEntity.class, entity.getId()));
em.flush();
transaction.commit();
AuditReader auditReader = AuditReaderFactory.get(em);
List<Number> revisions = auditReader.getRevisions(MyAuditedEntity.class, entity.getId());
if (revisions.size() != 2) {
throw new IllegalStateException(String.format("found %d revisions", revisions.size()));
}
for (Number revision : revisions) {
System.out.println(revision);
MyAuditedEntity revEntity = auditReader.find(MyAuditedEntity.class, MyAuditedEntity.class.getName(),
entity.getId(), revision, true);
if (revEntity == null) {
throw new IllegalStateException("failed to find delete revision");
}
if (!NAME.equals(revEntity.getName())) {
throw new IllegalStateException("revision listener failed to persist data on delete");
}
}
return "OK";
} catch (Exception exception) {
return exception.getMessage();
}
}
}
| EnversTestStoreDataAtDeleteResource |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/ExtensionLoader.java | {
"start": 58130,
"end": 59327
} | class ____ implements Comparator<Method> {
private static final MethodComparator INSTANCE = new MethodComparator();
@Override
public int compare(Method m1, Method m2) {
int compare = m1.getDeclaringClass().getName().compareTo(m2.getDeclaringClass().getName());
if (compare != 0) {
return compare;
}
compare = m1.getName().compareTo(m2.getName());
if (compare != 0) {
return compare;
}
Class<?>[] p1 = m1.getParameterTypes();
Class<?>[] p2 = m2.getParameterTypes();
compare = Integer.compare(p1.length, p2.length);
if (compare != 0) {
return compare;
}
for (int i = 0; i < p1.length; i++) {
compare = p1[i].getName().compareTo(p2[i].getName());
if (compare != 0) {
return compare;
}
}
// this shouldn't be useful, except if we have bridge methods, but let's be safe
return m1.getReturnType().getName().compareTo(m2.getReturnType().getName());
}
}
}
| MethodComparator |
java | quarkusio__quarkus | extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/AmbiguousDefaultTrustStoreProviderTest.java | {
"start": 1898,
"end": 2141
} | class ____ implements TrustStoreProvider {
@Override
public TrustStoreAndTrustOptions getTrustStore(Vertx vertx) {
// this method should never be called
return null;
}
}
}
| TestTrustStoreProvider |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/reindex/BulkByScrollTaskStatusOrExceptionTests.java | {
"start": 954,
"end": 4516
} | class ____ extends AbstractXContentTestCase<StatusOrException> {
@Override
protected StatusOrException createTestInstance() {
// failures are tested separately, so we can test XContent equivalence at least when we have no failures
return createTestInstanceWithoutExceptions();
}
static StatusOrException createTestInstanceWithoutExceptions() {
return new StatusOrException(BulkByScrollTaskStatusTests.randomStatusWithoutException());
}
static StatusOrException createTestInstanceWithExceptions() {
if (randomBoolean()) {
return new StatusOrException(new ElasticsearchException("test_exception"));
} else {
return new StatusOrException(BulkByScrollTaskStatusTests.randomStatus());
}
}
@Override
protected StatusOrException doParseInstance(XContentParser parser) throws IOException {
return BulkByScrollTaskStatusTests.parseStatusOrException(parser);
}
public static void assertEqualStatusOrException(
StatusOrException expected,
StatusOrException actual,
boolean includeUpdated,
boolean includeCreated
) {
if (expected != null && actual != null) {
assertNotSame(expected, actual);
if (expected.getException() == null) {
BulkByScrollTaskStatusTests
// we test includeCreated params in the Status tests
.assertEqualStatus(expected.getStatus(), actual.getStatus(), includeUpdated, includeCreated);
} else {
assertThat(actual.getException().getMessage(), containsString(expected.getException().getMessage()));
}
} else {
// If one of them is null both of them should be null
assertSame(expected, actual);
}
}
@Override
protected void assertEqualInstances(StatusOrException expected, StatusOrException actual) {
assertEqualStatusOrException(expected, actual, true, true);
}
@Override
protected boolean supportsUnknownFields() {
return true;
}
/**
* Test parsing {@link StatusOrException} with inner failures as they don't support asserting on xcontent equivalence, given that
* exceptions are not parsed back as the same original class. We run the usual {@link AbstractXContentTestCase#testFromXContent()}
* without failures, and this other test with failures where we disable asserting on xcontent equivalence at the end.
*/
public void testFromXContentWithFailures() throws IOException {
Supplier<StatusOrException> instanceSupplier = BulkByScrollTaskStatusOrExceptionTests::createTestInstanceWithExceptions;
// with random fields insertion in the inner exceptions, some random stuff may be parsed back as metadata,
// but that does not bother our assertions, as we only want to test that we don't break.
boolean supportsUnknownFields = true;
// exceptions are not of the same type whenever parsed back
boolean assertToXContentEquivalence = false;
AbstractXContentTestCase.testFromXContent(
NUMBER_OF_TEST_RUNS,
instanceSupplier,
supportsUnknownFields,
Strings.EMPTY_ARRAY,
getRandomFieldsExcludeFilter(),
this::createParser,
this::doParseInstance,
this::assertEqualInstances,
assertToXContentEquivalence,
ToXContent.EMPTY_PARAMS
);
}
}
| BulkByScrollTaskStatusOrExceptionTests |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/vld/ValidatePolymSubTypeTest.java | {
"start": 1223,
"end": 1451
} | class ____ {
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
public BaseValue value;
protected AnnotatedWrapper() { }
public AnnotatedWrapper(BaseValue v) { value = v; }
}
static | AnnotatedWrapper |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/ElementCollectionWithConverterTest.java | {
"start": 782,
"end": 1079
} | class ____ {
@Test
@TestForIssue(jiraKey = "HHH-12581")
@WithClasses( { Item.class } )
void testConverterAppliedToElementCollections() {
assertMetamodelClassGeneratedFor( Item.class );
// Verify that field roles is a SetAttribute with a generic type of Role. | ElementCollectionWithConverterTest |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java | {
"start": 2592,
"end": 2680
} | class ____ {
@Bean
TestBean x() {
return new TestBean();
}
}
@Configuration
| X |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/event/connection/JfrConnectEvent.java | {
"start": 365,
"end": 736
} | class ____ extends Event {
private final String redisUri;
private final String epId;
public JfrConnectEvent(ConnectEvent event) {
this.redisUri = event.getRedisUri();
this.epId = event.getEpId();
}
public String getRedisUri() {
return redisUri;
}
public String getEpId() {
return epId;
}
}
| JfrConnectEvent |
java | apache__camel | components/camel-salesforce/camel-salesforce-codegen/src/main/java/org/apache/camel/component/salesforce/codegen/SchemaExecution.java | {
"start": 1378,
"end": 4207
} | class ____ extends AbstractSalesforceExecution {
private static final Logger LOG = LoggerFactory.getLogger(SchemaExecution.class.getName());
String excludePattern;
String[] excludes;
String includePattern;
String[] includes;
String jsonSchemaFilename;
String jsonSchemaId;
File outputDirectory;
@Override
protected void executeWithClient() throws Exception {
getLog().info("Generating JSON Schema...");
final ObjectDescriptions descriptions = new ObjectDescriptions(
getRestClient(), getResponseTimeout(), includes, includePattern, excludes, excludePattern, getLog());
// generate JSON schema for every object description
final ObjectMapper schemaObjectMapper = JsonUtils.createSchemaObjectMapper();
final Set<JsonSchema> allSchemas = new HashSet<>();
for (final SObjectDescription description : descriptions.fetched()) {
if (Defaults.IGNORED_OBJECTS.contains(description.getName())) {
continue;
}
try {
allSchemas.addAll(JsonUtils.getSObjectJsonSchema(schemaObjectMapper, description, jsonSchemaId, true));
} catch (final IOException e) {
throw new RuntimeException("Unable to generate JSON Schema types for: " + description.getName(), e);
}
}
final Path schemaFilePath = outputDirectory.toPath().resolve(jsonSchemaFilename);
try {
Files.write(schemaFilePath,
JsonUtils.getJsonSchemaString(schemaObjectMapper, allSchemas, jsonSchemaId)
.getBytes(StandardCharsets.UTF_8));
} catch (final IOException e) {
throw new RuntimeException("Unable to generate JSON Schema source file: " + schemaFilePath, e);
}
getLog().info(
String.format("Successfully generated %s JSON Types in file %s", descriptions.count() * 2, schemaFilePath));
}
@Override
protected Logger getLog() {
return LOG;
}
public void setExcludePattern(String excludePattern) {
this.excludePattern = excludePattern;
}
public void setExcludes(String[] excludes) {
this.excludes = excludes;
}
public void setIncludePattern(String includePattern) {
this.includePattern = includePattern;
}
public void setIncludes(String[] includes) {
this.includes = includes;
}
public void setJsonSchemaFilename(String jsonSchemaFilename) {
this.jsonSchemaFilename = jsonSchemaFilename;
}
public void setJsonSchemaId(String jsonSchemaId) {
this.jsonSchemaId = jsonSchemaId;
}
public void setOutputDirectory(File outputDirectory) {
this.outputDirectory = outputDirectory;
}
}
| SchemaExecution |
java | spring-projects__spring-boot | module/spring-boot-data-couchbase/src/main/java/org/springframework/boot/data/couchbase/autoconfigure/DataCouchbaseAutoConfiguration.java | {
"start": 2179,
"end": 2307
} | class ____ {
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Validator.class)
static | DataCouchbaseAutoConfiguration |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestIntegrationTests.java | {
"start": 96012,
"end": 96418
} | class ____ {
static {
//noinspection ConstantValue
if (true) {
throw new RuntimeException("boom");
}
}
private static Stream<String> getArguments() {
return Stream.of("foo", "bar");
}
@ParameterizedTest(quoteTextArguments = false)
@MethodSource("getArguments")
void test(String value) {
fail("should not be called: " + value);
}
}
}
| ExceptionInStaticInitializerTestCase |
java | apache__flink | flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/vector/position/CollectionPosition.java | {
"start": 968,
"end": 1638
} | class ____ {
@Nullable private final boolean[] isNull;
private final long[] offsets;
private final long[] length;
private final int valueCount;
public CollectionPosition(boolean[] isNull, long[] offsets, long[] length, int valueCount) {
this.isNull = isNull;
this.offsets = offsets;
this.length = length;
this.valueCount = valueCount;
}
public boolean[] getIsNull() {
return isNull;
}
public long[] getOffsets() {
return offsets;
}
public long[] getLength() {
return length;
}
public int getValueCount() {
return valueCount;
}
}
| CollectionPosition |
java | elastic__elasticsearch | modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupBuilder.java | {
"start": 72883,
"end": 73121
} | class ____ to classes"
);
}
if (javaClassNamesToClasses.values().containsAll(classesToPainlessClasses.keySet()) == false) {
throw new IllegalArgumentException(
"the values of java | names |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/StartupProgressServlet.java | {
"start": 1700,
"end": 5471
} | class ____ extends DfsServlet {
private static final String COUNT = "count";
private static final String ELAPSED_TIME = "elapsedTime";
private static final String FILE = "file";
private static final String NAME = "name";
private static final String DESC = "desc";
private static final String PERCENT_COMPLETE = "percentComplete";
private static final String PHASES = "phases";
private static final String SIZE = "size";
private static final String STATUS = "status";
private static final String STEPS = "steps";
private static final String TOTAL = "total";
public static final String PATH_SPEC = "/startupProgress";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("application/json; charset=UTF-8");
StartupProgress prog = NameNodeHttpServer.getStartupProgressFromContext(
getServletContext());
StartupProgressView view = prog.createView();
JsonGenerator json = new JsonFactory().createGenerator(resp.getWriter());
try {
json.writeStartObject();
json.writeNumberField(ELAPSED_TIME, view.getElapsedTime());
json.writeNumberField(PERCENT_COMPLETE, view.getPercentComplete());
json.writeArrayFieldStart(PHASES);
for (Phase phase: view.getPhases()) {
json.writeStartObject();
json.writeStringField(NAME, phase.getName());
json.writeStringField(DESC, phase.getDescription());
json.writeStringField(STATUS, view.getStatus(phase).toString());
json.writeNumberField(PERCENT_COMPLETE, view.getPercentComplete(phase));
json.writeNumberField(ELAPSED_TIME, view.getElapsedTime(phase));
writeStringFieldIfNotNull(json, FILE, view.getFile(phase));
writeNumberFieldIfDefined(json, SIZE, view.getSize(phase));
json.writeArrayFieldStart(STEPS);
for (Step step: view.getSteps(phase)) {
json.writeStartObject();
StepType type = step.getType();
if (type != null) {
json.writeStringField(NAME, type.getName());
json.writeStringField(DESC, type.getDescription());
}
json.writeNumberField(COUNT, view.getCount(phase, step));
writeStringFieldIfNotNull(json, FILE, step.getFile());
writeNumberFieldIfDefined(json, SIZE, step.getSize());
json.writeNumberField(TOTAL, view.getTotal(phase, step));
json.writeNumberField(PERCENT_COMPLETE, view.getPercentComplete(phase,
step));
json.writeNumberField(ELAPSED_TIME, view.getElapsedTime(phase, step));
json.writeEndObject();
}
json.writeEndArray();
json.writeEndObject();
}
json.writeEndArray();
json.writeEndObject();
} finally {
IOUtils.cleanupWithLogger(LOG, json);
}
}
/**
* Writes a JSON number field only if the value is defined.
*
* @param json JsonGenerator to receive output
* @param key String key to put
* @param value long value to put
* @throws IOException if there is an I/O error
*/
private static void writeNumberFieldIfDefined(JsonGenerator json, String key,
long value) throws IOException {
if (value != Long.MIN_VALUE) {
json.writeNumberField(key, value);
}
}
/**
* Writes a JSON string field only if the value is non-null.
*
* @param json JsonGenerator to receive output
* @param key String key to put
* @param value String value to put
* @throws IOException if there is an I/O error
*/
private static void writeStringFieldIfNotNull(JsonGenerator json, String key,
String value) throws IOException {
if (value != null) {
json.writeStringField(key, value);
}
}
}
| StartupProgressServlet |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/TestConstructorTestClassScopedExtensionContextNestedTests.java | {
"start": 4419,
"end": 4528
} | class ____ {
@Bean
String text() {
return "enigma";
}
}
@TestConstructor(autowireMode = ALL)
| Config |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/impl/MetricCounterInt.java | {
"start": 1044,
"end": 1445
} | class ____ extends AbstractMetric {
final int value;
MetricCounterInt(MetricsInfo info, int value) {
super(info);
this.value = value;
}
@Override
public Integer value() {
return value;
}
@Override
public MetricType type() {
return MetricType.COUNTER;
}
@Override
public void visit(MetricsVisitor visitor) {
visitor.counter(this, value);
}
}
| MetricCounterInt |
java | alibaba__fastjson | src/main/java/com/alibaba/fastjson/serializer/BeanContext.java | {
"start": 264,
"end": 1488
} | class ____ {
private final Class<?> beanClass;
private final FieldInfo fieldInfo;
private final String format;
public BeanContext(Class<?> beanClass, FieldInfo fieldInfo){
this.beanClass = beanClass;
this.fieldInfo = fieldInfo;
this.format = fieldInfo.getFormat();
}
public Class<?> getBeanClass() {
return beanClass;
}
public Method getMethod() {
return fieldInfo.method;
}
public Field getField() {
return fieldInfo.field;
}
public String getName() {
return fieldInfo.name;
}
public String getLabel() {
return fieldInfo.label;
}
public Class<?> getFieldClass() {
return fieldInfo.fieldClass;
}
public Type getFieldType() {
return fieldInfo.fieldType;
}
public int getFeatures() {
return fieldInfo.serialzeFeatures;
}
public boolean isJsonDirect() {
return this.fieldInfo.jsonDirect;
}
public <T extends Annotation> T getAnnation(Class<T> annotationClass) {
return fieldInfo.getAnnation(annotationClass);
}
public String getFormat() {
return format;
}
}
| BeanContext |
java | apache__camel | components/camel-jt400/src/main/java/org/apache/camel/component/jt400/Jt400Type.java | {
"start": 853,
"end": 913
} | enum ____ {
DTAQ,
PGM,
SRVPGM,
MSGQ
}
| Jt400Type |
java | apache__dubbo | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java | {
"start": 1042,
"end": 1277
} | class ____ implements Dispatcher {
public static final String NAME = "all";
@Override
public ChannelHandler dispatch(ChannelHandler handler, URL url) {
return new AllChannelHandler(handler, url);
}
}
| AllDispatcher |
java | apache__avro | lang/java/tools/src/test/compiler/output-string/avro/examples/baseball/JSpecifyNullSafeAnnotationsFieldsTest.java | {
"start": 2555,
"end": 9569
} | class ____ by the given SchemaStore
*/
public static BinaryMessageDecoder<JSpecifyNullSafeAnnotationsFieldsTest> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this JSpecifyNullSafeAnnotationsFieldsTest to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a JSpecifyNullSafeAnnotationsFieldsTest from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a JSpecifyNullSafeAnnotationsFieldsTest instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static JSpecifyNullSafeAnnotationsFieldsTest fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
private java.lang.String name;
private java.lang.String nullable_name;
private int favorite_number;
private java.lang.Integer nullable_favorite_number;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public JSpecifyNullSafeAnnotationsFieldsTest() {}
/**
* All-args constructor.
* @param name The new value for name
* @param nullable_name The new value for nullable_name
* @param favorite_number The new value for favorite_number
* @param nullable_favorite_number The new value for nullable_favorite_number
*/
public JSpecifyNullSafeAnnotationsFieldsTest(@org.jspecify.annotations.NonNull java.lang.String name, @org.jspecify.annotations.Nullable java.lang.String nullable_name, @org.jspecify.annotations.NonNull java.lang.Integer favorite_number, @org.jspecify.annotations.Nullable java.lang.Integer nullable_favorite_number) {
this.name = name;
this.nullable_name = nullable_name;
this.favorite_number = favorite_number;
this.nullable_favorite_number = nullable_favorite_number;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return name;
case 1: return nullable_name;
case 2: return favorite_number;
case 3: return nullable_favorite_number;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: name = value$ != null ? value$.toString() : null; break;
case 1: nullable_name = value$ != null ? value$.toString() : null; break;
case 2: favorite_number = (java.lang.Integer)value$; break;
case 3: nullable_favorite_number = (java.lang.Integer)value$; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'name' field.
* @return The value of the 'name' field.
*/
@org.jspecify.annotations.NonNull
public java.lang.String getName() {
return name;
}
/**
* Sets the value of the 'name' field.
* @param value the value to set.
*/
public void setName(@org.jspecify.annotations.NonNull java.lang.String value) {
this.name = value;
}
/**
* Gets the value of the 'nullable_name' field.
* @return The value of the 'nullable_name' field.
*/
@org.jspecify.annotations.Nullable
public java.lang.String getNullableName() {
return nullable_name;
}
/**
* Sets the value of the 'nullable_name' field.
* @param value the value to set.
*/
public void setNullableName(@org.jspecify.annotations.Nullable java.lang.String value) {
this.nullable_name = value;
}
/**
* Gets the value of the 'favorite_number' field.
* @return The value of the 'favorite_number' field.
*/
@org.jspecify.annotations.NonNull
public int getFavoriteNumber() {
return favorite_number;
}
/**
* Sets the value of the 'favorite_number' field.
* @param value the value to set.
*/
public void setFavoriteNumber(@org.jspecify.annotations.NonNull int value) {
this.favorite_number = value;
}
/**
* Gets the value of the 'nullable_favorite_number' field.
* @return The value of the 'nullable_favorite_number' field.
*/
@org.jspecify.annotations.Nullable
public java.lang.Integer getNullableFavoriteNumber() {
return nullable_favorite_number;
}
/**
* Sets the value of the 'nullable_favorite_number' field.
* @param value the value to set.
*/
public void setNullableFavoriteNumber(@org.jspecify.annotations.Nullable java.lang.Integer value) {
this.nullable_favorite_number = value;
}
/**
* Creates a new JSpecifyNullSafeAnnotationsFieldsTest RecordBuilder.
* @return A new JSpecifyNullSafeAnnotationsFieldsTest RecordBuilder
*/
public static avro.examples.baseball.JSpecifyNullSafeAnnotationsFieldsTest.Builder newBuilder() {
return new avro.examples.baseball.JSpecifyNullSafeAnnotationsFieldsTest.Builder();
}
/**
* Creates a new JSpecifyNullSafeAnnotationsFieldsTest RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new JSpecifyNullSafeAnnotationsFieldsTest RecordBuilder
*/
public static avro.examples.baseball.JSpecifyNullSafeAnnotationsFieldsTest.Builder newBuilder(avro.examples.baseball.JSpecifyNullSafeAnnotationsFieldsTest.Builder other) {
if (other == null) {
return new avro.examples.baseball.JSpecifyNullSafeAnnotationsFieldsTest.Builder();
} else {
return new avro.examples.baseball.JSpecifyNullSafeAnnotationsFieldsTest.Builder(other);
}
}
/**
* Creates a new JSpecifyNullSafeAnnotationsFieldsTest RecordBuilder by copying an existing JSpecifyNullSafeAnnotationsFieldsTest instance.
* @param other The existing instance to copy.
* @return A new JSpecifyNullSafeAnnotationsFieldsTest RecordBuilder
*/
public static avro.examples.baseball.JSpecifyNullSafeAnnotationsFieldsTest.Builder newBuilder(avro.examples.baseball.JSpecifyNullSafeAnnotationsFieldsTest other) {
if (other == null) {
return new avro.examples.baseball.JSpecifyNullSafeAnnotationsFieldsTest.Builder();
} else {
return new avro.examples.baseball.JSpecifyNullSafeAnnotationsFieldsTest.Builder(other);
}
}
/**
* RecordBuilder for JSpecifyNullSafeAnnotationsFieldsTest instances.
*/
@org.apache.avro.specific.AvroGenerated
public static | backed |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java | {
"start": 25321,
"end": 25630
} | class ____ {
private final String[] arrayValue;
NestedConstructorBeanWithEmptyDefaultValueForArrayTypes(@DefaultValue String[] arrayValue) {
this.arrayValue = arrayValue;
}
String[] getArrayValue() {
return this.arrayValue;
}
}
static | NestedConstructorBeanWithEmptyDefaultValueForArrayTypes |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/support/replication/TransportWriteAction.java | {
"start": 14816,
"end": 17082
} | class ____<ReplicaRequest extends ReplicatedWriteRequest<ReplicaRequest>> extends ReplicaResult {
public final Location location;
private final ReplicaRequest request;
private final IndexShard replica;
private final Logger logger;
private final Consumer<Runnable> postWriteAction;
public WriteReplicaResult(
ReplicaRequest request,
@Nullable Location location,
@Nullable Exception operationFailure,
IndexShard replica,
Logger logger
) {
this(request, location, operationFailure, replica, logger, null);
}
public WriteReplicaResult(
ReplicaRequest request,
@Nullable Location location,
@Nullable Exception operationFailure,
IndexShard replica,
Logger logger,
Consumer<Runnable> postWriteAction
) {
super(operationFailure);
this.location = location;
this.request = request;
this.replica = replica;
this.logger = logger;
this.postWriteAction = postWriteAction;
}
@Override
public void runPostReplicaActions(ActionListener<Void> listener) {
if (finalFailure != null) {
listener.onFailure(finalFailure);
} else {
new AsyncAfterWriteAction(replica, request, location, new RespondingWriteResult() {
@Override
public void onSuccess(boolean forcedRefresh) {
listener.onResponse(null);
}
@Override
public void onFailure(Exception ex) {
listener.onFailure(ex);
}
}, logger, null, postWriteAction).run();
}
}
}
@Override
protected ClusterBlockLevel globalBlockLevel() {
return ClusterBlockLevel.WRITE;
}
@Override
public ClusterBlockLevel indexBlockLevel() {
return ClusterBlockLevel.WRITE;
}
/**
* callback used by {@link AsyncAfterWriteAction} to notify that all post
* process actions have been executed
*/
| WriteReplicaResult |
java | apache__camel | components/camel-spring-parent/camel-spring-ws/src/test/java/org/apache/camel/component/spring/ws/processor/FaultResponseProcessor.java | {
"start": 980,
"end": 1187
} | class ____ implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
exchange.setException(new RuntimeException("Sample Error"));
}
}
| FaultResponseProcessor |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/GroupReduceCombineDriver.java | {
"start": 2926,
"end": 10647
} | class ____<IN, OUT>
implements Driver<GroupCombineFunction<IN, OUT>, OUT> {
private static final Logger LOG = LoggerFactory.getLogger(GroupReduceCombineDriver.class);
/**
* Fix length records with a length below this threshold will be in-place sorted, if possible.
*/
private static final int THRESHOLD_FOR_IN_PLACE_SORTING = 32;
private TaskContext<GroupCombineFunction<IN, OUT>, OUT> taskContext;
private InMemorySorter<IN> sorter;
private GroupCombineFunction<IN, OUT> combiner;
private TypeSerializer<IN> serializer;
private TypeComparator<IN> groupingComparator;
private QuickSort sortAlgo = new QuickSort();
private Collector<OUT> output;
private List<MemorySegment> memory;
private long oversizedRecordCount;
private volatile boolean running = true;
private boolean objectReuseEnabled = false;
// ------------------------------------------------------------------------
@Override
public void setup(TaskContext<GroupCombineFunction<IN, OUT>, OUT> context) {
this.taskContext = context;
this.running = true;
}
@Override
public int getNumberOfInputs() {
return 1;
}
@Override
public Class<GroupCombineFunction<IN, OUT>> getStubType() {
@SuppressWarnings("unchecked")
final Class<GroupCombineFunction<IN, OUT>> clazz =
(Class<GroupCombineFunction<IN, OUT>>) (Class<?>) GroupCombineFunction.class;
return clazz;
}
@Override
public int getNumberOfDriverComparators() {
return 2;
}
@Override
public void prepare() throws Exception {
final DriverStrategy driverStrategy = this.taskContext.getTaskConfig().getDriverStrategy();
if (driverStrategy != DriverStrategy.SORTED_GROUP_COMBINE) {
throw new Exception(
"Invalid strategy " + driverStrategy + " for group reduce combiner.");
}
final TypeSerializerFactory<IN> serializerFactory = this.taskContext.getInputSerializer(0);
this.serializer = serializerFactory.getSerializer();
final TypeComparator<IN> sortingComparator = this.taskContext.getDriverComparator(0);
this.groupingComparator = this.taskContext.getDriverComparator(1);
this.combiner = this.taskContext.getStub();
this.output = this.taskContext.getOutputCollector();
MemoryManager memManager = this.taskContext.getMemoryManager();
final int numMemoryPages =
memManager.computeNumberOfPages(
this.taskContext.getTaskConfig().getRelativeMemoryDriver());
this.memory =
memManager.allocatePages(this.taskContext.getContainingTask(), numMemoryPages);
// instantiate a fix-length in-place sorter, if possible, otherwise the out-of-place sorter
if (sortingComparator.supportsSerializationWithKeyNormalization()
&& this.serializer.getLength() > 0
&& this.serializer.getLength() <= THRESHOLD_FOR_IN_PLACE_SORTING) {
this.sorter =
new FixedLengthRecordSorter<IN>(
this.serializer, sortingComparator.duplicate(), memory);
} else {
this.sorter =
new NormalizedKeySorter<IN>(
this.serializer, sortingComparator.duplicate(), memory);
}
ExecutionConfig executionConfig = taskContext.getExecutionConfig();
this.objectReuseEnabled = executionConfig.isObjectReuseEnabled();
if (LOG.isDebugEnabled()) {
LOG.debug(
"GroupReduceCombineDriver object reuse: {}.",
(this.objectReuseEnabled ? "ENABLED" : "DISABLED"));
}
}
@Override
public void run() throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("Combiner starting.");
}
final MutableObjectIterator<IN> in = this.taskContext.getInput(0);
final TypeSerializer<IN> serializer = this.serializer;
if (objectReuseEnabled) {
IN value = serializer.createInstance();
while (running && (value = in.next(value)) != null) {
// try writing to the sorter first
if (this.sorter.write(value)) {
continue;
}
// do the actual sorting, combining, and data writing
sortAndCombineAndRetryWrite(value);
}
} else {
IN value;
while (running && (value = in.next()) != null) {
// try writing to the sorter first
if (this.sorter.write(value)) {
continue;
}
// do the actual sorting, combining, and data writing
sortAndCombineAndRetryWrite(value);
}
}
// sort, combine, and send the final batch
if (running) {
sortAndCombine();
}
}
private void sortAndCombine() throws Exception {
if (sorter.isEmpty()) {
return;
}
final InMemorySorter<IN> sorter = this.sorter;
this.sortAlgo.sort(sorter);
final GroupCombineFunction<IN, OUT> combiner = this.combiner;
final Collector<OUT> output = this.output;
// iterate over key groups
if (objectReuseEnabled) {
final ReusingKeyGroupedIterator<IN> keyIter =
new ReusingKeyGroupedIterator<IN>(
sorter.getIterator(), this.serializer, this.groupingComparator);
while (this.running && keyIter.nextKey()) {
combiner.combine(keyIter.getValues(), output);
}
} else {
final NonReusingKeyGroupedIterator<IN> keyIter =
new NonReusingKeyGroupedIterator<IN>(
sorter.getIterator(), this.groupingComparator);
while (this.running && keyIter.nextKey()) {
combiner.combine(keyIter.getValues(), output);
}
}
}
private void sortAndCombineAndRetryWrite(IN value) throws Exception {
sortAndCombine();
this.sorter.reset();
// write the value again
if (!this.sorter.write(value)) {
++oversizedRecordCount;
LOG.debug(
"Cannot write record to fresh sort buffer, record is too large. "
+ "Oversized record count: {}",
oversizedRecordCount);
// simply forward the record. We need to pass it through the combine function to convert
// it
Iterable<IN> input = Collections.singleton(value);
this.combiner.combine(input, this.output);
this.sorter.reset();
}
}
@Override
public void cleanup() throws Exception {
if (this.sorter != null) {
this.sorter.dispose();
}
this.taskContext.getMemoryManager().release(this.memory);
}
@Override
public void cancel() {
this.running = false;
if (this.sorter != null) {
try {
this.sorter.dispose();
} catch (Exception e) {
// may happen during concurrent modification
}
}
this.taskContext.getMemoryManager().release(this.memory);
}
/**
* Gets the number of oversized records handled by this combiner.
*
* @return The number of oversized records handled by this combiner.
*/
public long getOversizedRecordCount() {
return oversizedRecordCount;
}
}
| GroupReduceCombineDriver |
java | elastic__elasticsearch | modules/lang-painless/src/main/java/org/elasticsearch/painless/ClassWriter.java | {
"start": 868,
"end": 922
} | class ____ possibly
* clinit if necessary.
*/
public | and |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/filter/factory/rewrite/GzipMessageBodyResolver.java | {
"start": 983,
"end": 1833
} | class ____ implements MessageBodyDecoder, MessageBodyEncoder {
@Override
public String encodingType() {
return "gzip";
}
@Override
public byte[] decode(byte[] encoded) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
GZIPInputStream gis = new GZIPInputStream(bis);
return FileCopyUtils.copyToByteArray(gis);
}
catch (IOException e) {
throw new IllegalStateException("couldn't decode body from gzip", e);
}
}
@Override
public byte[] encode(DataBuffer original) {
try {
ByteArrayOutputStream bis = new ByteArrayOutputStream();
GZIPOutputStream gos = new GZIPOutputStream(bis);
FileCopyUtils.copy(original.asInputStream(), gos);
return bis.toByteArray();
}
catch (IOException e) {
throw new IllegalStateException("couldn't encode body to gzip", e);
}
}
}
| GzipMessageBodyResolver |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/scanning/ClassInjectorTransformer.java | {
"start": 2703,
"end": 8712
} | class ____ implements BiFunction<String, ClassVisitor, ClassVisitor> {
private static final String WEB_APPLICATION_EXCEPTION_BINARY_NAME = WebApplicationException.class.getName().replace('.',
'/');
private static final String NOT_FOUND_EXCEPTION_BINARY_NAME = NotFoundException.class.getName().replace('.', '/');
private static final String BAD_REQUEST_EXCEPTION_BINARY_NAME = BadRequestException.class.getName().replace('.', '/');
private static final String PARAMETER_CONVERTER_BINARY_NAME = ParameterConverter.class.getName()
.replace('.', '/');
private static final String PARAMETER_CONVERTER_DESCRIPTOR = "L" + PARAMETER_CONVERTER_BINARY_NAME + ";";
private static final String QUARKUS_REST_INJECTION_TARGET_BINARY_NAME = ResteasyReactiveInjectionTarget.class.getName()
.replace('.', '/');
private static final String QUARKUS_REST_INJECTION_CONTEXT_BINARY_NAME = ResteasyReactiveInjectionContext.class.getName()
.replace('.', '/');
private static final String QUARKUS_REST_INJECTION_CONTEXT_DESCRIPTOR = "L" + QUARKUS_REST_INJECTION_CONTEXT_BINARY_NAME
+ ";";
private static final String INJECT_METHOD_NAME = "__quarkus_rest_inject";
private static final String INJECT_METHOD_DESCRIPTOR = "(" + QUARKUS_REST_INJECTION_CONTEXT_DESCRIPTOR + ")V";
private static final String QUARKUS_REST_DEPLOYMENT_BINARY_NAME = Deployment.class.getName().replace('.', '/');
private static final String QUARKUS_REST_DEPLOYMENT_DESCRIPTOR = "L" + QUARKUS_REST_DEPLOYMENT_BINARY_NAME + ";";
public static final String INIT_CONVERTER_METHOD_NAME = "__quarkus_init_converter__";
private static final String INIT_CONVERTER_FIELD_NAME = "__quarkus_converter__";
private static final String INIT_CONVERTER_METHOD_DESCRIPTOR = "(" + QUARKUS_REST_DEPLOYMENT_DESCRIPTOR + ")V";
private static final String PARAMETER_CONVERTER_SUPPORT_BINARY_NAME = ParameterConverterSupport.class.getName().replace('.',
'/');
private static final String MULTIPART_SUPPORT_BINARY_NAME = MultipartSupport.class.getName().replace('.', '/');
private static final String OBJECT_BINARY_NAME = Object.class.getName().replace('.', '/');
private static final String OBJECT_DESCRIPTOR = "L" + OBJECT_BINARY_NAME + ";";
private static final String STRING_BINARY_NAME = String.class.getName().replace('.', '/');
private static final String STRING_DESCRIPTOR = "L" + STRING_BINARY_NAME + ";";
private static final String BYTE_ARRAY_DESCRIPTOR = "[B";
private static final String INPUT_STREAM_BINARY_NAME = InputStream.class.getName().replace('.', '/');
private static final String INPUT_STREAM_DESCRIPTOR = "L" + INPUT_STREAM_BINARY_NAME + ";";
private static final String LIST_BINARY_NAME = List.class.getName().replace('.', '/');
private static final String LIST_DESCRIPTOR = "L" + LIST_BINARY_NAME + ";";
private static final String TYPE_BINARY_NAME = java.lang.reflect.Type.class.getName().replace('.', '/');
private static final String TYPE_DESCRIPTOR = "L" + TYPE_BINARY_NAME + ";";
private static final String CLASS_BINARY_NAME = Class.class.getName().replace('.', '/');
private static final String CLASS_DESCRIPTOR = "L" + CLASS_BINARY_NAME + ";";
private static final String MEDIA_TYPE_BINARY_NAME = MediaType.class.getName().replace('.', '/');
private static final String MEDIA_TYPE_DESCRIPTOR = "L" + MEDIA_TYPE_BINARY_NAME + ";";
private static final String DEPLOYMENT_UTILS_BINARY_NAME = DeploymentUtils.class.getName().replace('.', '/');
private static final String DEPLOYMENT_UTILS_DESCRIPTOR = "L" + DEPLOYMENT_UTILS_BINARY_NAME + ";";
private static final String TYPE_DESCRIPTOR_PARSER_BINARY_NAME = TypeSignatureParser.class.getName().replace('.', '/');
private static final String TYPE_DESCRIPTOR_PARSER_DESCRIPTOR = "L" + TYPE_DESCRIPTOR_PARSER_BINARY_NAME + ";";
private static final String FILE_BINARY_NAME = File.class.getName().replace('.', '/');
private static final String FILE_DESCRIPTOR = "L" + FILE_BINARY_NAME + ";";
private static final String PATH_BINARY_NAME = Path.class.getName().replace('.', '/');
private static final String PATH_DESCRIPTOR = "L" + PATH_BINARY_NAME + ";";
private static final String DEFAULT_FILE_UPLOAD_BINARY_NAME = DefaultFileUpload.class.getName().replace('.', '/');
private static final String DEFAULT_FILE_UPLOAD_DESCRIPTOR = "L" + DEFAULT_FILE_UPLOAD_BINARY_NAME + ";";
private static final String FILE_UPLOAD_BINARY_NAME = FileUpload.class.getName().replace('.', '/');
private static final String RESTEASY_REACTIVE_REQUEST_CONTEXT_BINARY_NAME = ResteasyReactiveRequestContext.class.getName()
.replace('.', '/');
private static final String RESTEASY_REACTIVE_REQUEST_CONTEXT_DESCRIPTOR = "L"
+ RESTEASY_REACTIVE_REQUEST_CONTEXT_BINARY_NAME + ";";
private final Map<FieldInfo, ServerIndexedParameter> fieldExtractors;
private final boolean superTypeIsInjectable;
/**
* If this is true then we will create a new bean param instance, rather than assuming it has been created for us
*/
private final boolean requireCreateBeanParams;
private IndexView indexView;
public ClassInjectorTransformer(Map<FieldInfo, ServerIndexedParameter> fieldExtractors, boolean superTypeIsInjectable,
boolean requireCreateBeanParams, IndexView indexView) {
this.fieldExtractors = fieldExtractors;
this.superTypeIsInjectable = superTypeIsInjectable;
this.requireCreateBeanParams = requireCreateBeanParams;
this.indexView = indexView;
}
@Override
public ClassVisitor apply(String classname, ClassVisitor visitor) {
return new ClassInjectorVisitor(Gizmo.ASM_API_VERSION, visitor,
fieldExtractors, superTypeIsInjectable,
requireCreateBeanParams, indexView);
}
static | ClassInjectorTransformer |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/assignability/generics/RawTypeAssignabilityTest.java | {
"start": 1186,
"end": 1742
} | class ____ {
@Inject
Foo rawFoo;
@Inject
Foo<Object> objectFoo;
@Inject
Foo<?> wildFoo;
@Inject
Foo<Long> longFoo;
public String pingWild() {
return wildFoo.ping();
}
public String pingRaw() {
return rawFoo.ping();
}
public String pingObject() {
return objectFoo.ping();
}
public String pingLong() {
return longFoo.ping();
}
}
@ApplicationScoped
static | MyConsumer |
java | apache__flink | flink-end-to-end-tests/flink-end-to-end-tests-common/src/main/java/org/apache/flink/tests/util/cache/TravisDownloadCache.java | {
"start": 1292,
"end": 2990
} | class ____ extends AbstractDownloadCache {
private static final String CACHE_FILE_NAME_DELIMITER = "__";
private static final Pattern CACHE_FILE_NAME_PATTERN =
Pattern.compile(
"(?<hash>.*)"
+ CACHE_FILE_NAME_DELIMITER
+ "(?<build>.*)"
+ CACHE_FILE_NAME_DELIMITER
+ "(?<name>.*)");
private final int ttl;
private final int buildNumber;
public TravisDownloadCache(final Path path, final int ttl, final int buildNumber) {
super(path);
this.ttl = ttl;
this.buildNumber = buildNumber;
}
@Override
Matcher createCacheFileMatcher(final String cacheFileName) {
return CACHE_FILE_NAME_PATTERN.matcher(cacheFileName);
}
@Override
String generateCacheFileName(final String url, final String fileName) {
final String hash = String.valueOf(url.hashCode());
return hash
+ CACHE_FILE_NAME_DELIMITER
+ buildNumber
+ CACHE_FILE_NAME_DELIMITER
+ fileName;
}
@Override
String regenerateOriginalFileName(final Matcher matcher) {
return matcher.group("name");
}
@Override
boolean exceedsTimeToLive(final Matcher matcher) {
int cachedBuildNumber = Integer.parseInt(matcher.group("build"));
return buildNumber - cachedBuildNumber > ttl;
}
@Override
boolean matchesCachedFile(final Matcher matcher, final String url) {
final String hash = matcher.group("hash");
return url.hashCode() == Integer.parseInt(hash);
}
}
| TravisDownloadCache |
java | quarkusio__quarkus | extensions/smallrye-fault-tolerance/deployment/src/test/java/io/quarkus/smallrye/faulttolerance/test/retry/when/RetryOnMethodRetryWhenOnClassTest.java | {
"start": 383,
"end": 951
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(RetryOnMethodRetryWhenOnClassService.class))
.assertException(e -> {
assertEquals(DefinitionException.class, e.getClass());
assertTrue(e.getMessage().contains("@RetryWhen present"));
assertTrue(e.getMessage().contains("@Retry is missing"));
});
@Test
public void test() {
}
}
| RetryOnMethodRetryWhenOnClassTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/generics/CompositeUserTypeInGenericSuperclassTest.java | {
"start": 3187,
"end": 3451
} | class ____ {
private Integer testProp;
public TestEmbeddable() {
}
public TestEmbeddable(Integer testProp) {
this.testProp = testProp;
}
public Integer getTestProp() {
return testProp;
}
}
@Entity( name = "TestEntity" )
static | TestEmbeddable |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/byte2darray/Byte2DArrayAssert_isNullOrEmpty_Test.java | {
"start": 947,
"end": 1401
} | class ____ extends Byte2DArrayAssertBaseTest {
@Override
protected Byte2DArrayAssert invoke_api_method() {
assertions.isNullOrEmpty();
return null;
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertNullOrEmpty(getInfo(assertions), getActual(assertions));
}
@Override
@Test
public void should_return_this() {
// Disable this test because isEmpty is void
}
}
| Byte2DArrayAssert_isNullOrEmpty_Test |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/hhh18829/AutoGeneratedIdClassTest.java | {
"start": 724,
"end": 1652
} | class ____ {
@Test
@WithClasses({Employee.class, AnotherEmployee.class, Address.class, EmployeeWithIdClass.class})
@TestForIssue(jiraKey = "HHH-18829")
void test() {
System.out.println( TestUtil.getMetaModelSourceAsString( Employee.class ) );
System.out.println( TestUtil.getMetaModelSourceAsString( AnotherEmployee.class ) );
System.out.println( TestUtil.getMetaModelSourceAsString( Address.class ) );
System.out.println( TestUtil.getMetaModelSourceAsString( EmployeeWithIdClass.class ) );
checkIfIdClassIsGenerated( Employee.class, new String[] {"empName", "empId"} );
checkIfIdClassIsGenerated( AnotherEmployee.class, new String[] {"empId", "empName"} );
final var clazz = getMetamodelClassFor( EmployeeWithIdClass.class );
assertTrue( Arrays.stream( clazz.getClasses() ).map( Class::getSimpleName )
.noneMatch( "Id"::equals ),
"EmployeeWithIdClass_ should not have inner | AutoGeneratedIdClassTest |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/streaming/api/datastream/extension/eventtime/EventTimeExtensionITCase.java | {
"start": 25204,
"end": 28279
} | class ____
implements TwoOutputEventTimeStreamProcessFunction<
Tuple2<Long, String>, Tuple2<Long, String>, Tuple2<Long, String>> {
public static ConcurrentLinkedQueue<Tuple2<Long, String>> receivedRecords =
new ConcurrentLinkedQueue<>();
public static ConcurrentLinkedQueue<Long> receivedEventTimes =
new ConcurrentLinkedQueue<>();
public static ConcurrentLinkedQueue<Long> invokedTimerTimes = new ConcurrentLinkedQueue<>();
private boolean needCollectReceivedWatermarkAndRecord;
private EventTimeManager eventTimeManager;
public TestTwoOutputEventTimeStreamProcessFunction(
boolean needCollectReceivedWatermarkAndRecord) {
this.needCollectReceivedWatermarkAndRecord = needCollectReceivedWatermarkAndRecord;
}
@Override
public void initEventTimeProcessFunction(EventTimeManager eventTimeManager) {
this.eventTimeManager = eventTimeManager;
}
@Override
public void processRecord(
Tuple2<Long, String> record,
Collector<Tuple2<Long, String>> output1,
Collector<Tuple2<Long, String>> output2,
TwoOutputPartitionedContext<Tuple2<Long, String>, Tuple2<Long, String>> ctx)
throws Exception {
if (needCollectReceivedWatermarkAndRecord) {
receivedRecords.add(record);
eventTimeManager.registerTimer(record.f0 + 1);
}
output1.collect(record);
output2.collect(record);
}
@Override
public WatermarkHandlingResult onWatermark(
Watermark watermark,
Collector<Tuple2<Long, String>> output1,
Collector<Tuple2<Long, String>> output2,
TwoOutputNonPartitionedContext<Tuple2<Long, String>, Tuple2<Long, String>> ctx) {
assertThat(EventTimeExtension.isEventTimeWatermark(watermark)).isFalse();
return WatermarkHandlingResult.PEEK;
}
@Override
public void onEventTimeWatermark(
long watermarkTimestamp,
Collector<Tuple2<Long, String>> output1,
Collector<Tuple2<Long, String>> output2,
TwoOutputNonPartitionedContext<Tuple2<Long, String>, Tuple2<Long, String>> ctx)
throws Exception {
if (needCollectReceivedWatermarkAndRecord) {
receivedEventTimes.add(watermarkTimestamp);
}
}
@Override
public void onEventTimer(
long timestamp,
Collector<Tuple2<Long, String>> output1,
Collector<Tuple2<Long, String>> output2,
TwoOutputPartitionedContext<Tuple2<Long, String>, Tuple2<Long, String>> ctx) {
if (needCollectReceivedWatermarkAndRecord) {
invokedTimerTimes.add(timestamp);
}
}
}
private static | TestTwoOutputEventTimeStreamProcessFunction |
java | elastic__elasticsearch | x-pack/plugin/esql/arrow/src/main/java/org/elasticsearch/xpack/esql/arrow/ArrowResponse.java | {
"start": 1865,
"end": 4486
} | class ____ {
private final BlockConverter converter;
private final String name;
private boolean multivalued;
public Column(String esqlType, String name) {
this.converter = ESQL_CONVERTERS.get(esqlType);
if (converter == null) {
throw new IllegalArgumentException("ES|QL type [" + esqlType + "] is not supported by the Arrow format");
}
this.name = name;
}
}
private final List<Column> columns;
private Iterator<ResponseSegment> segments;
private ResponseSegment currentSegment;
public ArrowResponse(List<Column> columns, List<Page> pages) {
this.columns = columns;
// Find multivalued columns
int colSize = columns.size();
for (int col = 0; col < colSize; col++) {
for (Page page : pages) {
if (page.getBlock(col).mayHaveMultivaluedFields()) {
columns.get(col).multivalued = true;
break;
}
}
}
currentSegment = new SchemaResponse(this);
List<ResponseSegment> rest = new ArrayList<>(pages.size());
for (Page page : pages) {
rest.add(new PageResponse(this, page));
}
rest.add(new EndResponse(this));
segments = rest.iterator();
}
@Override
public boolean isPartComplete() {
return currentSegment == null;
}
@Override
public boolean isLastPart() {
// Even if sent in chunks, the entirety of ESQL data is available, so it's single (chunked) part
return true;
}
@Override
public void getNextPart(ActionListener<ChunkedRestResponseBodyPart> listener) {
listener.onFailure(new IllegalStateException("no continuations available"));
}
@Override
public ReleasableBytesReference encodeChunk(int sizeHint, Recycler<BytesRef> recycler) throws IOException {
try {
return currentSegment.encodeChunk(sizeHint, recycler);
} finally {
if (currentSegment.isDone()) {
currentSegment = segments.hasNext() ? segments.next() : null;
}
}
}
@Override
public String getResponseContentTypeString() {
return ArrowFormat.CONTENT_TYPE;
}
@Override
public void close() {
currentSegment = null;
segments = null;
}
/**
* An Arrow response is composed of different segments, each being a set of chunks:
* the schema header, the data buffers, and the trailer.
*/
protected abstract static | Column |
java | google__dagger | javatests/dagger/internal/codegen/DaggerSuperficialValidationTest.java | {
"start": 3745,
"end": 3967
} | class ____ {",
" abstract MissingType<?> blah();",
"}"),
CompilerTests.kotlinSource(
"test.TestClass.kt",
"package test",
"",
"abstract | TestClass |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/rm/preemption/NoopAMPreemptionPolicy.java | {
"start": 1229,
"end": 2086
} | class ____ implements AMPreemptionPolicy {
@Override
public void init(AppContext context){
// do nothing
}
@Override
public void preempt(Context ctxt, PreemptionMessage preemptionRequests) {
// do nothing, ignore all requeusts
}
@Override
public void handleFailedContainer(TaskAttemptId attemptID) {
// do nothing
}
@Override
public boolean isPreempted(TaskAttemptId yarnAttemptID) {
return false;
}
@Override
public void reportSuccessfulPreemption(TaskAttemptId taskAttemptID) {
// ignore
}
@Override
public TaskCheckpointID getCheckpointID(TaskId taskId) {
return null;
}
@Override
public void setCheckpointID(TaskId taskId, TaskCheckpointID cid) {
// ignore
}
@Override
public void handleCompletedContainer(TaskAttemptId attemptID) {
// ignore
}
}
| NoopAMPreemptionPolicy |
java | apache__camel | dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/CamelLauncher.java | {
"start": 926,
"end": 1157
} | class ____ the Camel JBang Fat-Jar Launcher.
* <p>
* This launcher provides a self-contained executable JAR that includes all dependencies required to run Camel JBang
* without the need for the JBang two-step process.
*/
public | for |
java | google__auto | value/src/test/java/com/google/auto/value/processor/AutoOneOfCompilationTest.java | {
"start": 18646,
"end": 18708
} | interface ____ {}",
"",
" public | Nullable |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/root/ApplicationTest.java | {
"start": 4095,
"end": 4201
} | interface ____ {
@GET
@Path("ok")
String ok();
}
public static | IResourceTest |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/AzureBlobFileSystemStore.java | {
"start": 83096,
"end": 84219
} | class ____ {
private final String permission;
private final String umask;
Permissions(boolean isNamespaceEnabled, FsPermission permission,
FsPermission umask) {
if (isNamespaceEnabled) {
this.permission = getOctalNotation(permission);
this.umask = getOctalNotation(umask);
} else {
this.permission = null;
this.umask = null;
}
}
private String getOctalNotation(FsPermission fsPermission) {
Preconditions.checkNotNull(fsPermission, "fsPermission");
return String.format(AbfsHttpConstants.PERMISSION_FORMAT, fsPermission.toOctal());
}
public Boolean hasPermission() {
return permission != null && !permission.isEmpty();
}
public Boolean hasUmask() {
return umask != null && !umask.isEmpty();
}
public String getPermission() {
return permission;
}
public String getUmask() {
return umask;
}
@Override
public String toString() {
return String.format("{\"permission\":%s, \"umask\":%s}", permission,
umask);
}
}
/**
* A builder | Permissions |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/association/OneToOneAssociationTest.java | {
"start": 2193,
"end": 2507
} | class ____ {
@Id
Long id;
String login;
String password;
@OneToOne( mappedBy = "user" )
Customer customer;
void setLogin(String login) {
this.login = login;
}
Customer getCustomer() {
return customer;
}
void setCustomer(Customer customer) {
this.customer = customer;
}
}
}
| User |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperatorTest.java | {
"start": 70548,
"end": 72317
} | class ____
extends TableAsyncExecutionController<RowData, RowData, RowData> {
private static boolean insertTableDataAfterEmit = true;
public MyAsyncExecutionControllerDelegate(
AbstractTestSpec testSpec,
TableAsyncExecutionController<RowData, RowData, RowData> innerAec) {
super(
innerAec.getAsyncInvoke(),
innerAec.getEmitWatermark(),
entry -> {
if (insertTableDataAfterEmit) {
StreamingDeltaJoinOperator.InputIndexAwareStreamRecordQueueEntry
inputIndexAwareEntry =
((StreamingDeltaJoinOperator
.InputIndexAwareStreamRecordQueueEntry)
entry);
int inputIndex = inputIndexAwareEntry.getInputIndex();
//noinspection unchecked
insertTableData(
testSpec,
(StreamRecord<RowData>) inputIndexAwareEntry.getInputElement(),
inputIndex == 0);
}
innerAec.getEmitResult().accept(entry);
},
innerAec.getInferDrivenInputIndex(),
innerAec.getInferBlockingKey());
}
}
/**
* The {@link TestingFetcherResultFuture} is a simple implementation of {@link
* TableFunctionCollector} which forwards the collected collection.
*/
public static final | MyAsyncExecutionControllerDelegate |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/windowing/functions/InternalAsyncWindowFunction.java | {
"start": 2865,
"end": 3147
} | interface ____ extends java.io.Serializable {
long currentProcessingTime();
long currentWatermark();
KeyedStateStore windowState();
KeyedStateStore globalState();
<X> void output(OutputTag<X> outputTag, X value);
}
}
| InternalWindowContext |
java | apache__dubbo | dubbo-plugin/dubbo-triple-servlet/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/servlet/ServletHttpRequestAdapter.java | {
"start": 11087,
"end": 12183
} | class ____ extends ServletInputStream {
private final InputStream is;
HttpInputStream(InputStream is) {
this.is = is;
}
@Override
public int read() throws IOException {
return is.read();
}
@Override
public int read(byte[] b) throws IOException {
return is.read(b);
}
@Override
public void close() throws IOException {
is.close();
}
@Override
public int readLine(byte[] b, int off, int len) throws IOException {
return is.read(b, off, len);
}
@Override
public boolean isFinished() {
try {
return is.available() == 0;
} catch (IOException e) {
return false;
}
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
throw new UnsupportedOperationException();
}
}
}
| HttpInputStream |
java | elastic__elasticsearch | modules/repository-gcs/src/internalClusterTest/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobStoreRepositoryTests.java | {
"start": 11537,
"end": 15569
} | class ____ extends GoogleCloudStoragePlugin {
public TestGoogleCloudStoragePlugin(Settings settings) {
super(settings);
}
@Override
protected GoogleCloudStorageService createStorageService(ClusterService clusterService, ProjectResolver projectResolver) {
return new GoogleCloudStorageService(clusterService, projectResolver) {
@Override
StorageOptions createStorageOptions(
final GoogleCloudStorageClientSettings gcsClientSettings,
final HttpTransportOptions httpTransportOptions
) {
StorageOptions options = super.createStorageOptions(gcsClientSettings, httpTransportOptions);
return options.toBuilder()
.setStorageRetryStrategy(StorageRetryStrategy.getLegacyStorageRetryStrategy())
.setHost(options.getHost())
.setCredentials(options.getCredentials())
.setRetrySettings(
RetrySettings.newBuilder()
.setTotalTimeout(options.getRetrySettings().getTotalTimeout())
.setInitialRetryDelay(Duration.ofMillis(10L))
.setRetryDelayMultiplier(options.getRetrySettings().getRetryDelayMultiplier())
.setMaxRetryDelay(Duration.ofSeconds(1L))
.setMaxAttempts(0)
.setJittered(false)
.setInitialRpcTimeout(options.getRetrySettings().getInitialRpcTimeout())
.setRpcTimeoutMultiplier(options.getRetrySettings().getRpcTimeoutMultiplier())
.setMaxRpcTimeout(options.getRetrySettings().getMaxRpcTimeout())
.build()
)
.build();
}
};
}
@Override
public Map<String, Repository.Factory> getRepositories(
Environment env,
NamedXContentRegistry registry,
ClusterService clusterService,
BigArrays bigArrays,
RecoverySettings recoverySettings,
RepositoriesMetrics repositoriesMetrics,
SnapshotMetrics snapshotMetrics
) {
return Collections.singletonMap(
GoogleCloudStorageRepository.TYPE,
(projectId, metadata) -> new GoogleCloudStorageRepository(
projectId,
metadata,
registry,
this.storageService.get(),
clusterService,
bigArrays,
recoverySettings,
new GcsRepositoryStatsCollector(),
snapshotMetrics
) {
@Override
protected GoogleCloudStorageBlobStore createBlobStore() {
return new GoogleCloudStorageBlobStore(
getProjectId(),
metadata.settings().get("bucket"),
"test",
metadata.name(),
storageService.get(),
bigArrays,
randomIntBetween(1, 8) * 1024,
BackoffPolicy.noBackoff(),
this.statsCollector()
) {
@Override
long getLargeBlobThresholdInBytes() {
return ByteSizeUnit.MB.toBytes(1);
}
};
}
}
);
}
}
@SuppressForbidden(reason = "this test uses a HttpHandler to emulate a Google Cloud Storage endpoint")
private static | TestGoogleCloudStoragePlugin |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/mixed/CompletableAndThenPublisher.java | {
"start": 1169,
"end": 1652
} | class ____<R> extends Flowable<R> {
final CompletableSource source;
final Publisher<? extends R> other;
public CompletableAndThenPublisher(CompletableSource source,
Publisher<? extends R> other) {
this.source = source;
this.other = other;
}
@Override
protected void subscribeActual(Subscriber<? super R> s) {
source.subscribe(new AndThenPublisherSubscriber<R>(s, other));
}
static final | CompletableAndThenPublisher |
java | micronaut-projects__micronaut-core | router/src/main/java/io/micronaut/web/router/StatusRouteInfo.java | {
"start": 911,
"end": 2060
} | interface ____<T, R> extends MethodBasedRouteInfo<T, R>, RequestMatcher {
/**
* @return The type the exception originates from. Null if the error route is global.
*/
@Nullable
Class<?> originatingType();
/**
* @return The status
*/
HttpStatus status();
/**
* @return The status
*/
default int statusCode() {
return status().getCode();
}
/**
* Match the given HTTP status.
*
* @param status The status to match
* @return The route match
*/
Optional<RouteMatch<R>> match(HttpStatus status);
/**
* Match the given HTTP status.
*
* @param statusCode The status to match
* @return The route match
*/
default Optional<RouteMatch<R>> match(int statusCode) {
HttpStatus status;
try {
status = HttpStatus.valueOf(statusCode);
} catch (IllegalArgumentException iae) {
// custom status code
return Optional.empty();
}
return match(status);
}
/**
* Match the given HTTP status.
*
* @param originatingClass The | StatusRouteInfo |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/conversion/StringBuilderToStringConversion.java | {
"start": 365,
"end": 759
} | class ____ extends SimpleConversion {
@Override
protected String getToExpression(ConversionContext conversionContext) {
return "<SOURCE>.toString()";
}
@Override
protected String getFromExpression(ConversionContext conversionContext) {
return "new " + ConversionUtils.stringBuilder( conversionContext ) + "( <SOURCE> )";
}
}
| StringBuilderToStringConversion |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/cluster/ClusterStateObserverTests.java | {
"start": 1283,
"end": 3876
} | class ____ extends ESTestCase {
public void testClusterStateListenerToStringIncludesListenerToString() {
final ClusterApplierService clusterApplierService = mock(ClusterApplierService.class);
final AtomicBoolean listenerAdded = new AtomicBoolean();
doAnswer(invocation -> {
assertThat(Arrays.toString(invocation.getArguments()), containsString("test-listener"));
listenerAdded.set(true);
return null;
}).when(clusterApplierService).addTimeoutListener(any(), any());
final ClusterState clusterState = ClusterState.builder(new ClusterName("test")).nodes(DiscoveryNodes.builder()).build();
when(clusterApplierService.state()).thenReturn(clusterState);
final ClusterStateObserver clusterStateObserver = new ClusterStateObserver(
clusterState.version(),
clusterApplierService,
null,
logger,
new ThreadContext(Settings.EMPTY)
);
clusterStateObserver.waitForNextChange(new ClusterStateObserver.Listener() {
@Override
public void onNewClusterState(ClusterState state) {}
@Override
public void onClusterServiceClose() {}
@Override
public void onTimeout(TimeValue timeout) {}
@Override
public String toString() {
return "test-listener";
}
});
assertTrue(listenerAdded.get());
}
public void testWaitForState() throws Exception {
final ClusterState clusterState = ClusterState.builder(new ClusterName("test")).nodes(DiscoveryNodes.builder()).build();
final ClusterService clusterService = mock(ClusterService.class);
when(clusterService.state()).thenReturn(clusterState);
final PlainActionFuture<ClusterState> future = new PlainActionFuture<>();
ClusterStateObserver.waitForState(clusterService, new ThreadContext(Settings.EMPTY), new ClusterStateObserver.Listener() {
@Override
public void onNewClusterState(ClusterState state) {
future.onResponse(state);
}
@Override
public void onClusterServiceClose() {
fail("should not be called");
}
@Override
public void onTimeout(TimeValue timeout) {
fail("should not be called");
}
}, cs -> cs == clusterState, null, logger);
assertSame(clusterState, future.get(0L, TimeUnit.NANOSECONDS));
}
}
| ClusterStateObserverTests |
java | grpc__grpc-java | core/src/main/java/io/grpc/internal/HedgingPolicy.java | {
"start": 910,
"end": 2256
} | class ____ {
final int maxAttempts;
final long hedgingDelayNanos;
final Set<Code> nonFatalStatusCodes;
/**
* The caller is supposed to have validated the arguments and handled throwing exception or
* logging warnings already, so we avoid repeating args check here.
*/
HedgingPolicy(int maxAttempts, long hedgingDelayNanos, Set<Code> nonFatalStatusCodes) {
this.maxAttempts = maxAttempts;
this.hedgingDelayNanos = hedgingDelayNanos;
this.nonFatalStatusCodes = ImmutableSet.copyOf(nonFatalStatusCodes);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
HedgingPolicy that = (HedgingPolicy) other;
return maxAttempts == that.maxAttempts
&& hedgingDelayNanos == that.hedgingDelayNanos
&& Objects.equal(nonFatalStatusCodes, that.nonFatalStatusCodes);
}
@Override
public int hashCode() {
return Objects.hashCode(maxAttempts, hedgingDelayNanos, nonFatalStatusCodes);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("maxAttempts", maxAttempts)
.add("hedgingDelayNanos", hedgingDelayNanos)
.add("nonFatalStatusCodes", nonFatalStatusCodes)
.toString();
}
}
| HedgingPolicy |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java | {
"start": 21694,
"end": 22028
} | class ____ extends
TestClass1WithMultiLevelContextHierarchyAndUnnamedConfig {
}
@ContextHierarchy({//
//
@ContextConfiguration(locations = "3-A.xml"),//
@ContextConfiguration(locations = "3-B.xml"),//
@ContextConfiguration(locations = "3-C.xml") //
})
private static | TestClass2WithMultiLevelContextHierarchyAndUnnamedConfig |
java | netty__netty | testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketConnectTest.java | {
"start": 11239,
"end": 11816
} | class ____ extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ByteBuf) {
ByteBuf buffer = ctx.alloc().buffer();
ByteBuf buf = (ByteBuf) msg;
buffer.writeBytes(buf);
buf.release();
ctx.channel().writeAndFlush(buffer);
} else {
throw new IllegalArgumentException("Unexpected message type: " + msg);
}
}
}
}
| EchoServerHandler |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/BothBlockingAndNonBlockingOnMethodTest.java | {
"start": 615,
"end": 1209
} | class ____ {
@RegisterExtension
static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(Resource.class);
}
}).setExpectedException(DeploymentException.class);
@Test
public void test() {
fail("Should never have been called");
}
@Path("test")
public static | BothBlockingAndNonBlockingOnMethodTest |
java | spring-projects__spring-boot | buildSrc/src/main/java/org/springframework/boot/build/testing/TestFailuresPlugin.java | {
"start": 1647,
"end": 2577
} | class ____ implements TestListener {
private final List<TestDescriptor> failures = new ArrayList<>();
private final Provider<TestResultsOverview> testResultsOverview;
private final Test test;
private FailureRecordingTestListener(Provider<TestResultsOverview> testResultOverview, Test test) {
this.testResultsOverview = testResultOverview;
this.test = test;
}
@Override
public void afterSuite(TestDescriptor descriptor, TestResult result) {
if (!this.failures.isEmpty()) {
this.testResultsOverview.get().addFailures(this.test, this.failures);
}
}
@Override
public void afterTest(TestDescriptor descriptor, TestResult result) {
if (result.getFailedTestCount() > 0) {
this.failures.add(descriptor);
}
}
@Override
public void beforeSuite(TestDescriptor descriptor) {
}
@Override
public void beforeTest(TestDescriptor descriptor) {
}
}
}
| FailureRecordingTestListener |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/ingest/IngestAsyncProcessorIT.java | {
"start": 4159,
"end": 6873
} | class ____ extends Plugin implements IngestPlugin {
private ThreadPool threadPool;
@Override
public Collection<?> createComponents(PluginServices services) {
this.threadPool = services.threadPool();
return List.of();
}
@Override
public Map<String, Processor.Factory> getProcessors(Processor.Parameters parameters) {
return Map.of("test-async", (factories, tag, description, config, projectId) -> new AbstractProcessor(tag, description) {
@Override
public void execute(IngestDocument ingestDocument, BiConsumer<IngestDocument, Exception> handler) {
threadPool.generic().execute(() -> {
String id = (String) ingestDocument.getSourceAndMetadata().get("_id");
if (id.equals(String.valueOf(ERROR))) {
// lucky number seven always fails
handler.accept(ingestDocument, new RuntimeException("lucky number seven"));
} else {
if (usually()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// ignore
}
}
ingestDocument.setFieldValue("foo", "bar-" + id);
handler.accept(ingestDocument, null);
}
});
}
@Override
public String getType() {
return "test-async";
}
@Override
public boolean isAsync() {
return true;
}
}, "test", (processorFactories, tag, description, config, projectId) -> new AbstractProcessor(tag, description) {
@Override
public IngestDocument execute(IngestDocument ingestDocument) throws Exception {
String id = (String) ingestDocument.getSourceAndMetadata().get("_id");
if (id.equals(String.valueOf(DROPPED))) {
// lucky number three is always dropped
return null;
} else {
ingestDocument.setFieldValue("bar", "baz-" + id);
return ingestDocument;
}
}
@Override
public String getType() {
return "test";
}
});
}
}
}
| TestPlugin |
java | elastic__elasticsearch | x-pack/plugin/rank-rrf/src/main/java/org/elasticsearch/xpack/rank/linear/LinearRankDoc.java | {
"start": 1003,
"end": 5387
} | class ____ extends RankDoc {
public static final String NAME = "linear_rank_doc";
final float[] weights;
final String[] normalizers;
public float[] normalizedScores;
public LinearRankDoc(int doc, float score, int shardIndex) {
super(doc, score, shardIndex);
this.weights = null;
this.normalizers = null;
}
public LinearRankDoc(int doc, float score, int shardIndex, float[] weights, String[] normalizers) {
super(doc, score, shardIndex);
this.weights = weights;
this.normalizers = normalizers;
}
public LinearRankDoc(StreamInput in) throws IOException {
super(in);
weights = in.readOptionalFloatArray();
normalizedScores = in.readOptionalFloatArray();
normalizers = in.readOptionalStringArray();
}
@Override
public Explanation explain(Explanation[] sources, String[] queryNames) {
assert normalizedScores != null && weights != null && normalizers != null;
assert normalizedScores.length == sources.length;
Explanation[] details = new Explanation[sources.length];
for (int i = 0; i < sources.length; i++) {
final String queryAlias = queryNames[i] == null ? "" : " [" + queryNames[i] + "]";
final String queryIdentifier = "at index [" + i + "]" + queryAlias;
final float weight = weights == null ? DEFAULT_WEIGHT : weights[i];
final float normalizedScore = normalizedScores == null ? DEFAULT_SCORE : normalizedScores[i];
final String normalizer = normalizers == null ? DEFAULT_NORMALIZER.getName() : normalizers[i];
if (normalizedScore > 0) {
details[i] = Explanation.match(
weight * normalizedScore,
"weighted score: ["
+ weight * normalizedScore
+ "] in query "
+ queryIdentifier
+ " computed as ["
+ weight
+ " * "
+ normalizedScore
+ "]"
+ " using score normalizer ["
+ normalizer
+ "]"
+ " for original matching query with score:",
sources[i]
);
} else {
final String description = "weighted score: [0], result not found in query " + queryIdentifier;
details[i] = Explanation.noMatch(description);
}
}
return Explanation.match(
score,
"weighted linear combination score: ["
+ score
+ "] computed for normalized scores "
+ Arrays.toString(normalizedScores)
+ (weights == null ? "" : " and weights " + Arrays.toString(weights))
+ " as sum of (weight[i] * score[i]) for each query.",
details
);
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeOptionalFloatArray(weights);
out.writeOptionalFloatArray(normalizedScores);
out.writeOptionalStringArray(normalizers);
}
@Override
protected void doToXContent(XContentBuilder builder, Params params) throws IOException {
if (weights != null) {
builder.field("weights", weights);
}
if (normalizedScores != null) {
builder.field("normalizedScores", normalizedScores);
}
if (normalizers != null) {
builder.field("normalizers", normalizers);
}
}
@Override
public boolean doEquals(RankDoc rd) {
LinearRankDoc lrd = (LinearRankDoc) rd;
return Arrays.equals(weights, lrd.weights)
&& Arrays.equals(normalizedScores, lrd.normalizedScores)
&& Arrays.equals(normalizers, lrd.normalizers);
}
@Override
public int doHashCode() {
int result = Objects.hash(Arrays.hashCode(weights), Arrays.hashCode(normalizedScores), Arrays.hashCode(normalizers));
return 31 * result;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_18_0;
}
}
| LinearRankDoc |
java | apache__flink | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/sink/compactor/DecoderBasedReader.java | {
"start": 2185,
"end": 2735
} | interface ____<T> extends Serializable {
/** Prepares to start decoding the input stream. */
void open(InputStream input) throws IOException;
/**
* @return The next record that decoded from the opened input stream, or null if no more
* available.
*/
T decodeNext() throws IOException;
/** Closes the open resources. The decoder is responsible to close the input stream. */
void close() throws IOException;
/** Factory to create {@link Decoder}. */
| Decoder |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/routing/allocation/WriteLoadConstraintSettings.java | {
"start": 1285,
"end": 6144
} | enum ____ {
/**
* The decider is disabled
*/
DISABLED,
/**
* Only the low write low threshold, to try to avoid allocating to a node exceeding
* {@link #WRITE_LOAD_DECIDER_HIGH_UTILIZATION_THRESHOLD_SETTING}. Write-load hot-spot will not trigger rebalancing.
*/
LOW_THRESHOLD_ONLY,
/**
* All write load decider development work is turned on.
*/
ENABLED;
public boolean fullyEnabled() {
return this == ENABLED;
}
public boolean notFullyEnabled() {
return this != ENABLED;
}
public boolean atLeastLowThresholdEnabled() {
return this != DISABLED;
}
public boolean disabled() {
return this == DISABLED;
}
}
public static final Setting<WriteLoadDeciderStatus> WRITE_LOAD_DECIDER_ENABLED_SETTING = Setting.enumSetting(
WriteLoadDeciderStatus.class,
SETTING_PREFIX + "enabled",
WRITE_LOAD_DECIDER_FEATURE_FLAG.isEnabled() ? WriteLoadDeciderStatus.ENABLED : WriteLoadDeciderStatus.DISABLED,
Setting.Property.Dynamic,
Setting.Property.NodeScope
);
/**
* The threshold over which we consider write thread pool utilization "high"
*/
public static final Setting<RatioValue> WRITE_LOAD_DECIDER_HIGH_UTILIZATION_THRESHOLD_SETTING = new Setting<>(
SETTING_PREFIX + "high_utilization_threshold",
"90%",
RatioValue::parseRatioValue,
Setting.Property.Dynamic,
Setting.Property.NodeScope
);
/**
* The duration for which we need to see "high" utilization before we consider the low threshold exceeded
*/
public static final Setting<TimeValue> WRITE_LOAD_DECIDER_HIGH_UTILIZATION_DURATION_SETTING = Setting.timeSetting(
SETTING_PREFIX + "high_utilization_duration",
TimeValue.timeValueMinutes(10),
Setting.Property.Dynamic,
Setting.Property.NodeScope
);
/**
* When the decider is {@link WriteLoadDeciderStatus#ENABLED}, the write-load monitor will call
* {@link RerouteService#reroute(String, Priority, ActionListener)} when we see tasks being delayed by this amount of time
* (but no more often than {@link #WRITE_LOAD_DECIDER_REROUTE_INTERVAL_SETTING})
*/
public static final Setting<TimeValue> WRITE_LOAD_DECIDER_QUEUE_LATENCY_THRESHOLD_SETTING = Setting.timeSetting(
SETTING_PREFIX + "queue_latency_threshold",
TimeValue.timeValueSeconds(10),
Setting.Property.Dynamic,
Setting.Property.NodeScope
);
/**
* The minimum amount of time between successive calls to reroute to address write load hot-spots
*/
public static final Setting<TimeValue> WRITE_LOAD_DECIDER_REROUTE_INTERVAL_SETTING = Setting.timeSetting(
SETTING_PREFIX + "reroute_interval",
TimeValue.ZERO,
Setting.Property.Dynamic,
Setting.Property.NodeScope
);
/**
* The minimum amount of time between logging messages about write load decider interventions
*/
public static final Setting<TimeValue> WRITE_LOAD_DECIDER_MINIMUM_LOGGING_INTERVAL = Setting.timeSetting(
SETTING_PREFIX + "log_interval",
TimeValue.timeValueMinutes(1),
Setting.Property.Dynamic,
Setting.Property.NodeScope
);
private volatile WriteLoadDeciderStatus writeLoadDeciderStatus;
private volatile TimeValue minimumRerouteInterval;
private volatile double highUtilizationThreshold;
private volatile TimeValue queueLatencyThreshold;
public WriteLoadConstraintSettings(ClusterSettings clusterSettings) {
clusterSettings.initializeAndWatch(WRITE_LOAD_DECIDER_ENABLED_SETTING, status -> this.writeLoadDeciderStatus = status);
clusterSettings.initializeAndWatch(
WRITE_LOAD_DECIDER_REROUTE_INTERVAL_SETTING,
timeValue -> this.minimumRerouteInterval = timeValue
);
clusterSettings.initializeAndWatch(
WRITE_LOAD_DECIDER_HIGH_UTILIZATION_THRESHOLD_SETTING,
value -> highUtilizationThreshold = value.getAsRatio()
);
clusterSettings.initializeAndWatch(WRITE_LOAD_DECIDER_QUEUE_LATENCY_THRESHOLD_SETTING, value -> queueLatencyThreshold = value);
}
public WriteLoadDeciderStatus getWriteLoadConstraintEnabled() {
return this.writeLoadDeciderStatus;
}
public TimeValue getMinimumRerouteInterval() {
return this.minimumRerouteInterval;
}
public TimeValue getQueueLatencyThreshold() {
return this.queueLatencyThreshold;
}
/**
* @return The threshold as a ratio - i.e. in [0, 1]
*/
public double getHighUtilizationThreshold() {
return this.highUtilizationThreshold;
}
}
| WriteLoadDeciderStatus |
java | FasterXML__jackson-core | src/test/java/tools/jackson/core/unittest/filter/ParserFiltering700Test.java | {
"start": 641,
"end": 5895
} | class ____ extends TokenFilter {
@Override
public TokenFilter includeProperty(String name) {
if ("@type".equals(name)) {
return null;
}
return this;
}
}
/*
/**********************************************************************
/* Test methods, [core#700]
/**********************************************************************
*/
private final JsonFactory JSON_F = newStreamFactory();
// [core#700], simplified
@Test
void skippingRootLevel() throws Exception
{
final String json = a2q("{'@type':'yyy','value':12}");
// should become: {"value":12}
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new NoTypeFilter(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
assertEquals("value", p.currentName());
// 19-Jul-2021, tatu: while not ideal, existing contract is that "getText()"
// ought to return property name as well...
assertEquals("value", p.getString());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(12, p.getIntValue());
assertEquals(JsonToken.END_OBJECT, p.nextToken());
assertNull(p.nextToken());
p.close();
}
// [core#700], medium test
@Test
void skippingOneNested() throws Exception
{
final String json = a2q("{'value':{'@type':'yyy','a':12}}");
// should become: {"value":{"a":12}}
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new NoTypeFilter(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
assertEquals("value", p.currentName());
// as earlier, this needs to hold true too
assertEquals("value", p.getString());
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
assertEquals("a", p.currentName());
assertEquals("a", p.getString());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(12, p.getIntValue());
assertEquals(JsonToken.END_OBJECT, p.nextToken());
assertEquals(JsonToken.END_OBJECT, p.nextToken());
assertNull(p.nextToken());
p.close();
}
// [core#700], full test
@Test
void skippingForSingleWithPath() throws Exception
{
_testSkippingForSingleWithPath(false);
_testSkippingForSingleWithPath(true);
}
private void _testSkippingForSingleWithPath(boolean useNextName) throws Exception
{
final String json = a2q("{'@type':'xxx','value':{'@type':'yyy','a':99}}");
// should become: {"value":{"a":99}}
JsonParser p0 = _createParser(JSON_F, json);
JsonParser p = new FilteringParserDelegate(p0,
new NoTypeFilter(),
Inclusion.INCLUDE_ALL_AND_PATH,
true // multipleMatches
);
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertTrue(p.isExpectedStartObjectToken());
if (useNextName) {
assertEquals("value", p.nextName());
// as earlier, this needs to hold true too
assertEquals("value", p.getString());
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertTrue(p.isExpectedStartObjectToken());
assertEquals("a", p.nextName());
assertEquals("a", p.getString());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(99, p.getIntValue());
assertNull(p.nextName());
assertEquals(JsonToken.END_OBJECT, p.currentToken());
} else {
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
assertEquals("value", p.currentName());
assertEquals("value", p.getString());
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertTrue(p.isExpectedStartObjectToken());
assertToken(JsonToken.PROPERTY_NAME, p.nextToken());
assertEquals("a", p.currentName());
assertEquals("a", p.getString());
assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
assertEquals(99, p.getIntValue());
assertEquals(JsonToken.END_OBJECT, p.nextToken());
}
assertEquals(JsonToken.END_OBJECT, p.nextToken());
assertNull(p.nextToken());
p.close();
}
/*
/**********************************************************************
/* Helper methods
/**********************************************************************
*/
private JsonParser _createParser(TokenStreamFactory f, String json) throws Exception {
return f.createParser(ObjectReadContext.empty(), json);
}
}
| NoTypeFilter |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/features/ConflictingRequirementsException.java | {
"start": 990,
"end": 1635
} | class ____ extends Exception {
private final Set<Feature<?>> conflicts;
private final Object source;
public ConflictingRequirementsException(
String message, Set<Feature<?>> conflicts, Object source) {
super(message);
this.conflicts = conflicts;
this.source = source;
}
public Set<Feature<?>> getConflicts() {
return conflicts;
}
public Object getSource() {
return source;
}
@Override
public String getMessage() {
return super.getMessage() + " (source: " + source + ")";
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
| ConflictingRequirementsException |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessor.java | {
"start": 1690,
"end": 3083
} | class ____ implements BeanDefinitionRegistryPostProcessor, BeanPostProcessor {
/**
* The bean name of {@link DubboConfigConfigurationRegistrar}
*/
public static final String BEAN_NAME = "dubboConfigAliasPostProcessor";
private BeanDefinitionRegistry registry;
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
this.registry = registry;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// DO NOTHING
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// DO NOTHING
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof AbstractConfig) {
String id = ((AbstractConfig) bean).getId();
if (hasText(id) // id MUST be present in AbstractConfig
&& !nullSafeEquals(id, beanName) // id MUST NOT be equal to bean name
&& !BeanRegistrar.hasAlias(registry, beanName, id)) { // id MUST NOT be present in AliasRegistry
registry.registerAlias(beanName, id);
}
}
return bean;
}
}
| DubboConfigAliasPostProcessor |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/common/unit/DistanceUnitTests.java | {
"start": 766,
"end": 4777
} | class ____ extends ESTestCase {
public void testSimpleDistanceUnit() {
assertThat(DistanceUnit.KILOMETERS.convert(10, DistanceUnit.MILES), closeTo(16.09344, 0.001));
assertThat(DistanceUnit.MILES.convert(10, DistanceUnit.MILES), closeTo(10, 0.001));
assertThat(DistanceUnit.MILES.convert(10, DistanceUnit.KILOMETERS), closeTo(6.21371192, 0.001));
assertThat(DistanceUnit.NAUTICALMILES.convert(10, DistanceUnit.MILES), closeTo(8.689762, 0.001));
assertThat(DistanceUnit.KILOMETERS.convert(10, DistanceUnit.KILOMETERS), closeTo(10, 0.001));
assertThat(DistanceUnit.KILOMETERS.convert(10, DistanceUnit.METERS), closeTo(0.01, 0.00001));
assertThat(DistanceUnit.KILOMETERS.convert(1000, DistanceUnit.METERS), closeTo(1, 0.001));
assertThat(DistanceUnit.METERS.convert(1, DistanceUnit.KILOMETERS), closeTo(1000, 0.001));
}
public void testDistanceUnitParsing() {
assertThat(DistanceUnit.Distance.parseDistance("50km").unit, equalTo(DistanceUnit.KILOMETERS));
assertThat(DistanceUnit.Distance.parseDistance("500m").unit, equalTo(DistanceUnit.METERS));
assertThat(DistanceUnit.Distance.parseDistance("51mi").unit, equalTo(DistanceUnit.MILES));
assertThat(DistanceUnit.Distance.parseDistance("53nmi").unit, equalTo(DistanceUnit.NAUTICALMILES));
assertThat(DistanceUnit.Distance.parseDistance("53NM").unit, equalTo(DistanceUnit.NAUTICALMILES));
assertThat(DistanceUnit.Distance.parseDistance("52yd").unit, equalTo(DistanceUnit.YARD));
assertThat(DistanceUnit.Distance.parseDistance("12in").unit, equalTo(DistanceUnit.INCH));
assertThat(DistanceUnit.Distance.parseDistance("23mm").unit, equalTo(DistanceUnit.MILLIMETERS));
assertThat(DistanceUnit.Distance.parseDistance("23cm").unit, equalTo(DistanceUnit.CENTIMETERS));
double testValue = 12345.678;
for (DistanceUnit unit : DistanceUnit.values()) {
assertThat("Unit can be parsed from '" + unit.toString() + "'", DistanceUnit.fromString(unit.toString()), equalTo(unit));
assertThat(
"Unit can be parsed from '" + testValue + unit.toString() + "'",
DistanceUnit.fromString(unit.toString()),
equalTo(unit)
);
assertThat(
"Value can be parsed from '" + testValue + unit.toString() + "'",
DistanceUnit.Distance.parseDistance(unit.toString(testValue)).value,
equalTo(testValue)
);
}
}
/**
* This test ensures that we are aware of accidental reordering in the distance unit ordinals,
* since equality in e.g. CircleShapeBuilder, hashCode and serialization rely on them
*/
public void testDistanceUnitNames() {
assertEquals(0, DistanceUnit.INCH.ordinal());
assertEquals(1, DistanceUnit.YARD.ordinal());
assertEquals(2, DistanceUnit.FEET.ordinal());
assertEquals(3, DistanceUnit.KILOMETERS.ordinal());
assertEquals(4, DistanceUnit.NAUTICALMILES.ordinal());
assertEquals(5, DistanceUnit.MILLIMETERS.ordinal());
assertEquals(6, DistanceUnit.CENTIMETERS.ordinal());
assertEquals(7, DistanceUnit.MILES.ordinal());
assertEquals(8, DistanceUnit.METERS.ordinal());
}
public void testReadWrite() throws Exception {
for (DistanceUnit unit : DistanceUnit.values()) {
try (BytesStreamOutput out = new BytesStreamOutput()) {
unit.writeTo(out);
try (StreamInput in = out.bytes().streamInput()) {
assertThat("Roundtrip serialisation failed.", DistanceUnit.readFromStream(in), equalTo(unit));
}
}
}
}
public void testFromString() {
for (DistanceUnit unit : DistanceUnit.values()) {
assertThat("Roundtrip string parsing failed.", DistanceUnit.fromString(unit.toString()), equalTo(unit));
}
}
}
| DistanceUnitTests |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/aggregate/PresentOverTime.java | {
"start": 1395,
"end": 4050
} | class ____ extends TimeSeriesAggregateFunction {
public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(
Expression.class,
"PresentOverTime",
PresentOverTime::new
);
@FunctionInfo(
type = FunctionType.TIME_SERIES_AGGREGATE,
returnType = { "boolean" },
description = "Calculates the presence of a field in the output result over time range.",
appliesTo = { @FunctionAppliesTo(lifeCycle = FunctionAppliesToLifecycle.PREVIEW, version = "9.2.0") },
preview = true,
examples = { @Example(file = "k8s-timeseries", tag = "present_over_time") }
)
public PresentOverTime(
Source source,
@Param(
name = "field",
type = {
"aggregate_metric_double",
"boolean",
"cartesian_point",
"cartesian_shape",
"date",
"date_nanos",
"double",
"geo_point",
"geo_shape",
"geohash",
"geotile",
"geohex",
"integer",
"ip",
"keyword",
"long",
"text",
"unsigned_long",
"version" }
) Expression field
) {
this(source, field, Literal.TRUE, NO_WINDOW);
}
public PresentOverTime(Source source, Expression field, Expression filter, Expression window) {
super(source, field, filter, window, emptyList());
}
private PresentOverTime(StreamInput in) throws IOException {
super(in);
}
@Override
public String getWriteableName() {
return ENTRY.name;
}
@Override
public PresentOverTime withFilter(Expression filter) {
return new PresentOverTime(source(), field(), filter, window());
}
@Override
protected NodeInfo<PresentOverTime> info() {
return NodeInfo.create(this, PresentOverTime::new, field(), filter(), window());
}
@Override
public PresentOverTime replaceChildren(List<Expression> newChildren) {
return new PresentOverTime(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2));
}
@Override
protected TypeResolution resolveType() {
return perTimeSeriesAggregation().resolveType();
}
@Override
public DataType dataType() {
return perTimeSeriesAggregation().dataType();
}
@Override
public Present perTimeSeriesAggregation() {
return new Present(source(), field(), filter(), window());
}
}
| PresentOverTime |
java | quarkusio__quarkus | integration-tests/jackson/src/main/java/io/quarkus/it/jackson/InheritedModelWithBuilderResource.java | {
"start": 357,
"end": 717
} | class ____ {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response newModel(String body) throws IOException {
InheritedModelWithBuilder model = InheritedModelWithBuilder.fromJson(body);
return Response.status(201).entity(model.toJson()).build();
}
}
| InheritedModelWithBuilderResource |
java | junit-team__junit5 | junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/discovery/MethodSegmentResolver.java | {
"start": 964,
"end": 1286
} | class ____ {
// Pattern: [declaringClassName#]methodName(comma-separated list of parameter type names)
private static final Pattern METHOD_PATTERN = Pattern.compile(
"(?:(?<declaringClass>.+)#)?(?<method>.+)\\((?<parameters>.*)\\)");
/**
* If the {@code method} is package-private and declared a | MethodSegmentResolver |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.