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 | netty__netty | common/src/main/java/io/netty/util/Version.java | {
"start": 1070,
"end": 1412
} | class ____ the version information from {@code META-INF/io.netty.versions.properties}, which is
* generated in build time. Note that it may not be possible to retrieve the information completely, depending on
* your environment, such as the specified {@link ClassLoader}, the current {@link SecurityManager}.
* </p>
*/
public final | retrieves |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/util/concurrent/SpscArrayQueue.java | {
"start": 7973,
"end": 9272
} | class ____<T> extends SpscArrayQueueConsumer<T> {
/** */
private static final long serialVersionUID = -2684922090021364171L;
byte pad000,pad001,pad002,pad003,pad004,pad005,pad006,pad007;// 8b
byte pad010,pad011,pad012,pad013,pad014,pad015,pad016,pad017;// 16b
byte pad020,pad021,pad022,pad023,pad024,pad025,pad026,pad027;// 24b
byte pad030,pad031,pad032,pad033,pad034,pad035,pad036,pad037;// 32b
byte pad040,pad041,pad042,pad043,pad044,pad045,pad046,pad047;// 40b
byte pad050,pad051,pad052,pad053,pad054,pad055,pad056,pad057;// 48b
byte pad060,pad061,pad062,pad063,pad064,pad065,pad066,pad067;// 56b
byte pad070,pad071,pad072,pad073,pad074,pad075,pad076,pad077;// 64b
byte pad100,pad101,pad102,pad103,pad104,pad105,pad106,pad107;// 72b
byte pad110,pad111,pad112,pad113,pad114,pad115,pad116,pad117;// 80b
byte pad120,pad121,pad122,pad123,pad124,pad125,pad126,pad127;// 88b
byte pad130,pad131,pad132,pad133,pad134,pad135,pad136,pad137;// 96b
byte pad140,pad141,pad142,pad143,pad144,pad145,pad146,pad147;//104b
byte pad150,pad151,pad152,pad153,pad154,pad155,pad156,pad157;//112b
byte pad160,pad161,pad162,pad163,pad164,pad165,pad166,pad167;//120b
byte pad170,pad171,pad172,pad173,pad174,pad175,pad176,pad177;//128b
SpscArrayQueueP3(int length) {
super(length);
}
}
| SpscArrayQueueP3 |
java | google__dagger | javatests/dagger/internal/codegen/SourceFilesTest.java | {
"start": 1725,
"end": 2323
} | class ____ {}
@Test
public void testSimpleVariableName_randomKeywords() {
assertThat(simpleVariableName(For.class)).isEqualTo("for_");
assertThat(simpleVariableName(Goto.class)).isEqualTo("goto_");
}
@Test
public void testSimpleVariableName() {
assertThat(simpleVariableName(Object.class)).isEqualTo("object");
assertThat(simpleVariableName(List.class)).isEqualTo("list");
}
private static String simpleVariableName(Class<?> clazz) {
return SourceFiles.simpleVariableName(
XClassName.Companion.get(clazz.getPackageName(), clazz.getSimpleName()));
}
}
| Goto |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java | {
"start": 165108,
"end": 165196
} | interface ____<T> {
String doSomethingGeneric(T o);
}
public static | GenericInterface1 |
java | netty__netty | buffer/src/main/java/io/netty/buffer/AllocateBufferEvent.java | {
"start": 917,
"end": 1515
} | class ____ extends AbstractBufferEvent {
static final String NAME = "io.netty.AllocateBuffer";
private static final AllocateBufferEvent INSTANCE = new AllocateBufferEvent();
/**
* Statically check if this event is enabled.
*/
public static boolean isEventEnabled() {
return INSTANCE.isEnabled();
}
@Description("Is this chunk pooled, or is it a one-off allocation for this buffer?")
public boolean chunkPooled;
@Description("Is this buffer's chunk part of a thread-local magazine or arena?")
public boolean chunkThreadLocal;
}
| AllocateBufferEvent |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/repositories/IndexSnapshotsService.java | {
"start": 1538,
"end": 7446
} | class ____ {
private static final Logger logger = LogManager.getLogger(IndexSnapshotsService.class);
private static final Comparator<Tuple<SnapshotId, RepositoryData.SnapshotDetails>> START_TIME_COMPARATOR = Comparator.<
Tuple<SnapshotId, RepositoryData.SnapshotDetails>>comparingLong(pair -> pair.v2().getStartTimeMillis()).thenComparing(Tuple::v1);
private final RepositoriesService repositoriesService;
public IndexSnapshotsService(RepositoriesService repositoriesService) {
this.repositoriesService = repositoriesService;
}
public void getLatestSuccessfulSnapshotForShard(
String repositoryName,
ShardId shardId,
ActionListener<Optional<ShardSnapshotInfo>> originalListener
) {
assert repositoryName != null;
final ActionListener<Optional<ShardSnapshotInfo>> listener = originalListener.delegateResponse(
(delegate, err) -> delegate.onFailure(
new RepositoryException(repositoryName, "Unable to find the latest snapshot for shard [" + shardId + "]", err)
)
);
final Repository repository = getRepository(repositoryName);
if (repository == null) {
listener.onFailure(new RepositoryMissingException(repositoryName));
return;
}
final String indexName = shardId.getIndexName();
ListenableFuture<RepositoryData> repositoryDataStepListener = new ListenableFuture<>();
ListenableFuture<FetchShardSnapshotContext> snapshotInfoStepListener = new ListenableFuture<>();
repositoryDataStepListener.addListener(listener.delegateFailureAndWrap((delegate, repositoryData) -> {
if (repositoryData.hasIndex(indexName) == false) {
logger.debug("{} repository [{}] has no snapshots of this index", shardId, repositoryName);
delegate.onResponse(Optional.empty());
return;
}
final IndexId indexId = repositoryData.resolveIndexId(indexName);
final List<SnapshotId> indexSnapshots = repositoryData.getSnapshots(indexId);
final Optional<SnapshotId> latestSnapshotId = indexSnapshots.stream()
.map(snapshotId -> Tuple.tuple(snapshotId, repositoryData.getSnapshotDetails(snapshotId)))
.filter(s -> s.v2().getSnapshotState() != null && s.v2().getSnapshotState() == SnapshotState.SUCCESS)
.filter(s -> s.v2().getStartTimeMillis() != -1 && s.v2().getEndTimeMillis() != -1)
.max(START_TIME_COMPARATOR)
.map(Tuple::v1);
if (latestSnapshotId.isEmpty()) {
// It's possible that some of the backups were taken before 7.14 and they were successful backups, but they don't
// have the start/end date populated in RepositoryData. We could fetch all the backups and find out if there is
// a valid candidate, but for simplicity we just consider that we couldn't find any valid snapshot. Existing
// snapshots start/end timestamps should appear in the RepositoryData eventually.
logger.debug("{} could not determine latest snapshot of this shard in repository [{}]", shardId, repositoryName);
delegate.onResponse(Optional.empty());
return;
}
final SnapshotId snapshotId = latestSnapshotId.get();
logger.debug("{} fetching details of [{}][{}]", shardId, repositoryName, snapshotId);
repository.getSnapshotInfo(
snapshotId,
snapshotInfoStepListener.map(
snapshotInfo -> new FetchShardSnapshotContext(repository, repositoryData, indexId, shardId, snapshotInfo)
)
);
}));
snapshotInfoStepListener.addListener(listener.delegateFailureAndWrap((delegate, fetchSnapshotContext) -> {
assert ThreadPool.assertCurrentThreadPool(ThreadPool.Names.SNAPSHOT_META);
final SnapshotInfo snapshotInfo = fetchSnapshotContext.getSnapshotInfo();
if (snapshotInfo == null || snapshotInfo.state() != SnapshotState.SUCCESS) {
// We couldn't find a valid candidate
logger.debug("{} failed to retrieve snapshot details from [{}]", shardId, repositoryName);
delegate.onResponse(Optional.empty());
return;
}
// We fetch BlobStoreIndexShardSnapshots instead of BlobStoreIndexShardSnapshot in order to get the shardStateId that
// allows us to tell whether or not this shard had in-flight operations while the snapshot was taken.
final BlobStoreIndexShardSnapshots blobStoreIndexShardSnapshots = fetchSnapshotContext.getBlobStoreIndexShardSnapshots();
final String indexMetadataId = fetchSnapshotContext.getIndexMetadataId();
final Optional<ShardSnapshotInfo> indexShardSnapshotInfo = blobStoreIndexShardSnapshots.snapshots()
.stream()
.filter(snapshotFiles -> snapshotFiles.snapshot().equals(snapshotInfo.snapshotId().getName()))
.findFirst()
.map(snapshotFiles -> fetchSnapshotContext.createIndexShardSnapshotInfo(indexMetadataId, snapshotFiles));
delegate.onResponse(indexShardSnapshotInfo);
}));
repository.getRepositoryData(
EsExecutors.DIRECT_EXECUTOR_SERVICE, // TODO contemplate threading here, do we need to fork, see #101445?
repositoryDataStepListener
);
}
private Repository getRepository(String repositoryName) {
@FixForMultiProject(description = "resolve the actual projectId, ES-12176")
final var projectId = ProjectId.DEFAULT;
return repositoriesService.repositoryOrNull(projectId, repositoryName);
}
private static | IndexSnapshotsService |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/processor/internal/ReachabilityMetadata.java | {
"start": 6181,
"end": 7891
} | class ____ {
private final String type;
private final Collection<Method> methods = new TreeSet<>();
private final Collection<Field> fields = new TreeSet<>();
public Type(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void addMethod(Method method) {
methods.add(method);
}
public void addField(Field field) {
fields.add(field);
}
void toJson(MinimalJsonWriter jsonWriter) throws IOException {
jsonWriter.writeObjectStart();
jsonWriter.writeObjectKey(TYPE_NAME);
jsonWriter.writeString(type);
jsonWriter.writeSeparator();
boolean first = true;
jsonWriter.writeObjectKey(METHODS);
jsonWriter.writeArrayStart();
for (Method method : methods) {
if (!first) {
jsonWriter.writeSeparator();
}
first = false;
method.toJson(jsonWriter);
}
jsonWriter.writeArrayEnd();
jsonWriter.writeSeparator();
first = true;
jsonWriter.writeObjectKey(FIELDS);
jsonWriter.writeArrayStart();
for (Field field : fields) {
if (!first) {
jsonWriter.writeSeparator();
}
first = false;
field.toJson(jsonWriter);
}
jsonWriter.writeArrayEnd();
jsonWriter.writeObjectEnd();
}
}
/**
* Collection of reflection metadata.
*/
public static final | Type |
java | google__dagger | javatests/dagger/internal/codegen/ConflictingEntryPointsTest.java | {
"start": 4646,
"end": 4879
} | interface ____");
});
}
@Test
public void differentQualifier() {
Source base1 =
CompilerTests.javaSource(
"test.Base1", //
"package test;",
"",
" | TestComponent |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java | {
"start": 114424,
"end": 124248
} | class ____ {
// @Outgoing
@Outgoing("channel1")
Publisher<ProducerRecord<Double, java.nio.ByteBuffer>> method1() {
return null;
}
@Outgoing("channel3")
PublisherBuilder<ProducerRecord<Double, java.nio.ByteBuffer>> method3() {
return null;
}
@Outgoing("channel5")
Multi<ProducerRecord<Double, java.nio.ByteBuffer>> method5() {
return null;
}
@Outgoing("channel7")
ProducerRecord<Double, java.nio.ByteBuffer> method7() {
return null;
}
@Outgoing("channel9")
CompletionStage<ProducerRecord<Double, java.nio.ByteBuffer>> method9() {
return null;
}
@Outgoing("channel11")
Uni<ProducerRecord<Double, java.nio.ByteBuffer>> method11() {
return null;
}
// @Incoming
@Incoming("channel13")
Subscriber<ConsumerRecord<Integer, java.util.UUID>> method13() {
return null;
}
@Incoming("channel15")
SubscriberBuilder<ConsumerRecord<Integer, java.util.UUID>, Void> method15() {
return null;
}
@Incoming("channel18")
CompletionStage<?> method18(ConsumerRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel20")
Uni<?> method20(ConsumerRecord<Integer, java.util.UUID> msg) {
return null;
}
// @Incoming @Outgoing
@Incoming("channel22")
@Outgoing("channel23")
Processor<ConsumerRecord<Integer, java.util.UUID>, ProducerRecord<Double, java.nio.ByteBuffer>> method22() {
return null;
}
@Incoming("channel26")
@Outgoing("channel27")
ProcessorBuilder<ConsumerRecord<Integer, java.util.UUID>, ProducerRecord<Double, java.nio.ByteBuffer>> method24() {
return null;
}
@Incoming("channel30")
@Outgoing("channel31")
Publisher<ProducerRecord<Double, java.nio.ByteBuffer>> method26(ConsumerRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel34")
@Outgoing("channel35")
PublisherBuilder<ProducerRecord<Double, java.nio.ByteBuffer>> method28(ConsumerRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel38")
@Outgoing("channel39")
Multi<ProducerRecord<Double, java.nio.ByteBuffer>> method30(ConsumerRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel42")
@Outgoing("channel43")
ProducerRecord<Double, java.nio.ByteBuffer> method32(ConsumerRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel46")
@Outgoing("channel47")
CompletionStage<ProducerRecord<Double, java.nio.ByteBuffer>> method34(ConsumerRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel50")
@Outgoing("channel51")
Uni<ProducerRecord<Double, java.nio.ByteBuffer>> method36(ConsumerRecord<Integer, java.util.UUID> msg) {
return null;
}
// @Incoming @Outgoing stream manipulation
@Incoming("channel54")
@Outgoing("channel55")
Publisher<ProducerRecord<Double, java.nio.ByteBuffer>> method38(
Publisher<ConsumerRecord<Integer, java.util.UUID>> msg) {
return null;
}
@Incoming("channel58")
@Outgoing("channel59")
PublisherBuilder<ProducerRecord<Double, java.nio.ByteBuffer>> method40(
PublisherBuilder<ConsumerRecord<Integer, java.util.UUID>> msg) {
return null;
}
@Incoming("channel62")
@Outgoing("channel63")
Multi<ProducerRecord<Double, java.nio.ByteBuffer>> method42(Multi<ConsumerRecord<Integer, java.util.UUID>> msg) {
return null;
}
}
// ---
@Test
public void floatJsonArrayInShortByteArrayOut() {
// @formatter:off
Tuple[] expectations = {
tuple("mp.messaging.outgoing.channel1.value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"),
tuple("mp.messaging.outgoing.channel2.value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"),
tuple("mp.messaging.outgoing.channel3.key.serializer", "org.apache.kafka.common.serialization.ShortSerializer"),
tuple("mp.messaging.outgoing.channel3.value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"),
tuple("mp.messaging.outgoing.channel4.key.serializer", "org.apache.kafka.common.serialization.ShortSerializer"),
tuple("mp.messaging.outgoing.channel4.value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"),
tuple("mp.messaging.outgoing.channel5.key.serializer", "org.apache.kafka.common.serialization.ShortSerializer"),
tuple("mp.messaging.outgoing.channel5.value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"),
tuple("mp.messaging.outgoing.channel6.value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"),
tuple("mp.messaging.outgoing.channel7.value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"),
tuple("mp.messaging.outgoing.channel8.key.serializer", "org.apache.kafka.common.serialization.ShortSerializer"),
tuple("mp.messaging.outgoing.channel8.value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"),
tuple("mp.messaging.outgoing.channel9.key.serializer", "org.apache.kafka.common.serialization.ShortSerializer"),
tuple("mp.messaging.outgoing.channel9.value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"),
tuple("mp.messaging.outgoing.channel10.key.serializer", "org.apache.kafka.common.serialization.ShortSerializer"),
tuple("mp.messaging.outgoing.channel10.value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer"),
tuple("mp.messaging.incoming.channel11.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel12.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel13.key.deserializer", "org.apache.kafka.common.serialization.FloatDeserializer"),
tuple("mp.messaging.incoming.channel13.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel14.key.deserializer", "org.apache.kafka.common.serialization.FloatDeserializer"),
tuple("mp.messaging.incoming.channel14.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel15.key.deserializer", "org.apache.kafka.common.serialization.FloatDeserializer"),
tuple("mp.messaging.incoming.channel15.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel16.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel17.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel18.key.deserializer", "org.apache.kafka.common.serialization.FloatDeserializer"),
tuple("mp.messaging.incoming.channel18.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel19.key.deserializer", "org.apache.kafka.common.serialization.FloatDeserializer"),
tuple("mp.messaging.incoming.channel19.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel20.key.deserializer", "org.apache.kafka.common.serialization.FloatDeserializer"),
tuple("mp.messaging.incoming.channel20.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel21.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel22.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel23.key.deserializer", "org.apache.kafka.common.serialization.FloatDeserializer"),
tuple("mp.messaging.incoming.channel23.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel24.key.deserializer", "org.apache.kafka.common.serialization.FloatDeserializer"),
tuple("mp.messaging.incoming.channel24.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
tuple("mp.messaging.incoming.channel25.key.deserializer", "org.apache.kafka.common.serialization.FloatDeserializer"),
tuple("mp.messaging.incoming.channel25.value.deserializer", "io.quarkus.kafka.client.serialization.JsonArrayDeserializer"),
};
// @formatter:on
doTest(expectations, FloatJsonArrayInShortByteArrayOut.class);
}
private static | ConsumerRecordIntUuidInProducerRecordDoubleByteBufferOut |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/not_null_column/Base.java | {
"start": 744,
"end": 1137
} | class ____ {
private int tempIntField;
private Date tempDateField;
public int getTempIntField() {
return tempIntField;
}
public void setTempIntField(int tempIntField) {
this.tempIntField = tempIntField;
}
public Date getTempDateField() {
return tempDateField;
}
public void setTempDateField(Date tempDateField) {
this.tempDateField = tempDateField;
}
}
| Base |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/api/impl/pb/client/LocalizationProtocolPBClientImpl.java | {
"start": 1890,
"end": 2899
} | class ____ implements LocalizationProtocol,
Closeable {
private LocalizationProtocolPB proxy;
public LocalizationProtocolPBClientImpl(long clientVersion, InetSocketAddress addr, Configuration conf) throws IOException {
RPC.setProtocolEngine(conf, LocalizationProtocolPB.class,
ProtobufRpcEngine2.class);
proxy = (LocalizationProtocolPB)RPC.getProxy(
LocalizationProtocolPB.class, clientVersion, addr, conf);
}
@Override
public void close() {
if (this.proxy != null) {
RPC.stopProxy(this.proxy);
}
}
@Override
public LocalizerHeartbeatResponse heartbeat(LocalizerStatus status)
throws YarnException, IOException {
LocalizerStatusProto statusProto = ((LocalizerStatusPBImpl)status).getProto();
try {
return new LocalizerHeartbeatResponsePBImpl(
proxy.heartbeat(null, statusProto));
} catch (ServiceException e) {
RPCUtil.unwrapAndThrowException(e);
return null;
}
}
}
| LocalizationProtocolPBClientImpl |
java | quarkusio__quarkus | extensions/kubernetes-client/runtime/src/test/java/io/quarkus/kubernetes/client/runtime/KubernetesClientUtilsTest.java | {
"start": 382,
"end": 1452
} | class ____ {
@BeforeEach
public void setUp() {
System.getProperties().remove(Config.KUBERNETES_TRUST_CERT_SYSTEM_PROPERTY);
System.getProperties().remove(Config.KUBERNETES_DISABLE_HOSTNAME_VERIFICATION_SYSTEM_PROPERTY);
System.getProperties().remove(Config.KUBERNETES_KUBECONFIG_FILE);
}
@Test
void shouldGetConfigWithTrustCerts() throws Exception {
System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE,
new File(getClass().getResource("/test-kubeconfig").toURI()).getAbsolutePath());
Config config = Config.autoConfigure(null);
assertTrue(config.isTrustCerts());
}
@Test
void shouldGetClientWithTrustCerts() throws Exception {
System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE,
new File(getClass().getResource("/test-kubeconfig").toURI()).getAbsolutePath());
try (KubernetesClient client = KubernetesClientUtils.createClient()) {
assertTrue(client.getConfiguration().isTrustCerts());
}
}
}
| KubernetesClientUtilsTest |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapter.java | {
"start": 7228,
"end": 7288
} | class ____ as ThreadLocal value.
*/
private static final | used |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/method/configuration/MethodSecurityService.java | {
"start": 8432,
"end": 9570
} | class ____ implements MethodAuthorizationDeniedHandler {
MaskValueResolver maskValueResolver;
MaskAnnotationPostProcessor(ApplicationContext context) {
this.maskValueResolver = new MaskValueResolver(context);
}
@Override
public Object handleDeniedInvocation(MethodInvocation mi, AuthorizationResult authorizationResult) {
Mask mask = AnnotationUtils.getAnnotation(mi.getMethod(), Mask.class);
if (mask == null) {
mask = AnnotationUtils.getAnnotation(mi.getMethod().getDeclaringClass(), Mask.class);
}
return this.maskValueResolver.resolveValue(mask, mi, null);
}
@Override
public Object handleDeniedInvocationResult(MethodInvocationResult methodInvocationResult,
AuthorizationResult authorizationResult) {
MethodInvocation mi = methodInvocationResult.getMethodInvocation();
Mask mask = AnnotationUtils.getAnnotation(mi.getMethod(), Mask.class);
if (mask == null) {
mask = AnnotationUtils.getAnnotation(mi.getMethod().getDeclaringClass(), Mask.class);
}
return this.maskValueResolver.resolveValue(mask, mi, methodInvocationResult.getResult());
}
}
| MaskAnnotationPostProcessor |
java | elastic__elasticsearch | x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/integration/DataStreamLifecycleServiceRuntimeSecurityIT.java | {
"start": 17164,
"end": 20225
} | class ____ extends Plugin implements SystemIndexPlugin {
static final String SYSTEM_DATA_STREAM_NAME = ".fleet-actions-results";
@Override
public Collection<SystemDataStreamDescriptor> getSystemDataStreamDescriptors() {
try {
return List.of(
new SystemDataStreamDescriptor(
SYSTEM_DATA_STREAM_NAME,
"a system data stream for testing",
SystemDataStreamDescriptor.Type.EXTERNAL,
ComposableIndexTemplate.builder()
.indexPatterns(List.of(SYSTEM_DATA_STREAM_NAME))
.template(
Template.builder()
.mappings(new CompressedXContent("""
{
"properties": {
"@timestamp" : {
"type": "date"
},
"count": {
"type": "long"
}
}
}"""))
.lifecycle(DataStreamLifecycle.dataLifecycleBuilder().dataRetention(TimeValue.ZERO))
.dataStreamOptions(
new DataStreamOptions.Template(
new DataStreamFailureStore.Template(
true,
DataStreamLifecycle.failuresLifecycleBuilder().dataRetention(TimeValue.ZERO).buildTemplate()
)
)
)
)
.dataStreamTemplate(new ComposableIndexTemplate.DataStreamTemplate())
.build(),
Map.of(),
Collections.singletonList("test"),
"test",
new ExecutorNames(
ThreadPool.Names.SYSTEM_CRITICAL_READ,
ThreadPool.Names.SYSTEM_READ,
ThreadPool.Names.SYSTEM_WRITE
)
)
);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public String getFeatureName() {
return SystemDataStreamTestPlugin.class.getSimpleName();
}
@Override
public String getFeatureDescription() {
return "A plugin for testing the data stream lifecycle runtime actions on system data streams";
}
}
}
| SystemDataStreamTestPlugin |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inject/guice/OverridesGuiceInjectableMethodTest.java | {
"start": 2347,
"end": 2443
} | class ____ not contain an error,
* but it is extended in the next test class.
*/
public | does |
java | apache__camel | components/camel-infinispan/camel-infinispan-common/src/main/java/org/apache/camel/component/infinispan/cluster/InfinispanClusterView.java | {
"start": 1181,
"end": 1658
} | class ____ extends AbstractCamelClusterView {
private static final Logger LOGGER = LoggerFactory.getLogger(InfinispanClusterView.class);
protected InfinispanClusterView(CamelClusterService cluster, String namespace) {
super(cluster, namespace);
}
protected abstract boolean isLeader(String id);
// ***********************************************
//
// ***********************************************
protected final | InfinispanClusterView |
java | quarkusio__quarkus | integration-tests/spring-boot-properties/src/test/java/io/quarkus/it/spring/boot/DefaultPropertiesTest.java | {
"start": 261,
"end": 459
} | class ____ {
@Test
void shouldGetDefaultValue() {
when().get("/default/value")
.then()
.body(is(equalTo("default-value")));
}
}
| DefaultPropertiesTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/pool/ha/node/ZookeeperNodeRegisterTest.java | {
"start": 622,
"end": 3970
} | class ____ {
private static final Log LOG = LogFactory.getLog(ZookeeperNodeRegisterTest.class);
private static TestingServer server;
private final String PATH = "/ha-druid-datasource";
private ZookeeperNodeRegister register;
@BeforeClass
public static void init() throws Exception {
server = new TestingServer();
}
@AfterClass
public static void destroy() throws Exception {
server.close();
}
@Before
public void setUp() throws Exception {
register = new ZookeeperNodeRegister();
register.setZkConnectString(server.getConnectString());
register.setPath(PATH);
register.init();
}
@After
public void tearDown() throws Exception {
register.destroy();
register.getClient().close();
}
@Test
public void testRegister() throws Exception {
List<ZookeeperNodeInfo> payload = new ArrayList<ZookeeperNodeInfo>();
ZookeeperNodeInfo node1 = new ZookeeperNodeInfo();
node1.setPrefix("foo");
node1.setHost("127.0.0.1");
node1.setPort(1234);
node1.setDatabase("foo_db");
node1.setUsername("foo");
node1.setPassword("password");
payload.add(node1);
ZookeeperNodeInfo node2 = new ZookeeperNodeInfo();
node2.setPrefix("bar");
node2.setHost("127.0.0.1");
node2.setPort(5678);
node2.setUsername("bar");
node2.setPassword("password");
payload.add(node2);
assertFalse(register.register("test-foo", null));
assertTrue(register.register("test-foo", payload));
assertFalse(register.register("test-foo", payload));
Thread.sleep(1000); // Wait for the node to be created.
CuratorFramework client = register.getClient();
List<String> children = client.getChildren().forPath(PATH);
assertFalse(children.isEmpty());
assertEquals(1, children.size());
assertEquals("test-foo", children.get(0));
byte[] bytes = client.getData().forPath(PATH + "/test-foo");
Properties properties = new Properties();
String str = new String(bytes);
LOG.info("ZK Data: " + str);
properties.load(new StringReader(str));
validateNodeProperties(node1, properties);
validateNodeProperties(node2, properties);
assertTrue(properties.containsKey("foo.database"));
assertFalse(properties.containsKey("bar.database"));
assertEquals("foo_db", properties.getProperty("foo.database"));
}
private void validateNodeProperties(ZookeeperNodeInfo node, Properties properties) {
assertTrue(properties.containsKey(node.getPrefix() + "host"));
assertTrue(properties.containsKey(node.getPrefix() + "port"));
assertTrue(properties.containsKey(node.getPrefix() + "username"));
assertTrue(properties.containsKey(node.getPrefix() + "password"));
assertEquals(node.getHost(), properties.getProperty(node.getPrefix() + "host"));
assertEquals(node.getPort().toString(), properties.getProperty(node.getPrefix() + "port"));
assertEquals(node.getUsername(), properties.getProperty(node.getPrefix() + "username"));
assertEquals(node.getPassword(), properties.getProperty(node.getPrefix() + "password"));
}
}
| ZookeeperNodeRegisterTest |
java | processing__processing4 | core/src/processing/core/PApplet.java | {
"start": 336557,
"end": 338781
} | class ____ load (with package if any)
* @param sketchArgs command line arguments to pass to the sketch's 'args'
* array. Note that this is <i>not</i> the same as the args passed
* to (and understood by) PApplet such as --display.
*/
static public void main(final String mainClass, final String[] sketchArgs) {
String[] args = new String[] { mainClass };
if (sketchArgs != null) {
args = concat(args, sketchArgs);
}
runSketch(args, null);
}
// Moving this back off the EDT for 3.0 alpha 10. Not sure if we're helping
// or hurting, but unless we do, errors inside settings() are never passed
// through to the PDE. There are other ways around that, no doubt, but I'm
// also suspecting that these "not showing up" bugs might be EDT issues.
static public void runSketch(final String[] args,
final PApplet constructedSketch) {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
e.printStackTrace();
uncaughtThrowable = e;
});
// This doesn't work, need to mess with Info.plist instead
/*
// In an exported application, add the Contents/Java folder to the
// java.library.path, so that native libraries work properly.
// Without this, the library path is only set to Contents/MacOS
// where the launcher binary lives.
if (platform == MACOSX) {
URL coreJarURL =
PApplet.class.getProtectionDomain().getCodeSource().getLocation();
// The jarPath from above will/may be URL encoded (%20 for spaces)
String coreJarPath = urlDecode(coreJarURL.getPath());
if (coreJarPath.endsWith("/Contents/Java/core.jar")) {
// remove the /core.jar part from the end
String javaPath = coreJarPath.substring(0, coreJarPath.length() - 9);
String libraryPath = System.getProperty("java.library.path");
libraryPath += File.pathSeparator + javaPath;
System.setProperty("java.library.path", libraryPath);
}
}
*/
// So that the system proxy setting are used by default
System.setProperty("java.net.useSystemProxies", "true");
if (args.length < 1) {
System.err.println("Usage: PApplet [options] < | to |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/AllLongDoubleState.java | {
"start": 855,
"end": 2375
} | class ____ implements AggregatorState {
// the timestamp
private long v1;
// the value
private double v2;
// whether we've seen a first/last timestamp
private boolean seen;
// because we might observe a first/last timestamp without observing a value (e.g.: value was null)
private boolean v2Seen;
AllLongDoubleState(long v1, double v2) {
this.v1 = v1;
this.v2 = v2;
}
long v1() {
return v1;
}
void v1(long v1) {
this.v1 = v1;
}
double v2() {
return v2;
}
void v2(double v2) {
this.v2 = v2;
}
boolean seen() {
return seen;
}
void seen(boolean seen) {
this.seen = seen;
}
boolean v2Seen() {
return v2Seen;
}
void v2Seen(boolean v2Seen) {
this.v2Seen = v2Seen;
}
/** Extracts an intermediate view of the contents of this state. */
@Override
public void toIntermediate(Block[] blocks, int offset, DriverContext driverContext) {
assert blocks.length >= offset + 4;
blocks[offset + 0] = driverContext.blockFactory().newConstantLongBlockWith(v1, 1);
blocks[offset + 1] = driverContext.blockFactory().newConstantDoubleBlockWith(v2, 1);
blocks[offset + 2] = driverContext.blockFactory().newConstantBooleanBlockWith(seen, 1);
blocks[offset + 3] = driverContext.blockFactory().newConstantBooleanBlockWith(v2Seen, 1);
}
@Override
public void close() {}
}
| AllLongDoubleState |
java | square__retrofit | retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java | {
"start": 50118,
"end": 50619
} | class ____ {
@GET
Call<ResponseBody> method(@Url URI url) {
return null;
}
}
Request request = buildRequest(Example.class, URI.create("https://example2.com/foo/bar/"));
assertThat(request.method()).isEqualTo("GET");
assertThat(request.headers().size()).isEqualTo(0);
assertThat(request.url().toString()).isEqualTo("https://example2.com/foo/bar/");
assertThat(request.body()).isNull();
}
@Test
public void getWithUrlAbsoluteSameHost() {
| Example |
java | quarkusio__quarkus | extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/i18n/MessageBundleExpressionValidationTest.java | {
"start": 2189,
"end": 2495
} | interface ____ {
// item has no "foo" property, "bar" and "baf" are not parameters, string has no "baz" property
@Message("Hello {item.foo} {bar} {#each item.names}{it}{it.baz}{it_hasNext}{baf}{/each}{level}")
String hello(Item item);
}
@TemplateGlobal
static | WrongBundle |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/server/UnsupportedMediaTypeStatusException.java | {
"start": 1252,
"end": 5458
} | class ____ extends ResponseStatusException {
private static final String PARSE_ERROR_DETAIL_CODE =
ErrorResponse.getDefaultDetailMessageCode(UnsupportedMediaTypeStatusException.class, "parseError");
private final @Nullable MediaType contentType;
private final List<MediaType> supportedMediaTypes;
private final @Nullable ResolvableType bodyType;
private final @Nullable HttpMethod method;
/**
* Constructor for when the specified Content-Type is invalid.
*/
public UnsupportedMediaTypeStatusException(@Nullable String reason) {
this(reason, Collections.emptyList());
}
/**
* Constructor for when the specified Content-Type is invalid.
* @since 6.0.5
*/
public UnsupportedMediaTypeStatusException(@Nullable String reason, List<MediaType> supportedTypes) {
super(HttpStatus.UNSUPPORTED_MEDIA_TYPE, reason, null, PARSE_ERROR_DETAIL_CODE, null);
this.contentType = null;
this.supportedMediaTypes = Collections.unmodifiableList(supportedTypes);
this.bodyType = null;
this.method = null;
setDetail("Could not parse Content-Type.");
}
/**
* Constructor for when the Content-Type can be parsed but is not supported.
*/
public UnsupportedMediaTypeStatusException(@Nullable MediaType contentType, List<MediaType> supportedTypes) {
this(contentType, supportedTypes, null, null);
}
/**
* Constructor for when trying to encode from or decode to a specific Java type.
* @since 5.1
*/
public UnsupportedMediaTypeStatusException(@Nullable MediaType contentType, List<MediaType> supportedTypes,
@Nullable ResolvableType bodyType) {
this(contentType, supportedTypes, bodyType, null);
}
/**
* Constructor that provides the HTTP method.
* @since 5.3.6
*/
public UnsupportedMediaTypeStatusException(@Nullable MediaType contentType, List<MediaType> supportedTypes,
@Nullable HttpMethod method) {
this(contentType, supportedTypes, null, method);
}
/**
* Constructor for when trying to encode from or decode to a specific Java type.
* @since 5.3.6
*/
public UnsupportedMediaTypeStatusException(@Nullable MediaType contentType, List<MediaType> supportedTypes,
@Nullable ResolvableType bodyType, @Nullable HttpMethod method) {
super(HttpStatus.UNSUPPORTED_MEDIA_TYPE, initMessage(contentType, bodyType),
null, null, new Object[] {contentType, supportedTypes});
this.contentType = contentType;
this.supportedMediaTypes = Collections.unmodifiableList(supportedTypes);
this.bodyType = bodyType;
this.method = method;
setDetail(contentType != null ? "Content-Type '" + contentType + "' is not supported." : null);
}
private static String initMessage(@Nullable MediaType contentType, @Nullable ResolvableType bodyType) {
return "Content type '" + (contentType != null ? contentType : "") + "' not supported" +
(bodyType != null ? " for bodyType=" + bodyType : "");
}
/**
* Return the request Content-Type header if it was parsed successfully,
* or {@code null} otherwise.
*/
public @Nullable MediaType getContentType() {
return this.contentType;
}
/**
* Return the list of supported content types in cases when the Content-Type
* header is parsed but not supported, or an empty list otherwise.
*/
public List<MediaType> getSupportedMediaTypes() {
return this.supportedMediaTypes;
}
/**
* Return the body type in the context of which this exception was generated.
* <p>This is applicable when the exception was raised as a result trying to
* encode from or decode to a specific Java type.
* @return the body type, or {@code null} if not available
* @since 5.1
*/
public @Nullable ResolvableType getBodyType() {
return this.bodyType;
}
/**
* Return HttpHeaders with an "Accept" header that documents the supported
* media types, if available, or an empty instance otherwise.
*/
@Override
public HttpHeaders getHeaders() {
if (CollectionUtils.isEmpty(this.supportedMediaTypes) ) {
return HttpHeaders.EMPTY;
}
HttpHeaders headers = new HttpHeaders();
headers.setAccept(this.supportedMediaTypes);
if (this.method == HttpMethod.PATCH) {
headers.setAcceptPatch(this.supportedMediaTypes);
}
return headers;
}
}
| UnsupportedMediaTypeStatusException |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/handlers/AdvancedRedirectHandler.java | {
"start": 417,
"end": 659
} | interface ____ {
/**
* Allows code to set every aspect of the redirect request
*/
RequestOptions handle(Context context);
record Context(Response jaxRsResponse, HttpClientRequest request) {
}
}
| AdvancedRedirectHandler |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/webapp/AppController.java | {
"start": 1945,
"end": 2015
} | class ____ the various pages that the web app supports.
*/
public | renders |
java | quarkusio__quarkus | extensions/oidc-token-propagation/deployment/src/main/java/io/quarkus/oidc/token/propagation/deployment/OidcTokenPropagationAlwaysEnabledProcessor.java | {
"start": 310,
"end": 513
} | class ____ {
@BuildStep
FeatureBuildItem featureBuildItem() {
return new FeatureBuildItem(Feature.RESTEASY_CLIENT_OIDC_TOKEN_PROPAGATION);
}
}
| OidcTokenPropagationAlwaysEnabledProcessor |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestServletFilter.java | {
"start": 2457,
"end": 4716
} | class ____ extends FilterInitializer {
public Initializer() {}
@Override
public void initFilter(FilterContainer container, Configuration conf) {
container.addFilter("simple", SimpleFilter.class.getName(), null);
}
}
}
/** access a url, ignoring some IOException such as the page does not exist */
static void access(String urlstring) throws IOException {
LOG.warn("access " + urlstring);
URL url = new URL(urlstring);
URLConnection connection = url.openConnection();
connection.connect();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
try {
for(; in.readLine() != null; );
} finally {
in.close();
}
} catch(IOException ioe) {
LOG.warn("urlstring=" + urlstring, ioe);
}
}
public void testServletFilter() throws Exception {
Configuration conf = new Configuration();
//start a http server with CountingFilter
conf.set(HttpServer2.FILTER_INITIALIZER_PROPERTY,
SimpleFilter.Initializer.class.getName());
HttpServer2 http = createTestServer(conf);
http.start();
final String fsckURL = "/fsck";
final String stacksURL = "/stacks";
final String ajspURL = "/a.jsp";
final String logURL = "/logs/a.log";
final String hadooplogoURL = "/static/hadoop-logo.jpg";
final String[] urls = {fsckURL, stacksURL, ajspURL, logURL, hadooplogoURL};
final Random ran = new Random();
final int[] sequence = new int[50];
//generate a random sequence and update counts
for(int i = 0; i < sequence.length; i++) {
sequence[i] = ran.nextInt(urls.length);
}
//access the urls as the sequence
final String prefix = "http://"
+ NetUtils.getHostPortString(http.getConnectorAddress(0));
try {
for(int i = 0; i < sequence.length; i++) {
access(prefix + urls[sequence[i]]);
//make sure everything except fsck get filtered
if (sequence[i] == 0) {
assertEquals(null, uri);
} else {
assertEquals(urls[sequence[i]], uri);
uri = null;
}
}
} finally {
http.stop();
}
}
static public | Initializer |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/support/ContextLoaderUtils.java | {
"start": 8007,
"end": 8431
} | class ____), keyed by the
* {@link ContextConfiguration#name() name} of the context hierarchy level.
* <p>If a given level in the context hierarchy does not have an explicit
* name (i.e., configured via {@link ContextConfiguration#name}), a name will
* be generated for that hierarchy level by appending the numerical level to
* the {@link #GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX}.
* @param testClass the | hierarchy |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/string/ReverseSerializationTests.java | {
"start": 539,
"end": 757
} | class ____ extends AbstractUnaryScalarSerializationTests<Reverse> {
@Override
protected Reverse create(Source source, Expression child) {
return new Reverse(source, child);
}
}
| ReverseSerializationTests |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/SecurityHttpSettingsTests.java | {
"start": 552,
"end": 1934
} | class ____ extends ESTestCase {
public void testDisablesCompressionByDefaultForSsl() {
Settings settings = Settings.builder().put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true).build();
Settings.Builder pluginSettingsBuilder = Settings.builder();
SecurityHttpSettings.overrideSettings(pluginSettingsBuilder, settings);
assertThat(HttpTransportSettings.SETTING_HTTP_COMPRESSION.get(pluginSettingsBuilder.build()), is(false));
}
public void testLeavesCompressionOnIfNotSsl() {
Settings settings = Settings.builder().put(XPackSettings.HTTP_SSL_ENABLED.getKey(), false).build();
Settings.Builder pluginSettingsBuilder = Settings.builder();
SecurityHttpSettings.overrideSettings(pluginSettingsBuilder, settings);
assertThat(pluginSettingsBuilder.build().isEmpty(), is(true));
}
public void testDoesNotChangeExplicitlySetCompression() {
Settings settings = Settings.builder()
.put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true)
.put(HttpTransportSettings.SETTING_HTTP_COMPRESSION.getKey(), true)
.build();
Settings.Builder pluginSettingsBuilder = Settings.builder();
SecurityHttpSettings.overrideSettings(pluginSettingsBuilder, settings);
assertThat(pluginSettingsBuilder.build().isEmpty(), is(true));
}
}
| SecurityHttpSettingsTests |
java | google__guice | core/src/com/google/inject/matcher/Matchers.java | {
"start": 12565,
"end": 13332
} | class ____<T> extends AbstractMatcher<T> implements Serializable {
private final Matcher<? super T> a, b;
public OrMatcher(Matcher<? super T> a, Matcher<? super T> b) {
this.a = a;
this.b = b;
}
@Override
public boolean matches(T t) {
return a.matches(t) || b.matches(t);
}
@Override
public boolean equals(Object other) {
return other instanceof OrMatcher
&& ((OrMatcher) other).a.equals(a)
&& ((OrMatcher) other).b.equals(b);
}
@Override
public int hashCode() {
return 37 * (a.hashCode() ^ b.hashCode());
}
@Override
public String toString() {
return "or(" + a + ", " + b + ")";
}
private static final long serialVersionUID = 0;
}
}
| OrMatcher |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/filter/factory/SetRequestUriGatewayFilterFactoryTests.java | {
"start": 1433,
"end": 3785
} | class ____ {
@Test
public void filterChangeRequestUri() {
SetRequestUriGatewayFilterFactory factory = new SetRequestUriGatewayFilterFactory();
GatewayFilter filter = factory.apply(c -> c.setTemplate("https://example.com"));
MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost").build();
ServerWebExchange exchange = MockServerWebExchange.from(request);
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, URI.create("http://localhost"));
GatewayFilterChain filterChain = mock(GatewayFilterChain.class);
ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor.forClass(ServerWebExchange.class);
when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());
filter.filter(exchange, filterChain);
ServerWebExchange webExchange = captor.getValue();
URI uri = (URI) webExchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR);
assertThat(uri).isNotNull();
assertThat(uri.toString()).isEqualTo("https://example.com");
}
@Test
public void filterDoesNotChangeRequestUriIfUriIsInvalid() throws Exception {
SetRequestUriGatewayFilterFactory factory = new SetRequestUriGatewayFilterFactory();
GatewayFilter filter = factory.apply(c -> c.setTemplate("invalid_uri"));
MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost").build();
ServerWebExchange exchange = MockServerWebExchange.from(request);
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, URI.create("http://localhost"));
GatewayFilterChain filterChain = mock(GatewayFilterChain.class);
ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor.forClass(ServerWebExchange.class);
when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());
filter.filter(exchange, filterChain);
ServerWebExchange webExchange = captor.getValue();
URI uri = (URI) webExchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR);
assertThat(uri).isNotNull();
assertThat(uri.toURL().toString()).isEqualTo("http://localhost");
}
@Test
public void toStringFormat() {
SetRequestUriGatewayFilterFactory.Config config = new SetRequestUriGatewayFilterFactory.Config();
config.setTemplate("http://localhost:8080");
GatewayFilter filter = new SetRequestUriGatewayFilterFactory().apply(config);
assertThat(filter.toString()).contains("http://localhost:8080");
}
}
| SetRequestUriGatewayFilterFactoryTests |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/bootstrap/BootstrapChecks.java | {
"start": 21610,
"end": 22717
} | class ____ implements BootstrapCheck {
@Override
public BootstrapCheckResult check(BootstrapContext context) {
if (getVmName().toLowerCase(Locale.ROOT).contains("client")) {
final String message = String.format(
Locale.ROOT,
"JVM is using the client VM [%s] but should be using a server VM for the best performance",
getVmName()
);
return BootstrapCheckResult.failure(message);
} else {
return BootstrapCheckResult.success();
}
}
// visible for testing
String getVmName() {
return JvmInfo.jvmInfo().getVmName();
}
@Override
public ReferenceDocs referenceDocs() {
return ReferenceDocs.BOOTSTRAP_CHECK_CLIENT_JVM;
}
}
/**
* Checks if the serial collector is in use. This collector is single-threaded and devastating
* for performance and should not be used for a server application like Elasticsearch.
*/
static | ClientJvmCheck |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerStateTransitionListener.java | {
"start": 1901,
"end": 2204
} | interface ____ extends
StateTransitionListener<ContainerImpl, ContainerEvent, ContainerState> {
/**
* Init method which will be invoked by the Node Manager to inject the
* NM {@link Context}.
* @param context NM Context.
*/
void init(Context context);
}
| ContainerStateTransitionListener |
java | junit-team__junit5 | junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/MethodSelector.java | {
"start": 7117,
"end": 8040
} | class ____ for each parameter
* type based on its name and throws a {@link JUnitException} if the class
* cannot be loaded.
*
* @return the method's parameter types; never {@code null} but potentially
* an empty array if the selected method does not declare parameters
* @since 1.10
* @see #getParameterTypeNames()
* @see Method#getParameterTypes()
*/
@API(status = MAINTAINED, since = "1.13.3")
public Class<?>[] getParameterTypes() {
return lazyLoadParameterTypes().clone();
}
private Class<?> lazyLoadJavaClass() {
Class<?> value = this.javaClass;
if (value == null) {
// @formatter:off
Try<Class<?>> tryToLoadClass = this.classLoader == null
? ReflectionSupport.tryToLoadClass(this.className)
: ReflectionSupport.tryToLoadClass(this.className, this.classLoader);
value = tryToLoadClass.getNonNullOrThrow(cause ->
new PreconditionViolationException("Could not load | reference |
java | spring-projects__spring-boot | module/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/autoconfigure/KafkaProperties.java | {
"start": 19048,
"end": 21708
} | class ____ {
private final Ssl ssl = new Ssl();
private final Security security = new Security();
/**
* ID to pass to the server when making requests. Used for server-side logging.
*/
private @Nullable String clientId;
/**
* Additional admin-specific properties used to configure the client.
*/
private final Map<String, String> properties = new HashMap<>();
/**
* Close timeout.
*/
private @Nullable Duration closeTimeout;
/**
* Operation timeout.
*/
private @Nullable Duration operationTimeout;
/**
* Whether to fail fast if the broker is not available on startup.
*/
private boolean failFast;
/**
* Whether to enable modification of existing topic configuration.
*/
private boolean modifyTopicConfigs;
/**
* Whether to automatically create topics during context initialization. When set
* to false, disables automatic topic creation during context initialization.
*/
private boolean autoCreate = true;
public Ssl getSsl() {
return this.ssl;
}
public Security getSecurity() {
return this.security;
}
public @Nullable String getClientId() {
return this.clientId;
}
public void setClientId(@Nullable String clientId) {
this.clientId = clientId;
}
public @Nullable Duration getCloseTimeout() {
return this.closeTimeout;
}
public void setCloseTimeout(@Nullable Duration closeTimeout) {
this.closeTimeout = closeTimeout;
}
public @Nullable Duration getOperationTimeout() {
return this.operationTimeout;
}
public void setOperationTimeout(@Nullable Duration operationTimeout) {
this.operationTimeout = operationTimeout;
}
public boolean isFailFast() {
return this.failFast;
}
public void setFailFast(boolean failFast) {
this.failFast = failFast;
}
public boolean isModifyTopicConfigs() {
return this.modifyTopicConfigs;
}
public void setModifyTopicConfigs(boolean modifyTopicConfigs) {
this.modifyTopicConfigs = modifyTopicConfigs;
}
public boolean isAutoCreate() {
return this.autoCreate;
}
public void setAutoCreate(boolean autoCreate) {
this.autoCreate = autoCreate;
}
public Map<String, String> getProperties() {
return this.properties;
}
public Map<String, Object> buildProperties() {
Properties properties = new Properties();
PropertyMapper map = PropertyMapper.get();
map.from(this::getClientId).to(properties.in(ProducerConfig.CLIENT_ID_CONFIG));
return properties.with(this.ssl, this.security, this.properties);
}
}
/**
* High (and some medium) priority Streams properties and a general properties bucket.
*/
public static | Admin |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/metrics/DescriptiveStatisticsHistogramStatistics.java | {
"start": 1775,
"end": 3445
} | class ____ extends HistogramStatistics
implements Serializable {
private static final long serialVersionUID = 1L;
private final CommonMetricsSnapshot statisticsSummary = new CommonMetricsSnapshot();
public DescriptiveStatisticsHistogramStatistics(
DescriptiveStatisticsHistogram.CircularDoubleArray histogramValues) {
this(histogramValues.toUnsortedArray());
}
public DescriptiveStatisticsHistogramStatistics(final double[] values) {
statisticsSummary.evaluate(values);
}
@Override
public double getQuantile(double quantile) {
return statisticsSummary.getPercentile(quantile * 100);
}
@Override
public long[] getValues() {
return Arrays.stream(statisticsSummary.getValues()).mapToLong(i -> (long) i).toArray();
}
@Override
public int size() {
return (int) statisticsSummary.getCount();
}
@Override
public double getMean() {
return statisticsSummary.getMean();
}
@Override
public double getStdDev() {
return statisticsSummary.getStandardDeviation();
}
@Override
public long getMax() {
return (long) statisticsSummary.getMax();
}
@Override
public long getMin() {
return (long) statisticsSummary.getMin();
}
/**
* Function to extract several commonly used metrics in an optimised way, i.e. with as few runs
* over the data / calculations as possible.
*
* <p>Note that calls to {@link #evaluate(double[])} or {@link #evaluate(double[], int, int)}
* will not return a value but instead populate this | DescriptiveStatisticsHistogramStatistics |
java | quarkusio__quarkus | docs/src/test/java/io/quarkus/docs/vale/ValeAsciidocLint.java | {
"start": 1708,
"end": 9156
} | class ____ {
public static TypeReference<Map<String, List<Check>>> typeRef = new TypeReference<Map<String, List<Check>>>() {
};
String imageName;
AlertLevel minAlertLevel;
Predicate<String> fileFilterPattern;
Path valeDir;
Path srcDir;
Path targetDir;
Path valeConfigFile;
public static void main(String[] args) throws Exception {
if (args == null) {
args = new String[0];
}
ValeAsciidocLint linter = new ValeAsciidocLint()
.setValeAlertLevel(System.getProperty("valeLevel"))
.setValeImageName(System.getProperty("vale.image"))
.setValeDir(args.length >= 1
? Path.of(args[0])
: docsDir().resolve(".vale"))
.setSrcDir(args.length >= 2
? Path.of(args[1])
: docsDir().resolve("src/main/asciidoc"))
.setTargetDir(args.length >= 3
? Path.of(args[2])
: docsDir().resolve("target"))
.setValeConfig(args.length >= 4
? Path.of(args[0])
: docsDir().resolve(".vale.ini"));
Map<String, ChecksBySeverity> results = linter.lintFiles();
linter.resultsToYaml(results, null);
}
public ValeAsciidocLint setValeImageName(String imageName) {
this.imageName = imageName;
return this;
}
public ValeAsciidocLint setValeAlertLevel(String valeLevel) {
this.minAlertLevel = AlertLevel.from(valeLevel);
return this;
}
public ValeAsciidocLint setValeDir(Path valeDir) {
this.valeDir = valeDir;
return this;
}
public ValeAsciidocLint setValeConfig(Path valeConfig) {
this.valeConfigFile = valeConfig;
return this;
}
public ValeAsciidocLint setSrcDir(Path srcDir) {
this.srcDir = srcDir;
return this;
}
public ValeAsciidocLint setTargetDir(Path targetDir) {
this.targetDir = targetDir;
return this;
}
public ValeAsciidocLint setFileFilterPattern(String filter) {
if (filter == null || filter.isBlank() || "true".equals(filter)) {
return this;
}
fileFilterPattern = Pattern.compile(filter).asPredicate();
return this;
}
public ValeAsciidocLint setFileList(final Collection<String> fileNames) {
if (fileNames != null && !fileNames.isEmpty()) {
fileFilterPattern = new Predicate<String>() {
@Override
public boolean test(String p) {
return fileNames.contains(p);
}
};
}
return this;
}
public void resultsToYaml(Map<String, ChecksBySeverity> lintChecks, Map<String, FileMessages> metadataErrors)
throws StreamWriteException, DatabindException, IOException {
ObjectMapper yaml = new ObjectMapper(new YAMLFactory().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES));
Map<String, Map<String, Object>> results = lintChecks.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(), e -> {
Map<String, Object> value = new TreeMap<>(); // sort by key for consistency
value.putAll(e.getValue().checksBySeverity);
if (metadataErrors != null) {
FileMessages fm = metadataErrors.get(e.getKey());
if (fm != null) {
value.put("metadata", fm);
}
}
return value;
}));
yaml.writeValue(targetDir.resolve("vale.yaml").toFile(), results);
}
public Map<String, ChecksBySeverity> lintFiles() throws Exception {
if (imageName == null) {
throw new IllegalStateException(
String.format("Vale image not specified (vale.image system property not found)"));
}
if (!Files.exists(valeDir) || !Files.isDirectory(valeDir)) {
throw new IllegalStateException(
String.format("Vale config directory (%s) does not exist", valeDir.toAbsolutePath()));
}
if (!Files.exists(srcDir) || !Files.isDirectory(srcDir)) {
throw new IllegalStateException(
String.format("Source directory (%s) does not exist. Exiting.%n", srcDir.toAbsolutePath()));
}
if (!Files.exists(targetDir) || !Files.isDirectory(targetDir)) {
throw new IllegalStateException(
String.format("Target directory (%s) does not exist. Exiting.%n", targetDir.toAbsolutePath()));
}
if (!Files.exists(valeConfigFile) || !Files.isRegularFile(valeConfigFile)) {
throw new IllegalStateException(
String.format("Vale config file (%s) does not exist. Exiting.%n", valeConfigFile.toAbsolutePath()));
}
DockerImageName valeImage = DockerImageName.parse(imageName);
List<String> command = new ArrayList<>(List.of("--config=/.vale.ini",
"--minAlertLevel=" + minAlertLevel.name(),
"--output=JSON",
"--no-exit"));
if (fileFilterPattern == null) {
// inspect all files in the mounted asciidoc dir
command.add("/asciidoc");
} else {
// construct list of files to inspect
try (Stream<Path> pathStream = Files.list(srcDir)) {
pathStream
.map(path -> path.getFileName().toString())
.filter(p -> includeFile(p))
.map(p -> "/asciidoc/" + p)
.forEach(p -> command.add(p));
}
}
try (GenericContainer<?> container = new GenericContainer<>(valeImage)
.withFileSystemBind(valeDir.toString(), "/.vale", BindMode.READ_ONLY)
.withFileSystemBind(srcDir.toString(), "/asciidoc", BindMode.READ_ONLY)
.withCopyFileToContainer(MountableFile.forHostPath(valeConfigFile), "/.vale.ini")
.withStartupCheckStrategy(new IndefiniteWaitOneShotStartupCheckStrategy())
.withCommand(command.toArray(new String[0]))) {
container.start();
System.out.println("βοΈ Collating results...");
final String logs = container.getLogs(OutputType.STDOUT);
ObjectMapper json = new ObjectMapper();
Map<String, List<Check>> results = json.readValue(logs, typeRef);
Map<String, ChecksBySeverity> fileAndSeverity = new TreeMap<String, ChecksBySeverity>();
for (Entry<String, List<Check>> e : results.entrySet()) {
String key = e.getKey().replace("/asciidoc/", "");
fileAndSeverity.put(key, new ChecksBySeverity().addAll(e.getValue()));
}
return fileAndSeverity;
}
}
boolean includeFile(String fileName) {
if (fileFilterPattern != null) {
return fileFilterPattern.test(fileName);
}
return true;
}
static Path docsDir() {
Path path = Paths.get(System.getProperty("user.dir"));
if (path.endsWith("docs")) {
return path;
}
return path.resolve("docs");
}
public static | ValeAsciidocLint |
java | apache__spark | common/network-common/src/main/java/org/apache/spark/network/server/RpcHandler.java | {
"start": 6817,
"end": 7101
} | class ____ implements MergedBlockMetaReqHandler {
@Override
public void receiveMergeBlockMetaReq(TransportClient client,
MergedBlockMetaRequest mergedBlockMetaRequest, MergedBlockMetaResponseCallback callback) {
// do nothing
}
}
}
| NoopMergedBlockMetaReqHandler |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/SubQueryDecorrelator.java | {
"start": 64307,
"end": 64844
} | class ____ {
private final com.google.common.collect.ImmutableMap<RexSubQuery, Pair<RelNode, RexNode>>
subQueryMap;
static final Result EMPTY = new Result(new HashMap<>());
private Result(Map<RexSubQuery, Pair<RelNode, RexNode>> subQueryMap) {
this.subQueryMap = com.google.common.collect.ImmutableMap.copyOf(subQueryMap);
}
public Pair<RelNode, RexNode> getSubQueryEquivalent(RexSubQuery subQuery) {
return subQueryMap.get(subQuery);
}
}
}
| Result |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/support/http/UserAgentMacTest.java | {
"start": 757,
"end": 1834
} | class ____ extends TestCase {
public void test_mac_firefox() throws Exception {
WebAppStat stat = new WebAppStat("");
stat.computeUserAgent("Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6");
assertEquals(0, stat.getBrowserChromeCount());
assertEquals(1, stat.getBrowserFirefoxCount());
assertEquals(0, stat.getBrowserOperaCount());
assertEquals(0, stat.getBrowserSafariCount());
assertEquals(0, stat.getDeviceAndroidCount());
assertEquals(0, stat.getDeviceIpadCount());
assertEquals(0, stat.getDeviceIphoneCount());
assertEquals(0, stat.getDeviceWindowsPhoneCount());
assertEquals(0, stat.getOSLinuxCount());
assertEquals(0, stat.getOSLinuxUbuntuCount());
assertEquals(1, stat.getOSMacOSXCount());
assertEquals(0, stat.getOSWindowsCount());
assertEquals(0, stat.getOSSymbianCount());
assertEquals(0, stat.getOSFreeBSDCount());
assertEquals(0, stat.getOSOpenBSDCount());
}
}
| UserAgentMacTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/ops/DeleteTest.java | {
"start": 478,
"end": 2195
} | class ____ extends AbstractOperationTestCase {
@Test
@SuppressWarnings("unchecked")
public void testDeleteVersionedWithCollectionNoUpdate(SessionFactoryScope scope) {
// test adapted from HHH-1564...
scope.inTransaction(
session -> {
VersionedEntity c = new VersionedEntity( "c1", "child-1" );
VersionedEntity p = new VersionedEntity( "root", "root" );
p.getChildren().add( c );
c.setParent( p );
session.persist( p );
}
);
clearCounts( scope );
scope.inTransaction(
session -> {
VersionedEntity loadedParent = session.get( VersionedEntity.class, "root" );
session.remove( loadedParent );
}
);
assertInsertCount( 0, scope );
assertUpdateCount( 0, scope );
assertDeleteCount( 2, scope );
}
@Test
public void testNoUpdateOnDelete(SessionFactoryScope scope) {
Node node = new Node( "test" );
scope.inTransaction(
session ->
session.persist( node )
);
clearCounts( scope );
scope.inTransaction(
session ->
session.remove( node )
);
assertUpdateCount( 0, scope );
assertInsertCount( 0, scope );
}
@Test
@SuppressWarnings("unchecked")
public void testNoUpdateOnDeleteWithCollection(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Node parent = new Node( "parent" );
Node child = new Node( "child" );
parent.getCascadingChildren().add( child );
session.persist( parent );
}
);
clearCounts( scope );
scope.inTransaction(
session -> {
Node parent = session.get( Node.class, "parent" );
session.remove( parent );
}
);
assertUpdateCount( 0, scope );
assertInsertCount( 0, scope );
assertDeleteCount( 2, scope );
}
}
| DeleteTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/TwitterDirectMessageEndpointBuilderFactory.java | {
"start": 32980,
"end": 46739
} | interface ____
extends
EndpointConsumerBuilder {
default TwitterDirectMessageEndpointConsumerBuilder basic() {
return (TwitterDirectMessageEndpointConsumerBuilder) this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Used by the geography search, to search by radius using the
* configured metrics. The unit can either be mi for miles, or km for
* kilometers. You need to configure all the following options:
* longitude, latitude, radius, and distanceMetric.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: km
* Group: consumer (advanced)
*
* @param distanceMetric the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder distanceMetric(String distanceMetric) {
doSetProperty("distanceMetric", distanceMetric);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder exceptionHandler(String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder exchangePattern(String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Used for enabling full text from twitter (eg receive tweets that
* contains more than 140 characters).
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: consumer (advanced)
*
* @param extendedMode the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder extendedMode(boolean extendedMode) {
doSetProperty("extendedMode", extendedMode);
return this;
}
/**
* Used for enabling full text from twitter (eg receive tweets that
* contains more than 140 characters).
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: consumer (advanced)
*
* @param extendedMode the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder extendedMode(String extendedMode) {
doSetProperty("extendedMode", extendedMode);
return this;
}
/**
* Used by the geography search to search by latitude. You need to
* configure all the following options: longitude, latitude, radius, and
* distanceMetric.
*
* The option is a: <code>java.lang.Double</code> type.
*
* Group: consumer (advanced)
*
* @param latitude the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder latitude(Double latitude) {
doSetProperty("latitude", latitude);
return this;
}
/**
* Used by the geography search to search by latitude. You need to
* configure all the following options: longitude, latitude, radius, and
* distanceMetric.
*
* The option will be converted to a <code>java.lang.Double</code> type.
*
* Group: consumer (advanced)
*
* @param latitude the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder latitude(String latitude) {
doSetProperty("latitude", latitude);
return this;
}
/**
* Bounding boxes, created by pairs of lat/lons. Can be used for filter.
* A pair is defined as lat,lon. And multiple pairs can be separated by
* semicolon.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer (advanced)
*
* @param locations the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder locations(String locations) {
doSetProperty("locations", locations);
return this;
}
/**
* Used by the geography search to search by longitude. You need to
* configure all the following options: longitude, latitude, radius, and
* distanceMetric.
*
* The option is a: <code>java.lang.Double</code> type.
*
* Group: consumer (advanced)
*
* @param longitude the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder longitude(Double longitude) {
doSetProperty("longitude", longitude);
return this;
}
/**
* Used by the geography search to search by longitude. You need to
* configure all the following options: longitude, latitude, radius, and
* distanceMetric.
*
* The option will be converted to a <code>java.lang.Double</code> type.
*
* Group: consumer (advanced)
*
* @param longitude the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder longitude(String longitude) {
doSetProperty("longitude", longitude);
return this;
}
/**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option is a:
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*
* @param pollStrategy the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder pollStrategy(org.apache.camel.spi.PollingConsumerPollStrategy pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
}
/**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option will be converted to a
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*
* @param pollStrategy the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder pollStrategy(String pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
}
/**
* Used by the geography search to search by radius. You need to
* configure all the following options: longitude, latitude, radius, and
* distanceMetric.
*
* The option is a: <code>java.lang.Double</code> type.
*
* Group: consumer (advanced)
*
* @param radius the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder radius(Double radius) {
doSetProperty("radius", radius);
return this;
}
/**
* Used by the geography search to search by radius. You need to
* configure all the following options: longitude, latitude, radius, and
* distanceMetric.
*
* The option will be converted to a <code>java.lang.Double</code> type.
*
* Group: consumer (advanced)
*
* @param radius the value to set
* @return the dsl builder
*/
default AdvancedTwitterDirectMessageEndpointConsumerBuilder radius(String radius) {
doSetProperty("radius", radius);
return this;
}
}
/**
* Builder for endpoint producers for the Twitter Direct Message component.
*/
public | AdvancedTwitterDirectMessageEndpointConsumerBuilder |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/serializer/avro/AvroReflectSerialization.java | {
"start": 1332,
"end": 1628
} | class ____ be accepted by this
* serialization, it must either be in the package list configured via
* <code>avro.reflect.pkgs</code> or implement
* {@link AvroReflectSerializable} interface.
*
*/
@SuppressWarnings("unchecked")
@InterfaceAudience.Public
@InterfaceStability.Evolving
public | to |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/contexts/application/ApplicationContextGetTest.java | {
"start": 671,
"end": 1492
} | class ____ {
@RegisterExtension
ArcTestContainer container = new ArcTestContainer(Boom.class);
@Test
public void testGet() {
InjectableContext appContext = Arc.container().getActiveContext(ApplicationScoped.class);
assertNotNull(appContext);
List<InjectableContext> appContexts = Arc.container().getContexts(ApplicationScoped.class);
assertEquals(1, appContexts.size());
InjectableBean<Boom> boomBean = Arc.container().instance(Boom.class).getBean();
assertThatIllegalArgumentException()
.isThrownBy(() -> appContext.get(boomBean));
assertThatIllegalArgumentException()
.isThrownBy(() -> appContext.get(boomBean, new CreationalContextImpl<>(boomBean)));
}
@Singleton
public static | ApplicationContextGetTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/statistics/IOStatisticsSupport.java | {
"start": 2785,
"end": 3389
} | interface ____ implemented
return null;
}
}
/**
* Return a stub duration tracker factory whose returned trackers
* are always no-ops.
*
* As singletons are returned, this is very low-cost to use.
* @return a duration tracker factory.
*/
public static DurationTrackerFactory stubDurationTrackerFactory() {
return StubDurationTrackerFactory.STUB_DURATION_TRACKER_FACTORY;
}
/**
* Get a stub duration tracker.
* @return a stub tracker.
*/
public static DurationTracker stubDurationTracker() {
return StubDurationTracker.STUB_DURATION_TRACKER;
}
}
| not |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/persistence/IntegerResourceVersion.java | {
"start": 1075,
"end": 2821
} | class ____ implements ResourceVersion<IntegerResourceVersion> {
private static final long serialVersionUID = 1L;
private static final IntegerResourceVersion NOT_EXISTING = new IntegerResourceVersion(-1);
private final int value;
private IntegerResourceVersion(int value) {
this.value = value;
}
@Override
public int compareTo(@Nonnull IntegerResourceVersion other) {
return Integer.compare(value, other.getValue());
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj != null && obj.getClass() == IntegerResourceVersion.class) {
final IntegerResourceVersion that = (IntegerResourceVersion) obj;
return this.value == that.getValue();
} else {
return false;
}
}
@Override
public int hashCode() {
return Integer.hashCode(value);
}
@Override
public boolean isExisting() {
return this != NOT_EXISTING;
}
@Override
public String toString() {
return "IntegerResourceVersion{" + "value='" + value + '\'' + '}';
}
public int getValue() {
return this.value;
}
public static IntegerResourceVersion notExisting() {
return NOT_EXISTING;
}
/**
* Create a {@link IntegerResourceVersion} with given integer value.
*
* @param value resource version integer value. The value should not be negative.
* @return {@link IntegerResourceVersion} with given value.
*/
public static IntegerResourceVersion valueOf(int value) {
Preconditions.checkArgument(value >= 0);
return new IntegerResourceVersion(value);
}
}
| IntegerResourceVersion |
java | elastic__elasticsearch | test/framework/src/test/java/org/elasticsearch/logsdb/datageneration/DataGenerationSnapshotTests.java | {
"start": 9998,
"end": 10724
} | class ____ implements DataSourceResponse.ChildFieldGenerator {
private int generatedFields = 0;
@Override
public int generateChildFieldCount() {
return 2;
}
@Override
public boolean generateDynamicSubObject() {
return false;
}
@Override
public boolean generateNestedSubObject() {
return generatedFields > 6 && generatedFields < 12;
}
@Override
public boolean generateRegularSubObject() {
return generatedFields < 6;
}
@Override
public String generateFieldName() {
return "f" + (generatedFields++ + 1);
}
}
}
| StaticChildFieldGenerator |
java | apache__camel | components/camel-azure/camel-azure-eventgrid/src/main/java/org/apache/camel/component/azure/eventgrid/CredentialType.java | {
"start": 863,
"end": 1300
} | enum ____ {
/**
* EventGrid Access Key
*/
ACCESS_KEY,
/**
* Includes:
* <uL>
* <li>Service principal with secret</li>
* <li>Service principal with certificate</li>
* <li>username and password</li>
* </uL>
*
* @see com.azure.identity.DefaultAzureCredentialBuilder
*/
AZURE_IDENTITY,
/**
* EventGrid Token Credential
*/
TOKEN_CREDENTIAL,
}
| CredentialType |
java | apache__kafka | tools/src/main/java/org/apache/kafka/tools/VerifiableConsumer.java | {
"start": 14728,
"end": 15179
} | class ____ {
private final String topic;
private final int partition;
public PartitionData(String topic, int partition) {
this.topic = topic;
this.partition = partition;
}
@JsonProperty
public String topic() {
return topic;
}
@JsonProperty
public int partition() {
return partition;
}
}
private static | PartitionData |
java | netty__netty | codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionTest.java | {
"start": 2343,
"end": 29662
} | class ____ {
private DefaultHttp2Connection server;
private DefaultHttp2Connection client;
private static EventLoopGroup group;
@Mock
private Http2Connection.Listener clientListener;
@Mock
private Http2Connection.Listener clientListener2;
@BeforeAll
public static void beforeClass() {
group = new MultiThreadIoEventLoopGroup(2, LocalIoHandler.newFactory());
}
@AfterAll
public static void afterClass() {
group.shutdownGracefully();
}
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
server = new DefaultHttp2Connection(true);
client = new DefaultHttp2Connection(false);
client.addListener(clientListener);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
assertNotNull(client.stream(((Http2Stream) invocation.getArgument(0)).id()));
return null;
}
}).when(clientListener).onStreamClosed(any(Http2Stream.class));
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
assertNull(client.stream(((Http2Stream) invocation.getArgument(0)).id()));
return null;
}
}).when(clientListener).onStreamRemoved(any(Http2Stream.class));
}
@Test
public void getStreamWithoutStreamShouldReturnNull() {
assertNull(server.stream(100));
}
@Test
public void removeAllStreamsWithEmptyStreams() throws InterruptedException {
testRemoveAllStreams();
}
@Test
public void removeAllStreamsWithJustOneLocalStream() throws Exception {
client.local().createStream(3, false);
testRemoveAllStreams();
}
@Test
public void removeAllStreamsWithJustOneRemoveStream() throws Exception {
client.remote().createStream(2, false);
testRemoveAllStreams();
}
@Test
public void removeAllStreamsWithManyActiveStreams() throws Exception {
Endpoint<Http2RemoteFlowController> remote = client.remote();
Endpoint<Http2LocalFlowController> local = client.local();
for (int c = 3, s = 2; c < 5000; c += 2, s += 2) {
local.createStream(c, false);
remote.createStream(s, false);
}
testRemoveAllStreams();
}
@Test
public void removeIndividualStreamsWhileCloseDoesNotNPE() throws Exception {
final Http2Stream streamA = client.local().createStream(3, false);
final Http2Stream streamB = client.remote().createStream(2, false);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
streamA.close();
streamB.close();
return null;
}
}).when(clientListener2).onStreamClosed(any(Http2Stream.class));
try {
client.addListener(clientListener2);
testRemoveAllStreams();
} finally {
client.removeListener(clientListener2);
}
}
@Test
public void removeAllStreamsWhileIteratingActiveStreams() throws Exception {
final Endpoint<Http2RemoteFlowController> remote = client.remote();
final Endpoint<Http2LocalFlowController> local = client.local();
for (int c = 3, s = 2; c < 5000; c += 2, s += 2) {
local.createStream(c, false);
remote.createStream(s, false);
}
final Promise<Void> promise = group.next().newPromise();
final CountDownLatch latch = new CountDownLatch(client.numActiveStreams());
client.forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) {
client.close(promise).addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
assertTrue(promise.isDone());
latch.countDown();
}
});
return true;
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void removeAllStreamsWhileIteratingActiveStreamsAndExceptionOccurs()
throws Exception {
final Endpoint<Http2RemoteFlowController> remote = client.remote();
final Endpoint<Http2LocalFlowController> local = client.local();
for (int c = 3, s = 2; c < 5000; c += 2, s += 2) {
local.createStream(c, false);
remote.createStream(s, false);
}
final Promise<Void> promise = group.next().newPromise();
final CountDownLatch latch = new CountDownLatch(1);
try {
client.forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) throws Http2Exception {
// This close call is basically a noop, because the following statement will throw an exception.
client.close(promise);
// Do an invalid operation while iterating.
remote.createStream(3, false);
return true;
}
});
} catch (Http2Exception ignored) {
client.close(promise).addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
assertTrue(promise.isDone());
latch.countDown();
}
});
}
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void goAwayReceivedShouldCloseStreamsGreaterThanLastStream() throws Exception {
Http2Stream stream1 = client.local().createStream(3, false);
Http2Stream stream2 = client.local().createStream(5, false);
Http2Stream remoteStream = client.remote().createStream(4, false);
assertEquals(State.OPEN, stream1.state());
assertEquals(State.OPEN, stream2.state());
client.goAwayReceived(3, 8, null);
assertEquals(State.OPEN, stream1.state());
assertEquals(State.CLOSED, stream2.state());
assertEquals(State.OPEN, remoteStream.state());
assertEquals(3, client.local().lastStreamKnownByPeer());
assertEquals(5, client.local().lastStreamCreated());
// The remote endpoint must not be affected by a received GOAWAY frame.
assertEquals(-1, client.remote().lastStreamKnownByPeer());
assertEquals(State.OPEN, remoteStream.state());
}
@Test
public void goAwaySentShouldCloseStreamsGreaterThanLastStream() throws Exception {
Http2Stream stream1 = server.remote().createStream(3, false);
Http2Stream stream2 = server.remote().createStream(5, false);
Http2Stream localStream = server.local().createStream(4, false);
server.goAwaySent(3, 8, null);
assertEquals(State.OPEN, stream1.state());
assertEquals(State.CLOSED, stream2.state());
assertEquals(3, server.remote().lastStreamKnownByPeer());
assertEquals(5, server.remote().lastStreamCreated());
// The local endpoint must not be affected by a sent GOAWAY frame.
assertEquals(-1, server.local().lastStreamKnownByPeer());
assertEquals(State.OPEN, localStream.state());
}
@Test
public void serverCreateStreamShouldSucceed() throws Http2Exception {
Http2Stream stream = server.local().createStream(2, false);
assertEquals(2, stream.id());
assertEquals(State.OPEN, stream.state());
assertEquals(1, server.numActiveStreams());
assertEquals(2, server.local().lastStreamCreated());
stream = server.local().createStream(4, true);
assertEquals(4, stream.id());
assertEquals(State.HALF_CLOSED_LOCAL, stream.state());
assertEquals(2, server.numActiveStreams());
assertEquals(4, server.local().lastStreamCreated());
stream = server.remote().createStream(3, true);
assertEquals(3, stream.id());
assertEquals(State.HALF_CLOSED_REMOTE, stream.state());
assertEquals(3, server.numActiveStreams());
assertEquals(3, server.remote().lastStreamCreated());
stream = server.remote().createStream(5, false);
assertEquals(5, stream.id());
assertEquals(State.OPEN, stream.state());
assertEquals(4, server.numActiveStreams());
assertEquals(5, server.remote().lastStreamCreated());
}
@Test
public void clientCreateStreamShouldSucceed() throws Http2Exception {
Http2Stream stream = client.remote().createStream(2, false);
assertEquals(2, stream.id());
assertEquals(State.OPEN, stream.state());
assertEquals(1, client.numActiveStreams());
assertEquals(2, client.remote().lastStreamCreated());
stream = client.remote().createStream(4, true);
assertEquals(4, stream.id());
assertEquals(State.HALF_CLOSED_REMOTE, stream.state());
assertEquals(2, client.numActiveStreams());
assertEquals(4, client.remote().lastStreamCreated());
assertTrue(stream.isHeadersReceived());
stream = client.local().createStream(3, true);
assertEquals(3, stream.id());
assertEquals(State.HALF_CLOSED_LOCAL, stream.state());
assertEquals(3, client.numActiveStreams());
assertEquals(3, client.local().lastStreamCreated());
assertTrue(stream.isHeadersSent());
stream = client.local().createStream(5, false);
assertEquals(5, stream.id());
assertEquals(State.OPEN, stream.state());
assertEquals(4, client.numActiveStreams());
assertEquals(5, client.local().lastStreamCreated());
}
@Test
public void serverReservePushStreamShouldSucceed() throws Http2Exception {
Http2Stream stream = server.remote().createStream(3, true);
Http2Stream pushStream = server.local().reservePushStream(2, stream);
assertEquals(2, pushStream.id());
assertEquals(State.RESERVED_LOCAL, pushStream.state());
assertEquals(1, server.numActiveStreams());
assertEquals(2, server.local().lastStreamCreated());
}
@Test
public void clientReservePushStreamShouldSucceed() throws Http2Exception {
Http2Stream stream = server.remote().createStream(3, true);
Http2Stream pushStream = server.local().reservePushStream(4, stream);
assertEquals(4, pushStream.id());
assertEquals(State.RESERVED_LOCAL, pushStream.state());
assertEquals(1, server.numActiveStreams());
assertEquals(4, server.local().lastStreamCreated());
}
@Test
public void serverRemoteIncrementAndGetStreamShouldSucceed() throws Http2Exception {
incrementAndGetStreamShouldSucceed(server.remote());
}
@Test
public void serverLocalIncrementAndGetStreamShouldSucceed() throws Http2Exception {
incrementAndGetStreamShouldSucceed(server.local());
}
@Test
public void clientRemoteIncrementAndGetStreamShouldSucceed() throws Http2Exception {
incrementAndGetStreamShouldSucceed(client.remote());
}
@Test
public void clientLocalIncrementAndGetStreamShouldSucceed() throws Http2Exception {
incrementAndGetStreamShouldSucceed(client.local());
}
@Test
public void serverRemoteIncrementAndGetStreamShouldRespectOverflow() throws Http2Exception {
incrementAndGetStreamShouldRespectOverflow(server.remote(), MAX_VALUE);
}
@Test
public void serverLocalIncrementAndGetStreamShouldRespectOverflow() throws Http2Exception {
incrementAndGetStreamShouldRespectOverflow(server.local(), MAX_VALUE - 1);
}
@Test
public void clientRemoteIncrementAndGetStreamShouldRespectOverflow() throws Http2Exception {
incrementAndGetStreamShouldRespectOverflow(client.remote(), MAX_VALUE - 1);
}
@Test
public void clientLocalIncrementAndGetStreamShouldRespectOverflow() throws Http2Exception {
incrementAndGetStreamShouldRespectOverflow(client.local(), MAX_VALUE);
}
@Test
public void clientLocalCreateStreamExhaustedSpace() throws Http2Exception {
client.local().createStream(MAX_VALUE, true);
Http2Exception expected = assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
client.local().createStream(MAX_VALUE, true);
}
});
assertEquals(Http2Error.REFUSED_STREAM, expected.error());
assertEquals(Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN, expected.shutdownHint());
}
@Test
public void newStreamBehindExpectedShouldThrow() throws Http2Exception {
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
server.local().createStream(0, true);
}
});
}
@Test
public void newStreamNotForServerShouldThrow() throws Http2Exception {
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
server.local().createStream(11, true);
}
});
}
@Test
public void newStreamNotForClientShouldThrow() throws Http2Exception {
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
client.local().createStream(10, true);
}
});
}
@Test
public void createShouldThrowWhenMaxAllowedStreamsOpenExceeded() throws Http2Exception {
server.local().maxActiveStreams(0);
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
server.local().createStream(2, true);
}
});
}
@Test
public void serverCreatePushShouldFailOnRemoteEndpointWhenMaxAllowedStreamsExceeded() throws Http2Exception {
server = new DefaultHttp2Connection(true, 0);
server.remote().maxActiveStreams(1);
final Http2Stream requestStream = server.remote().createStream(3, false);
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
server.remote().reservePushStream(2, requestStream);
}
});
}
@Test
public void clientCreatePushShouldFailOnRemoteEndpointWhenMaxAllowedStreamsExceeded() throws Http2Exception {
client = new DefaultHttp2Connection(false, 0);
client.remote().maxActiveStreams(1);
final Http2Stream requestStream = client.remote().createStream(2, false);
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
client.remote().reservePushStream(4, requestStream);
}
});
}
@Test
public void serverCreatePushShouldSucceedOnLocalEndpointWhenMaxAllowedStreamsExceeded() throws Http2Exception {
server = new DefaultHttp2Connection(true, 0);
server.local().maxActiveStreams(1);
Http2Stream requestStream = server.remote().createStream(3, false);
assertNotNull(server.local().reservePushStream(2, requestStream));
}
@Test
public void reserveWithPushDisallowedShouldThrow() throws Http2Exception {
final Http2Stream stream = server.remote().createStream(3, true);
server.remote().allowPushTo(false);
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
server.local().reservePushStream(2, stream);
}
});
}
@Test
public void goAwayReceivedShouldDisallowLocalCreation() throws Http2Exception {
server.goAwayReceived(0, 1L, Unpooled.EMPTY_BUFFER);
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
server.local().createStream(3, true);
}
});
}
@Test
public void goAwayReceivedShouldAllowRemoteCreation() throws Http2Exception {
server.goAwayReceived(0, 1L, Unpooled.EMPTY_BUFFER);
server.remote().createStream(3, true);
}
@Test
public void goAwaySentShouldDisallowRemoteCreation() throws Http2Exception {
server.goAwaySent(0, 1L, Unpooled.EMPTY_BUFFER);
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
server.remote().createStream(2, true);
}
});
}
@Test
public void goAwaySentShouldAllowLocalCreation() throws Http2Exception {
server.goAwaySent(0, 1L, Unpooled.EMPTY_BUFFER);
server.local().createStream(2, true);
}
@Test
public void closeShouldSucceed() throws Http2Exception {
Http2Stream stream = server.remote().createStream(3, true);
stream.close();
assertEquals(State.CLOSED, stream.state());
assertEquals(0, server.numActiveStreams());
}
@Test
public void closeLocalWhenOpenShouldSucceed() throws Http2Exception {
Http2Stream stream = server.remote().createStream(3, false);
stream.closeLocalSide();
assertEquals(State.HALF_CLOSED_LOCAL, stream.state());
assertEquals(1, server.numActiveStreams());
}
@Test
public void closeRemoteWhenOpenShouldSucceed() throws Http2Exception {
Http2Stream stream = server.remote().createStream(3, false);
stream.closeRemoteSide();
assertEquals(State.HALF_CLOSED_REMOTE, stream.state());
assertEquals(1, server.numActiveStreams());
}
@Test
public void closeOnlyOpenSideShouldClose() throws Http2Exception {
Http2Stream stream = server.remote().createStream(3, true);
stream.closeLocalSide();
assertEquals(State.CLOSED, stream.state());
assertEquals(0, server.numActiveStreams());
}
@SuppressWarnings("NumericOverflow")
@Test
public void localStreamInvalidStreamIdShouldThrow() {
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
client.local().createStream(MAX_VALUE + 2, false);
}
});
}
@SuppressWarnings("NumericOverflow")
@Test
public void remoteStreamInvalidStreamIdShouldThrow() {
assertThrows(Http2Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
client.remote().createStream(MAX_VALUE + 1, false);
}
});
}
/**
* We force {@link #clientListener} methods to all throw a {@link RuntimeException} and verify the following:
* <ol>
* <li>all listener methods are called for both {@link #clientListener} and {@link #clientListener2}</li>
* <li>{@link #clientListener2} is notified after {@link #clientListener}</li>
* <li>{@link #clientListener2} methods are all still called despite {@link #clientListener}'s
* method throwing a {@link RuntimeException}</li>
* </ol>
*/
@Test
public void listenerThrowShouldNotPreventOtherListenersFromBeingNotified() throws Http2Exception {
final boolean[] calledArray = new boolean[128];
// The following setup will ensure that clientListener throws exceptions, and marks a value in an array
// such that clientListener2 will verify that is set or fail the test.
int methodIndex = 0;
doAnswer(new ListenerExceptionThrower(calledArray, methodIndex))
.when(clientListener).onStreamAdded(any(Http2Stream.class));
doAnswer(new ListenerVerifyCallAnswer(calledArray, methodIndex++))
.when(clientListener2).onStreamAdded(any(Http2Stream.class));
doAnswer(new ListenerExceptionThrower(calledArray, methodIndex))
.when(clientListener).onStreamActive(any(Http2Stream.class));
doAnswer(new ListenerVerifyCallAnswer(calledArray, methodIndex++))
.when(clientListener2).onStreamActive(any(Http2Stream.class));
doAnswer(new ListenerExceptionThrower(calledArray, methodIndex))
.when(clientListener).onStreamHalfClosed(any(Http2Stream.class));
doAnswer(new ListenerVerifyCallAnswer(calledArray, methodIndex++))
.when(clientListener2).onStreamHalfClosed(any(Http2Stream.class));
doAnswer(new ListenerExceptionThrower(calledArray, methodIndex))
.when(clientListener).onStreamClosed(any(Http2Stream.class));
doAnswer(new ListenerVerifyCallAnswer(calledArray, methodIndex++))
.when(clientListener2).onStreamClosed(any(Http2Stream.class));
doAnswer(new ListenerExceptionThrower(calledArray, methodIndex))
.when(clientListener).onStreamRemoved(any(Http2Stream.class));
doAnswer(new ListenerVerifyCallAnswer(calledArray, methodIndex++))
.when(clientListener2).onStreamRemoved(any(Http2Stream.class));
doAnswer(new ListenerExceptionThrower(calledArray, methodIndex))
.when(clientListener).onGoAwaySent(anyInt(), anyLong(), any(ByteBuf.class));
doAnswer(new ListenerVerifyCallAnswer(calledArray, methodIndex++))
.when(clientListener2).onGoAwaySent(anyInt(), anyLong(), any(ByteBuf.class));
doAnswer(new ListenerExceptionThrower(calledArray, methodIndex))
.when(clientListener).onGoAwayReceived(anyInt(), anyLong(), any(ByteBuf.class));
doAnswer(new ListenerVerifyCallAnswer(calledArray, methodIndex++))
.when(clientListener2).onGoAwayReceived(anyInt(), anyLong(), any(ByteBuf.class));
doAnswer(new ListenerExceptionThrower(calledArray, methodIndex))
.when(clientListener).onStreamAdded(any(Http2Stream.class));
doAnswer(new ListenerVerifyCallAnswer(calledArray, methodIndex++))
.when(clientListener2).onStreamAdded(any(Http2Stream.class));
// Now we add clientListener2 and exercise all listener functionality
try {
client.addListener(clientListener2);
Http2Stream stream = client.local().createStream(3, false);
verify(clientListener).onStreamAdded(any(Http2Stream.class));
verify(clientListener2).onStreamAdded(any(Http2Stream.class));
verify(clientListener).onStreamActive(any(Http2Stream.class));
verify(clientListener2).onStreamActive(any(Http2Stream.class));
Http2Stream reservedStream = client.remote().reservePushStream(2, stream);
verify(clientListener, never()).onStreamActive(streamEq(reservedStream));
verify(clientListener2, never()).onStreamActive(streamEq(reservedStream));
reservedStream.open(false);
verify(clientListener).onStreamActive(streamEq(reservedStream));
verify(clientListener2).onStreamActive(streamEq(reservedStream));
stream.closeLocalSide();
verify(clientListener).onStreamHalfClosed(any(Http2Stream.class));
verify(clientListener2).onStreamHalfClosed(any(Http2Stream.class));
stream.close();
verify(clientListener).onStreamClosed(any(Http2Stream.class));
verify(clientListener2).onStreamClosed(any(Http2Stream.class));
verify(clientListener).onStreamRemoved(any(Http2Stream.class));
verify(clientListener2).onStreamRemoved(any(Http2Stream.class));
client.goAwaySent(client.connectionStream().id(), Http2Error.INTERNAL_ERROR.code(), Unpooled.EMPTY_BUFFER);
verify(clientListener).onGoAwaySent(anyInt(), anyLong(), any(ByteBuf.class));
verify(clientListener2).onGoAwaySent(anyInt(), anyLong(), any(ByteBuf.class));
client.goAwayReceived(client.connectionStream().id(),
Http2Error.INTERNAL_ERROR.code(), Unpooled.EMPTY_BUFFER);
verify(clientListener).onGoAwayReceived(anyInt(), anyLong(), any(ByteBuf.class));
verify(clientListener2).onGoAwayReceived(anyInt(), anyLong(), any(ByteBuf.class));
} finally {
client.removeListener(clientListener2);
}
}
@Test
public void clientLastStreamCreatedWithoutStreamCreated() {
assertEquals(0, client.local().lastStreamCreated());
}
@Test
public void serverLastStreamCreatedWithoutStreamCreated() {
assertEquals(0, server.local().lastStreamCreated());
}
@Test
public void clientCreateMaxStreamId() throws Exception {
int id = MAX_VALUE;
client.local().createStream(id, false);
assertTrue(client.streamMayHaveExisted(id));
assertEquals(id, client.local().lastStreamCreated());
}
@Test
public void serverCreateMaxStreamId() throws Exception {
int id = MAX_VALUE - 1;
server.local().createStream(id, false);
assertTrue(server.streamMayHaveExisted(id));
assertEquals(id, server.local().lastStreamCreated());
}
private void testRemoveAllStreams() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Promise<Void> promise = group.next().newPromise();
client.close(promise).addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
assertTrue(promise.isDone());
latch.countDown();
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
private static void incrementAndGetStreamShouldRespectOverflow(final Endpoint<?> endpoint, int streamId) {
assertTrue(streamId > 0);
try {
endpoint.createStream(streamId, true);
streamId = endpoint.incrementAndGetNextStreamId();
} catch (Throwable t) {
fail(t);
}
assertTrue(streamId < 0);
final int finalStreamId = streamId;
assertThrows(Http2NoMoreStreamIdsException.class, new Executable() {
@Override
public void execute() throws Throwable {
endpoint.createStream(finalStreamId, true);
}
});
}
private static void incrementAndGetStreamShouldSucceed(Endpoint<?> endpoint) throws Http2Exception {
Http2Stream streamA = endpoint.createStream(endpoint.incrementAndGetNextStreamId(), true);
Http2Stream streamB = endpoint.createStream(streamA.id() + 2, true);
Http2Stream streamC = endpoint.createStream(endpoint.incrementAndGetNextStreamId(), true);
assertEquals(streamB.id() + 2, streamC.id());
endpoint.createStream(streamC.id() + 2, true);
}
private static final | DefaultHttp2ConnectionTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/monitor/jvm/JvmService.java | {
"start": 906,
"end": 1878
} | class ____ implements ReportingService<JvmInfo> {
private static final Logger logger = LogManager.getLogger(JvmService.class);
private final JvmInfo jvmInfo;
private final SingleObjectCache<JvmStats> jvmStatsCache;
public static final Setting<TimeValue> REFRESH_INTERVAL_SETTING = Setting.timeSetting(
"monitor.jvm.refresh_interval",
TimeValue.timeValueSeconds(1),
TimeValue.timeValueSeconds(1),
Property.NodeScope
);
public JvmService(Settings settings) {
this.jvmInfo = JvmInfo.jvmInfo();
TimeValue refreshInterval = REFRESH_INTERVAL_SETTING.get(settings);
jvmStatsCache = new JvmStatsCache(refreshInterval, JvmStats.jvmStats());
logger.debug("using refresh_interval [{}]", refreshInterval);
}
@Override
public JvmInfo info() {
return this.jvmInfo;
}
public JvmStats stats() {
return jvmStatsCache.getOrRefresh();
}
private | JvmService |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/http/impl/websocket/WebSocketConnectionImpl.java | {
"start": 5119,
"end": 7585
} | interface ____ both
if (this.metrics instanceof HttpServerMetrics) {
HttpServerMetrics metrics = (HttpServerMetrics) this.metrics;
if (METRICS_ENABLED && metrics != null) {
metrics.disconnected(metric);
}
} else if (this.metrics instanceof HttpClientMetrics) {
HttpClientMetrics metrics = (HttpClientMetrics) this.metrics;
if (METRICS_ENABLED && metrics != null) {
metrics.disconnected(metric);
}
}
super.handleClosed();
}
@Override
protected void handleMessage(Object msg) {
if (msg instanceof WebSocketFrame) {
WebSocketFrame frame = (WebSocketFrame) msg;
handleWsFrame(frame);
}
}
public void handleWsFrame(WebSocketFrame msg) {
WebSocketFrameInternal frame = decodeFrame(msg);
WebSocketImplBase<?> w;
synchronized (this) {
w = webSocket;
}
if (frame.isClose()) {
closeReceived = true;
if (!closeSent) {
close(closeFrame(frame.closeStatusCode(), frame.closeReason())); // Reason
} else {
if (server) {
finishClose();
}
}
}
if (w != null) {
w.handleFrame(frame);
}
}
private void finishClose() {
// Do we really need to test timeout ????
ScheduledFuture<?> timeout = closingTimeout;
if (timeout == null || timeout.cancel(false)) {
closingTimeout = null;
ChannelPromise p = closePromise;
closePromise = null;
super.writeClose(p);
}
}
private WebSocketFrameInternal decodeFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame msg) {
ByteBuf payload = safeBuffer(msg.content());
boolean isFinal = msg.isFinalFragment();
WebSocketFrameType frameType;
if (msg instanceof BinaryWebSocketFrame) {
frameType = WebSocketFrameType.BINARY;
} else if (msg instanceof CloseWebSocketFrame) {
frameType = WebSocketFrameType.CLOSE;
} else if (msg instanceof PingWebSocketFrame) {
frameType = WebSocketFrameType.PING;
} else if (msg instanceof PongWebSocketFrame) {
frameType = WebSocketFrameType.PONG;
} else if (msg instanceof TextWebSocketFrame) {
frameType = WebSocketFrameType.TEXT;
} else if (msg instanceof ContinuationWebSocketFrame) {
frameType = WebSocketFrameType.CONTINUATION;
} else {
throw new IllegalStateException("Unsupported WebSocket msg " + msg);
}
return new WebSocketFrameImpl(frameType, payload, isFinal);
}
}
| to |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/fetch/Stay.java | {
"start": 655,
"end": 2827
} | class ____ implements Serializable {
// member declaration
private int id;
private Person person;
private Person oldPerson;
private Person veryOldPerson;
private Date startDate;
private Date endDate;
private String vessel;
private String authoriser;
private String comments;
// constructors
public Stay() {
}
public Stay(int id) {
this.id = id;
}
public Stay(Person person, Date startDate, Date endDate, String vessel, String authoriser, String comments) {
this.authoriser = authoriser;
this.endDate = endDate;
this.person = person;
this.startDate = startDate;
this.vessel = vessel;
this.comments = comments;
}
// properties
public String getAuthoriser() {
return authoriser;
}
public void setAuthoriser(String authoriser) {
this.authoriser = authoriser;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "person")
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@Fetch(FetchMode.SELECT)
@JoinColumn(name = "oldperson")
public Person getOldPerson() {
return oldPerson;
}
public void setOldPerson(Person oldPerson) {
this.oldPerson = oldPerson;
}
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@Fetch(FetchMode.JOIN)
@JoinColumn(name = "veryoldperson")
public Person getVeryOldPerson() {
return veryOldPerson;
}
public void setVeryOldPerson(Person veryOldPerson) {
this.veryOldPerson = veryOldPerson;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public String getVessel() {
return vessel;
}
public void setVessel(String vessel) {
this.vessel = vessel;
}
}
| Stay |
java | apache__hadoop | hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-infra/src/main/java/org/apache/hadoop/tools/dynamometer/BlockPlacementPolicyAlwaysSatisfied.java | {
"start": 1515,
"end": 1982
} | class ____
implements BlockPlacementStatus {
@Override
public boolean isPlacementPolicySatisfied() {
return true;
}
public String getErrorDescription() {
return null;
}
@Override
public int getAdditionalReplicasRequired() {
return 0;
}
}
@Override
public BlockPlacementStatus verifyBlockPlacement(DatanodeInfo[] locs,
int numberOfReplicas) {
return SATISFIED;
}
}
| BlockPlacementStatusSatisfied |
java | micronaut-projects__micronaut-core | http-server-netty/src/main/java/io/micronaut/http/server/netty/HttpPipelineBuilder.java | {
"start": 9997,
"end": 10587
} | class ____ {
/**
* Create a QUIC SSL engine provider ({@link io.netty.handler.codec.quic.QuicCodecBuilder#sslEngineProvider(Function)}).
*
* @return The engine provider
*/
static Function<QuicChannel, ? extends QuicSslEngine> quicEngineFactory(SslHandlerHolder sslHandlerHolder) {
return q -> {
QuicSslEngine e = sslHandlerHolder.contextHolder.quicSslContext().newEngine(q.alloc());
sslHandlerHolder.quicSslEngine = e;
return e;
};
}
}
final | QuicFactory |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/stream/StreamRemoveParams.java | {
"start": 726,
"end": 1025
} | class ____ extends BaseReferencesParams<StreamRemoveArgs> implements StreamRemoveArgs {
private final StreamMessageId[] ids;
public StreamRemoveParams(StreamMessageId[] ids) {
this.ids = ids;
}
public StreamMessageId[] getIds() {
return ids;
}
}
| StreamRemoveParams |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/SelfAlwaysReturnsThisTest.java | {
"start": 7154,
"end": 7532
} | class ____ {
public Builder selfie() {
return new Builder();
}
}
""")
.expectUnchanged()
.doTest();
}
@Test
public void self_hasParams() {
helper
.addInputLines(
"Builder.java",
"""
package com.google.frobber;
public final | Builder |
java | elastic__elasticsearch | libs/core/src/main/java/org/elasticsearch/core/Types.java | {
"start": 577,
"end": 1111
} | class ____ {
private Types() {}
/**
* There are some situations where we cannot appease javac's type checking, and we
* need to forcibly cast an object's type. Please don't use this method unless you
* have no choice.
* @param argument the object to cast
* @param <T> the inferred type to which to cast the argument
* @return a cast version of the argument
*/
@SuppressWarnings("unchecked")
public static <T> T forciblyCast(Object argument) {
return (T) argument;
}
}
| Types |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/SystemUtils.java | {
"start": 66406,
"end": 66892
} | class ____ loaded.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_2000 = getOsNameMatches(OS_NAME_WINDOWS_PREFIX + " 2000");
/**
* The constant {@code true} if this is Windows 2003.
* <p>
* The result depends on the value of the {@link #OS_NAME} constant.
* </p>
* <p>
* The field will return {@code false} if {@link #OS_NAME} is {@code null}.
* </p>
* <p>
* This value is initialized when the | is |
java | quarkusio__quarkus | test-framework/vertx/src/main/java/io/quarkus/test/vertx/RunOnVertxContextTestMethodInvoker.java | {
"start": 1939,
"end": 2624
} | class ____ to avoid ClassLoader issues
&& originalTestMethod.getParameterTypes()[0].getName().equals(UniAsserter.class.getName()));
}
protected boolean hasSupportedAnnotation(Class<?> originalTestClass, Method originalTestMethod) {
return hasAnnotation(RunOnVertxContext.class, originalTestMethod.getAnnotations())
|| hasAnnotation(RunOnVertxContext.class, originalTestClass.getAnnotations())
|| hasAnnotation(TestReactiveTransaction.class, originalTestMethod.getAnnotations())
|| hasAnnotation(TestReactiveTransaction.class, originalTestClass.getAnnotations());
}
// we need to use the | name |
java | apache__spark | sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/ColumnValue.java | {
"start": 1779,
"end": 8695
} | class ____ {
private static TColumnValue booleanValue(Boolean value) {
TBoolValue tBoolValue = new TBoolValue();
if (value != null) {
tBoolValue.setValue(value);
}
return TColumnValue.boolVal(tBoolValue);
}
private static TColumnValue byteValue(Byte value) {
TByteValue tByteValue = new TByteValue();
if (value != null) {
tByteValue.setValue(value);
}
return TColumnValue.byteVal(tByteValue);
}
private static TColumnValue shortValue(Short value) {
TI16Value tI16Value = new TI16Value();
if (value != null) {
tI16Value.setValue(value);
}
return TColumnValue.i16Val(tI16Value);
}
private static TColumnValue intValue(Integer value) {
TI32Value tI32Value = new TI32Value();
if (value != null) {
tI32Value.setValue(value);
}
return TColumnValue.i32Val(tI32Value);
}
private static TColumnValue longValue(Long value) {
TI64Value tI64Value = new TI64Value();
if (value != null) {
tI64Value.setValue(value);
}
return TColumnValue.i64Val(tI64Value);
}
private static TColumnValue floatValue(Float value) {
TDoubleValue tDoubleValue = new TDoubleValue();
if (value != null) {
tDoubleValue.setValue(value);
}
return TColumnValue.doubleVal(tDoubleValue);
}
private static TColumnValue doubleValue(Double value) {
TDoubleValue tDoubleValue = new TDoubleValue();
if (value != null) {
tDoubleValue.setValue(value);
}
return TColumnValue.doubleVal(tDoubleValue);
}
private static TColumnValue stringValue(String value) {
TStringValue tStringValue = new TStringValue();
if (value != null) {
tStringValue.setValue(value);
}
return TColumnValue.stringVal(tStringValue);
}
private static TColumnValue stringValue(HiveChar value) {
TStringValue tStringValue = new TStringValue();
if (value != null) {
tStringValue.setValue(value.toString());
}
return TColumnValue.stringVal(tStringValue);
}
private static TColumnValue stringValue(HiveVarchar value) {
TStringValue tStringValue = new TStringValue();
if (value != null) {
tStringValue.setValue(value.toString());
}
return TColumnValue.stringVal(tStringValue);
}
private static TColumnValue stringValue(HiveIntervalYearMonth value) {
TStringValue tStrValue = new TStringValue();
if (value != null) {
tStrValue.setValue(value.toString());
}
return TColumnValue.stringVal(tStrValue);
}
private static TColumnValue stringValue(HiveIntervalDayTime value) {
TStringValue tStrValue = new TStringValue();
if (value != null) {
tStrValue.setValue(value.toString());
}
return TColumnValue.stringVal(tStrValue);
}
public static TColumnValue toTColumnValue(TypeDescriptor typeDescriptor, Object value) {
Type type = typeDescriptor.getType();
switch (type) {
case BOOLEAN_TYPE:
return booleanValue((Boolean)value);
case TINYINT_TYPE:
return byteValue((Byte)value);
case SMALLINT_TYPE:
return shortValue((Short)value);
case INT_TYPE:
return intValue((Integer)value);
case BIGINT_TYPE:
return longValue((Long)value);
case FLOAT_TYPE:
return floatValue((Float)value);
case DOUBLE_TYPE:
return doubleValue((Double)value);
case STRING_TYPE:
return stringValue((String)value);
case CHAR_TYPE:
return stringValue((HiveChar)value);
case VARCHAR_TYPE:
return stringValue((HiveVarchar)value);
case DATE_TYPE:
case TIMESTAMP_TYPE:
// SPARK-31859, SPARK-31861: converted to string already in SparkExecuteStatementOperation
return stringValue((String)value);
case DECIMAL_TYPE:
String plainStr = value == null ? null : ((BigDecimal)value).toPlainString();
return stringValue(plainStr);
case BINARY_TYPE:
String strVal = value == null ? null : UTF8String.fromBytes((byte[])value).toString();
return stringValue(strVal);
case ARRAY_TYPE:
case MAP_TYPE:
case STRUCT_TYPE:
case UNION_TYPE:
case USER_DEFINED_TYPE:
case INTERVAL_YEAR_MONTH_TYPE:
case INTERVAL_DAY_TIME_TYPE:
return stringValue((String)value);
case NULL_TYPE:
return stringValue((String)value);
default:
return null;
}
}
private static Boolean getBooleanValue(TBoolValue tBoolValue) {
if (tBoolValue.isSetValue()) {
return tBoolValue.isValue();
}
return null;
}
private static Byte getByteValue(TByteValue tByteValue) {
if (tByteValue.isSetValue()) {
return tByteValue.getValue();
}
return null;
}
private static Short getShortValue(TI16Value tI16Value) {
if (tI16Value.isSetValue()) {
return tI16Value.getValue();
}
return null;
}
private static Integer getIntegerValue(TI32Value tI32Value) {
if (tI32Value.isSetValue()) {
return tI32Value.getValue();
}
return null;
}
private static Long getLongValue(TI64Value tI64Value) {
if (tI64Value.isSetValue()) {
return tI64Value.getValue();
}
return null;
}
private static Double getDoubleValue(TDoubleValue tDoubleValue) {
if (tDoubleValue.isSetValue()) {
return tDoubleValue.getValue();
}
return null;
}
private static String getStringValue(TStringValue tStringValue) {
if (tStringValue.isSetValue()) {
return tStringValue.getValue();
}
return null;
}
private static Date getDateValue(TStringValue tStringValue) {
if (tStringValue.isSetValue()) {
return Date.valueOf(tStringValue.getValue());
}
return null;
}
private static Timestamp getTimestampValue(TStringValue tStringValue) {
if (tStringValue.isSetValue()) {
return Timestamp.valueOf(tStringValue.getValue());
}
return null;
}
private static byte[] getBinaryValue(TStringValue tString) {
if (tString.isSetValue()) {
return tString.getValue().getBytes();
}
return null;
}
private static BigDecimal getBigDecimalValue(TStringValue tStringValue) {
if (tStringValue.isSetValue()) {
return new BigDecimal(tStringValue.getValue());
}
return null;
}
public static Object toColumnValue(TColumnValue value) {
TColumnValue._Fields field = value.getSetField();
switch (field) {
case BOOL_VAL:
return getBooleanValue(value.getBoolVal());
case BYTE_VAL:
return getByteValue(value.getByteVal());
case I16_VAL:
return getShortValue(value.getI16Val());
case I32_VAL:
return getIntegerValue(value.getI32Val());
case I64_VAL:
return getLongValue(value.getI64Val());
case DOUBLE_VAL:
return getDoubleValue(value.getDoubleVal());
case STRING_VAL:
return getStringValue(value.getStringVal());
}
throw new IllegalArgumentException("never");
}
}
| ColumnValue |
java | apache__camel | components/camel-aws/camel-aws2-sts/src/test/java/org/apache/camel/component/aws2/sts/integration/Aws2StsBase.java | {
"start": 1370,
"end": 1868
} | class ____ extends CamelTestSupport {
@RegisterExtension
public static AWSService service = AWSServiceFactory.createSTSService();
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
STS2Component stsComponent = context.getComponent("aws2-sts", STS2Component.class);
stsComponent.getConfiguration().setStsClient(AWSSDKClientUtils.newSTSClient());
return context;
}
}
| Aws2StsBase |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/converter/stream/StreamCacheConverter.java | {
"start": 1412,
"end": 3269
} | class ____ {
/**
* Utility classes should not have a public constructor.
*/
private StreamCacheConverter() {
}
@Converter(order = 1)
public static StreamCache convertToStreamCache(ByteArrayInputStream stream, Exchange exchange) throws IOException {
return new ByteArrayInputStreamCache(stream);
}
@Converter(order = 2)
public static StreamCache convertToStreamCache(InputStream stream, Exchange exchange) throws IOException {
// transfer the input stream to a cached output stream, and then creates a new stream cache view
// of the data, which ensures the input stream is cached and re-readable.
CachedOutputStream cos = new CachedOutputStream(exchange);
IOHelper.copyAndCloseInput(stream, cos);
return cos.newStreamCache();
}
@Converter(order = 3)
public static StreamCache convertToStreamCache(CachedOutputStream cos, Exchange exchange) throws IOException {
return cos.newStreamCache();
}
@Converter(order = 4)
public static StreamCache convertToStreamCache(Reader reader, Exchange exchange) throws IOException {
String data = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, reader);
return new ReaderCache(data);
}
@Converter(order = 5)
public static byte[] convertToByteArray(StreamCache cache, Exchange exchange) throws IOException {
// lets serialize it as a byte array
ByteArrayOutputStream os = new ByteArrayOutputStream();
cache.writeTo(os);
return os.toByteArray();
}
@Converter(order = 6)
public static ByteBuffer convertToByteBuffer(StreamCache cache, Exchange exchange) throws IOException {
byte[] array = convertToByteArray(cache, exchange);
return ByteBuffer.wrap(array);
}
}
| StreamCacheConverter |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/annotatewith/CustomAnnotationWithTwoAnnotationElements.java | {
"start": 496,
"end": 635
} | interface ____ {
String value() default "";
boolean namedAnnotationElement() default false;
}
| CustomAnnotationWithTwoAnnotationElements |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/rest/VerbDefinition.java | {
"start": 1467,
"end": 10418
} | class ____ extends OptionalIdentifiedDefinition<VerbDefinition> {
@XmlTransient
private RestDefinition rest;
@XmlElementRef
private List<ParamDefinition> params = new ArrayList<>();
@XmlElementRef
private List<ResponseMessageDefinition> responseMsgs = new ArrayList<>();
@XmlElementRef
private List<SecurityDefinition> security = new ArrayList<>();
@XmlAttribute
private String path;
@XmlAttribute
private String consumes;
@XmlAttribute
private String produces;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean")
private String disabled;
@XmlAttribute
@Metadata(label = "advanced")
private String type;
@XmlTransient
private Class<?> typeClass;
@XmlAttribute
@Metadata(label = "advanced")
private String outType;
@XmlTransient
private Class<?> outTypeClass;
@XmlAttribute
@Metadata(defaultValue = "off", enums = "off,auto,json,xml,json_xml")
private String bindingMode;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String skipBindingOnErrorCode;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String clientRequestValidation;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String clientResponseValidation;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String enableCORS;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String enableNoContentResponse;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "true")
private String apiDocs;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String deprecated;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean")
private String streamCache;
@XmlAttribute
private String routeId;
@XmlElement(required = true)
private ToDefinition to;
@Override
public String getShortName() {
return "verb";
}
@Override
public String getLabel() {
return "verb";
}
public String getDeprecated() {
return deprecated;
}
/**
* Marks this rest operation as deprecated in OpenApi documentation.
*/
public void setDeprecated(String deprecated) {
this.deprecated = deprecated;
}
public VerbDefinition deprecated() {
this.deprecated = "true";
return this;
}
public String getRouteId() {
return routeId;
}
/**
* Whether stream caching is enabled on this rest operation.
*/
public String getStreamCache() {
return streamCache;
}
/**
* Whether stream caching is enabled on this rest operation.
*/
public void setStreamCache(String streamCache) {
this.streamCache = streamCache;
}
/**
* Enable or disables stream caching for this rest operation.
*
* @param streamCache whether to use stream caching (true or false), the value can be a property placeholder
* @return the builder
*/
public VerbDefinition streamCache(String streamCache) {
setStreamCache(streamCache);
return this;
}
/**
* Sets the id of the route
*/
public void setRouteId(String routeId) {
this.routeId = routeId;
}
public List<ParamDefinition> getParams() {
return params;
}
/**
* To specify the REST operation parameters.
*/
public void setParams(List<ParamDefinition> params) {
this.params = params;
}
public List<ResponseMessageDefinition> getResponseMsgs() {
return responseMsgs;
}
/**
* Sets operation response messages.
*/
public void setResponseMsgs(List<ResponseMessageDefinition> responseMsgs) {
this.responseMsgs = responseMsgs;
}
public List<SecurityDefinition> getSecurity() {
return security;
}
/**
* Sets the security settings for this verb.
*/
public void setSecurity(List<SecurityDefinition> security) {
this.security = security;
}
public String getPath() {
return path;
}
/**
* The path mapping URIs of this REST operation such as /{id}.
*/
public void setPath(String path) {
this.path = path;
}
public String getConsumes() {
return consumes;
}
/**
* To define the content type what the REST service consumes (accept as input), such as application/xml or
* application/json. This option will override what may be configured on a parent level
*/
public void setConsumes(String consumes) {
this.consumes = consumes;
}
public String getProduces() {
return produces;
}
/**
* To define the content type what the REST service produces (uses for output), such as application/xml or
* application/json This option will override what may be configured on a parent level
*/
public void setProduces(String produces) {
this.produces = produces;
}
public String getDisabled() {
return disabled;
}
/**
* Whether to disable this REST service from the route during build time. Once an REST service has been disabled
* then it cannot be enabled later at runtime.
*/
public void setDisabled(String disabled) {
this.disabled = disabled;
}
public String getBindingMode() {
return bindingMode;
}
/**
* Sets the binding mode to use. This option will override what may be configured on a parent level
* <p/>
* The default value is off
*/
public void setBindingMode(String bindingMode) {
this.bindingMode = bindingMode;
}
public String getSkipBindingOnErrorCode() {
return skipBindingOnErrorCode;
}
/**
* Whether to skip binding on output if there is a custom HTTP error code header. This allows to build custom error
* messages that do not bind to json / xml etc, as success messages otherwise will do. This option will override
* what may be configured on a parent level
*/
public void setSkipBindingOnErrorCode(String skipBindingOnErrorCode) {
this.skipBindingOnErrorCode = skipBindingOnErrorCode;
}
public String getClientRequestValidation() {
return clientRequestValidation;
}
/**
* Whether to enable validation of the client request to check:
*
* 1) Content-Type header matches what the Rest DSL consumes; returns HTTP Status 415 if validation error. 2) Accept
* header matches what the Rest DSL produces; returns HTTP Status 406 if validation error. 3) Missing required data
* (query parameters, HTTP headers, body); returns HTTP Status 400 if validation error. 4) Parsing error of the
* message body (JSon, XML or Auto binding mode must be enabled); returns HTTP Status 400 if validation error.
*/
public void setClientRequestValidation(String clientRequestValidation) {
this.clientRequestValidation = clientRequestValidation;
}
public String getClientResponseValidation() {
return clientResponseValidation;
}
/**
* Whether to check what Camel is returning as response to the client:
*
* 1) Status-code and Content-Type matches Rest DSL response messages. 2) Check whether expected headers is included
* according to the Rest DSL repose message headers. 3) If the response body is JSon then check whether its valid
* JSon. Returns 500 if validation error detected.
*/
public void setClientResponseValidation(String clientResponseValidation) {
this.clientResponseValidation = clientResponseValidation;
}
public String getEnableCORS() {
return enableCORS;
}
/**
* Whether to enable CORS headers in the HTTP response. This option will override what may be configured on a parent
* level
* <p/>
* The default value is false.
*/
public void setEnableCORS(String enableCORS) {
this.enableCORS = enableCORS;
}
public String getEnableNoContentResponse() {
return enableNoContentResponse;
}
/**
* Whether to return HTTP 204 with an empty body when a response contains an empty JSON object or XML root object.
* <p/>
* The default value is false.
*/
public void setEnableNoContentResponse(String enableNoContentResponse) {
this.enableNoContentResponse = enableNoContentResponse;
}
public String getType() {
return type;
}
/**
* Sets the | VerbDefinition |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmcontainer/RMContainerImpl.java | {
"start": 22755,
"end": 26388
} | class ____
extends BaseTransition {
@Override
public void transition(RMContainerImpl container, RMContainerEvent event) {
RMContainerNMDoneChangeResourceEvent nmDoneChangeResourceEvent =
(RMContainerNMDoneChangeResourceEvent)event;
Resource rmContainerResource = container.getAllocatedResource();
Resource nmContainerResource =
nmDoneChangeResourceEvent.getNMContainerResource();
if (Resources.equals(rmContainerResource, nmContainerResource)) {
// If rmContainerResource == nmContainerResource, the resource
// increase is confirmed.
// In this case:
// - Set the lastConfirmedResource as nmContainerResource
// - Unregister the allocation expirer
container.lastConfirmedResource = nmContainerResource;
container.containerAllocationExpirer.unregister(
new AllocationExpirationInfo(event.getContainerId()));
} else if (Resources.fitsIn(rmContainerResource, nmContainerResource)) {
// If rmContainerResource < nmContainerResource, this is caused by the
// following sequence:
// 1. AM asks for increase from 1G to 5G, and RM approves it
// 2. AM acquires the increase token and increases on NM
// 3. Before NM reports 5G to RM to confirm the increase, AM sends
// a decrease request to 4G, and RM approves it
// 4. When NM reports 5G to RM, RM now sees its own allocation as 4G
// In this cases:
// - Set the lastConfirmedResource as rmContainerResource
// - Unregister the allocation expirer
// - Notify NM to reduce its resource to rmContainerResource
container.lastConfirmedResource = rmContainerResource;
container.containerAllocationExpirer.unregister(
new AllocationExpirationInfo(event.getContainerId()));
container.eventHandler.handle(new RMNodeUpdateContainerEvent(
container.nodeId,
Collections.singletonMap(container.getContainer(),
ContainerUpdateType.DECREASE_RESOURCE)));
} else if (Resources.fitsIn(nmContainerResource, rmContainerResource)) {
// If nmContainerResource < rmContainerResource, this is caused by the
// following sequence:
// 1. AM asks for increase from 1G to 2G, and RM approves it
// 2. AM asks for increase from 2G to 4G, and RM approves it
// 3. AM only uses the 2G token to increase on NM, but never uses the
// 4G token
// 4. NM reports 2G to RM, but RM sees its own allocation as 4G
// In this case:
// - Set the lastConfirmedResource as the maximum of
// nmContainerResource and lastConfirmedResource
// - Do NOT unregister the allocation expirer
// When the increase allocation expires, resource will be rolled back to
// the last confirmed resource.
container.lastConfirmedResource = Resources.componentwiseMax(
nmContainerResource, container.lastConfirmedResource);
} else {
// Something wrong happened, kill the container
LOG.warn("Something wrong happened, container size reported by NM"
+ " is not expected, ContainerID=" + container.getContainerId()
+ " rm-size-resource:" + rmContainerResource + " nm-size-resource:"
+ nmContainerResource);
container.eventHandler.handle(new RMNodeCleanContainerEvent(
container.nodeId, container.getContainerId()));
}
}
}
private static | NMReportedContainerChangeIsDoneTransition |
java | elastic__elasticsearch | client/sniffer/src/main/java/org/elasticsearch/client/sniff/Sniffer.java | {
"start": 8592,
"end": 10758
} | class ____ {
final Task task;
final Future<?> future;
ScheduledTask(Task task, Future<?> future) {
this.task = task;
this.future = future;
}
/**
* Cancels this task. Returns true if the task has been successfully cancelled, meaning it won't be executed
* or if it is its execution won't have any effect. Returns false if the task cannot be cancelled (possibly it was
* already cancelled or already completed).
*/
boolean skip() {
/*
* Future#cancel should return false whenever a task cannot be cancelled, most likely as it has already started. We don't
* trust it much though so we try to cancel hoping that it will work. At the same time we always call skip too, which means
* that if the task has already started the state change will fail. We could potentially not call skip when cancel returns
* false but we prefer to stay on the safe side.
*/
future.cancel(false);
return task.skip();
}
}
final void sniff() throws IOException {
List<Node> sniffedNodes = nodesSniffer.sniff();
if (logger.isDebugEnabled()) {
logger.debug("sniffed nodes: " + sniffedNodes);
}
if (sniffedNodes.isEmpty()) {
logger.warn("no nodes to set, nodes will be updated at the next sniffing round");
} else {
restClient.setNodes(sniffedNodes);
}
}
@Override
public void close() {
if (initialized.get()) {
nextScheduledTask.skip();
}
this.scheduler.shutdown();
}
/**
* Returns a new {@link SnifferBuilder} to help with {@link Sniffer} creation.
*
* @param restClient the client that gets its hosts set (via
* {@link RestClient#setNodes(Collection)}) once they are fetched
* @return a new instance of {@link SnifferBuilder}
*/
public static SnifferBuilder builder(RestClient restClient) {
return new SnifferBuilder(restClient);
}
/**
* The Scheduler | ScheduledTask |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/SearchServiceSingleNodeTests.java | {
"start": 84191,
"end": 84598
} | class ____ extends Plugin implements SearchPlugin {
@Override
public List<QuerySpec<?>> getQueries() {
return singletonList(new QuerySpec<>("fail_on_rewrite_query", FailOnRewriteQueryBuilder::new, parseContext -> {
throw new UnsupportedOperationException("No query parser for this plugin");
}));
}
}
public static | FailOnRewriteQueryPlugin |
java | apache__logging-log4j2 | log4j-core-test/src/main/java/org/apache/logging/log4j/core/test/smtp/SmtpRequest.java | {
"start": 3130,
"end": 10998
} | class ____ {
/**
* SMTP action received from client.
*/
private final SmtpActionType action;
/**
* Current state of the SMTP state table.
*/
private final SmtpState state;
/**
* Additional information passed from the client with the SMTP action.
*/
private final String params;
/**
* Create a new SMTP client request.
*
* @param actionType type of action/command
* @param params remainder of command line once command is removed
* @param state current SMTP server state
*/
public SmtpRequest(final SmtpActionType actionType, final String params, final SmtpState state) {
this.action = actionType;
this.state = state;
this.params = params;
}
/**
* Execute the SMTP request returning a response. This method models the state transition table for the SMTP server.
*
* @return reponse to the request
*/
public SmtpResponse execute() {
SmtpResponse response = null;
if (action.isStateless()) {
if (SmtpActionType.EXPN == action || SmtpActionType.VRFY == action) {
response = new SmtpResponse(252, "Not supported", this.state);
} else if (SmtpActionType.HELP == action) {
response = new SmtpResponse(211, "No help available", this.state);
} else if (SmtpActionType.NOOP == action) {
response = new SmtpResponse(250, "OK", this.state);
} else if (SmtpActionType.VRFY == action) {
response = new SmtpResponse(252, "Not supported", this.state);
} else if (SmtpActionType.RSET == action) {
response = new SmtpResponse(250, "OK", SmtpState.GREET);
} else {
response = new SmtpResponse(500, "Command not recognized", this.state);
}
// Stateful commands
} else if (SmtpActionType.CONNECT == action) {
if (SmtpState.CONNECT == state) {
response = new SmtpResponse(220, "localhost Dumbster SMTP service ready", SmtpState.GREET);
} else {
response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
}
} else if (SmtpActionType.EHLO == action) {
if (SmtpState.GREET == state) {
response = new SmtpResponse(250, "OK", SmtpState.MAIL);
} else {
response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
}
} else if (SmtpActionType.MAIL == action) {
if (SmtpState.MAIL == state || SmtpState.QUIT == state) {
response = new SmtpResponse(250, "OK", SmtpState.RCPT);
} else {
response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
}
} else if (SmtpActionType.RCPT == action) {
if (SmtpState.RCPT == state) {
response = new SmtpResponse(250, "OK", this.state);
} else {
response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
}
} else if (SmtpActionType.DATA == action) {
if (SmtpState.RCPT == state) {
response = new SmtpResponse(354, "Start mail input; end with <CRLF>.<CRLF>", SmtpState.DATA_HDR);
} else {
response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
}
} else if (SmtpActionType.UNRECOG == action) {
if (SmtpState.DATA_HDR == state || SmtpState.DATA_BODY == state) {
response = new SmtpResponse(-1, Strings.EMPTY, this.state);
} else {
response = new SmtpResponse(500, "Command not recognized", this.state);
}
} else if (SmtpActionType.DATA_END == action) {
if (SmtpState.DATA_HDR == state || SmtpState.DATA_BODY == state) {
response = new SmtpResponse(250, "OK", SmtpState.QUIT);
} else {
response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
}
} else if (SmtpActionType.BLANK_LINE == action) {
if (SmtpState.DATA_HDR == state) {
response = new SmtpResponse(-1, Strings.EMPTY, SmtpState.DATA_BODY);
} else if (SmtpState.DATA_BODY == state) {
response = new SmtpResponse(-1, Strings.EMPTY, this.state);
} else {
response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
}
} else if (SmtpActionType.QUIT == action) {
if (SmtpState.QUIT == state) {
response = new SmtpResponse(
221, "localhost Dumbster service closing transmission channel", SmtpState.CONNECT);
} else {
response = new SmtpResponse(503, "Bad sequence of commands: " + action, this.state);
}
} else {
response = new SmtpResponse(500, "Command not recognized", this.state);
}
return response;
}
/**
* Create an SMTP request object given a line of the input stream from the client and the current internal state.
*
* @param s line of input
* @param state current state
* @return a populated SmtpRequest object
*/
public static SmtpRequest createRequest(final String s, final SmtpState state) {
SmtpActionType action = null;
String params = null;
if (state == SmtpState.DATA_HDR) {
if (s.equals(".")) {
action = SmtpActionType.DATA_END;
} else if (s.length() < 1) {
action = SmtpActionType.BLANK_LINE;
} else {
action = SmtpActionType.UNRECOG;
params = s;
}
} else if (state == SmtpState.DATA_BODY) {
if (s.equals(".")) {
action = SmtpActionType.DATA_END;
} else {
action = SmtpActionType.UNRECOG;
if (s.length() < 1) {
params = "\n";
} else {
params = s;
}
}
} else {
final String su = toRootUpperCase(s);
if (su.startsWith("EHLO ") || su.startsWith("HELO")) {
action = SmtpActionType.EHLO;
params = s.substring(5);
} else if (su.startsWith("MAIL FROM:")) {
action = SmtpActionType.MAIL;
params = s.substring(10);
} else if (su.startsWith("RCPT TO:")) {
action = SmtpActionType.RCPT;
params = s.substring(8);
} else if (su.startsWith("DATA")) {
action = SmtpActionType.DATA;
} else if (su.startsWith("QUIT")) {
action = SmtpActionType.QUIT;
} else if (su.startsWith("RSET")) {
action = SmtpActionType.RSET;
} else if (su.startsWith("NOOP")) {
action = SmtpActionType.NOOP;
} else if (su.startsWith("EXPN")) {
action = SmtpActionType.EXPN;
} else if (su.startsWith("VRFY")) {
action = SmtpActionType.VRFY;
} else if (su.startsWith("HELP")) {
action = SmtpActionType.HELP;
} else {
action = SmtpActionType.UNRECOG;
}
}
final SmtpRequest req = new SmtpRequest(action, params, state);
return req;
}
/**
* Get the parameters of this request (remainder of command line once the command is removed.
*
* @return parameters
*/
public String getParams() {
return params;
}
}
| SmtpRequest |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/zoneddatetime/ZonedDateTimeAssert_isStrictlyBetween_Test.java | {
"start": 820,
"end": 1233
} | class ____ extends AbstractZonedDateTimeAssertBaseTest {
@Override
protected ZonedDateTimeAssert invoke_api_method() {
return assertions.isStrictlyBetween(YESTERDAY, TOMORROW);
}
@Override
protected void verify_internal_effects() {
verify(comparables).assertIsBetween(getInfo(assertions), getActual(assertions), YESTERDAY, TOMORROW, false, false);
}
}
| ZonedDateTimeAssert_isStrictlyBetween_Test |
java | apache__dubbo | dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilderTest.java | {
"start": 1756,
"end": 5777
} | class ____ extends AbstractAnnotationProcessingTest {
private ArrayTypeDefinitionBuilder builder;
private TypeElement testType;
private VariableElement integersField;
private VariableElement stringsField;
private VariableElement primitiveTypeModelsField;
private VariableElement modelsField;
private VariableElement colorsField;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(ArrayTypeModel.class);
}
@Override
protected void beforeEach() {
builder = new ArrayTypeDefinitionBuilder();
testType = getType(ArrayTypeModel.class);
integersField = findField(testType, "integers");
stringsField = findField(testType, "strings");
primitiveTypeModelsField = findField(testType, "primitiveTypeModels");
modelsField = findField(testType, "models");
colorsField = findField(testType, "colors");
}
@Test
void testAccept() {
assertTrue(builder.accept(processingEnv, integersField.asType()));
assertTrue(builder.accept(processingEnv, stringsField.asType()));
assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType()));
assertTrue(builder.accept(processingEnv, modelsField.asType()));
assertTrue(builder.accept(processingEnv, colorsField.asType()));
}
@Test
void testBuild() {
buildAndAssertTypeDefinition(processingEnv, integersField, "int[]", "int", builder);
buildAndAssertTypeDefinition(processingEnv, stringsField, "java.lang.String[]", "java.lang.String", builder);
buildAndAssertTypeDefinition(
processingEnv,
primitiveTypeModelsField,
"org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel[]",
"org.apache.dubbo.metadata.annotation.processing.model.PrimitiveTypeModel",
builder);
buildAndAssertTypeDefinition(
processingEnv,
modelsField,
"org.apache.dubbo.metadata.annotation.processing.model.Model[]",
"org.apache.dubbo.metadata.annotation.processing.model.Model",
builder,
(def, subDef) -> {
TypeElement subType = elements.getTypeElement(subDef.getType());
assertEquals(ElementKind.CLASS, subType.getKind());
});
buildAndAssertTypeDefinition(
processingEnv,
colorsField,
"org.apache.dubbo.metadata.annotation.processing.model.Color[]",
"org.apache.dubbo.metadata.annotation.processing.model.Color",
builder,
(def, subDef) -> {
TypeElement subType = elements.getTypeElement(subDef.getType());
assertEquals(ElementKind.ENUM, subType.getKind());
});
}
static void buildAndAssertTypeDefinition(
ProcessingEnvironment processingEnv,
VariableElement field,
String expectedType,
String compositeType,
TypeBuilder builder,
BiConsumer<TypeDefinition, TypeDefinition>... assertions) {
Map<String, TypeDefinition> typeCache = new HashMap<>();
TypeDefinition typeDefinition = TypeDefinitionBuilder.build(processingEnv, field, typeCache);
String subTypeName = typeDefinition.getItems().get(0);
TypeDefinition subTypeDefinition = typeCache.get(subTypeName);
assertEquals(expectedType, typeDefinition.getType());
// assertEquals(field.getSimpleName().toString(), typeDefinition.get$ref());
assertEquals(compositeType, subTypeDefinition.getType());
// assertEquals(builder.getClass().getName(), typeDefinition.getTypeBuilderName());
Stream.of(assertions).forEach(assertion -> assertion.accept(typeDefinition, subTypeDefinition));
}
}
| ArrayTypeDefinitionBuilderTest |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultScheduler.java | {
"start": 22723,
"end": 24880
} | class ____ implements ExecutionSlotAllocationContext {
@Override
public ResourceProfile getResourceProfile(final ExecutionVertexID executionVertexId) {
return getExecutionVertex(executionVertexId).getResourceProfile();
}
@Override
public Optional<AllocationID> findPriorAllocationId(
final ExecutionVertexID executionVertexId) {
return getExecutionVertex(executionVertexId).findLastAllocation();
}
@Override
public SchedulingTopology getSchedulingTopology() {
return DefaultScheduler.this.getSchedulingTopology();
}
@Override
public Set<SlotSharingGroup> getLogicalSlotSharingGroups() {
return getJobGraph().getSlotSharingGroups();
}
@Override
public Set<CoLocationGroup> getCoLocationGroups() {
return getJobGraph().getCoLocationGroups();
}
@Override
public Collection<ConsumedPartitionGroup> getConsumedPartitionGroups(
ExecutionVertexID executionVertexId) {
return inputsLocationsRetriever.getConsumedPartitionGroups(executionVertexId);
}
@Override
public Collection<ExecutionVertexID> getProducersOfConsumedPartitionGroup(
ConsumedPartitionGroup consumedPartitionGroup) {
return inputsLocationsRetriever.getProducersOfConsumedPartitionGroup(
consumedPartitionGroup);
}
@Override
public Optional<CompletableFuture<TaskManagerLocation>> getTaskManagerLocation(
ExecutionVertexID executionVertexId) {
return inputsLocationsRetriever.getTaskManagerLocation(executionVertexId);
}
@Override
public Optional<TaskManagerLocation> getStateLocation(ExecutionVertexID executionVertexId) {
return stateLocationRetriever.getStateLocation(executionVertexId);
}
@Override
public Set<AllocationID> getReservedAllocations() {
return reservedAllocationRefCounters.keySet();
}
}
}
| DefaultExecutionSlotAllocationContext |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/RollingLevelDB.java | {
"start": 1954,
"end": 3540
} | class ____ {
/** Logger for this class. */
private static final Logger LOG = LoggerFactory.
getLogger(RollingLevelDB.class);
/** Factory to open and create new leveldb instances. */
private static JniDBFactory factory = new JniDBFactory();
/** Thread safe date formatter. */
private FastDateFormat fdf;
/** Date parser. */
private SimpleDateFormat sdf;
/** Calendar to calculate the current and next rolling period. */
private GregorianCalendar cal = new GregorianCalendar(
TimeZone.getTimeZone("GMT"));
/** Collection of all active rolling leveldb instances. */
private final TreeMap<Long, DB> rollingdbs;
/** Collection of all rolling leveldb instances to evict. */
private final TreeMap<Long, DB> rollingdbsToEvict;
/** Name of this rolling level db. */
private final String name;
/** Calculated timestamp of when to roll a new leveldb instance. */
private volatile long nextRollingCheckMillis = 0;
/** File system instance to find and create new leveldb instances. */
private FileSystem lfs = null;
/** Directory to store rolling leveldb instances. */
private Path rollingDBPath;
/** Configuration for this object. */
private Configuration conf;
/** Rolling period. */
private RollingPeriod rollingPeriod;
/**
* Rolling leveldb instances are evicted when their endtime is earlier than
* the current time minus the time to live value.
*/
private long ttl;
/** Whether time to live is enabled. */
private boolean ttlEnabled;
/** Encapsulates the rolling period to date format lookup. */
| RollingLevelDB |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DateTimeParsePipe.java | {
"start": 776,
"end": 2203
} | class ____ extends BinaryDateTimePipe {
private final Parser parser;
public DateTimeParsePipe(Source source, Expression expression, Pipe left, Pipe right, ZoneId zoneId, Parser parser) {
super(source, expression, left, right, zoneId);
this.parser = parser;
}
@Override
protected NodeInfo<DateTimeParsePipe> info() {
return NodeInfo.create(this, DateTimeParsePipe::new, expression(), left(), right(), zoneId(), parser);
}
@Override
protected DateTimeParsePipe replaceChildren(Pipe left, Pipe right) {
return new DateTimeParsePipe(source(), expression(), left, right, zoneId(), parser);
}
@Override
protected Processor makeProcessor(Processor left, Processor right, ZoneId zoneId) {
return new DateTimeParseProcessor(left, right, zoneId, parser);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), this.parser);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (super.equals(o) == false) {
return false;
}
DateTimeParsePipe that = (DateTimeParsePipe) o;
return super.equals(o) && this.parser == that.parser;
}
public Parser parser() {
return parser;
}
}
| DateTimeParsePipe |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/contract/rawlocal/TestRawLocalContractBulkDelete.java | {
"start": 1116,
"end": 1323
} | class ____ extends AbstractContractBulkDeleteTest {
@Override
protected AbstractFSContract createContract(Configuration conf) {
return new RawlocalFSContract(conf);
}
}
| TestRawLocalContractBulkDelete |
java | apache__camel | components/camel-aws/camel-aws2-s3/src/test/java/org/apache/camel/component/aws2/s3/integration/S3ObjectTaggingOperationIT.java | {
"start": 1521,
"end": 5380
} | class ____ extends Aws2S3Base {
@EndpointInject
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint result;
@Test
public void putAndGetObjectTagging() throws Exception {
// First upload an object
template.send("direct:putObject", exchange -> {
exchange.getIn().setBody("Test Content");
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test-tagging-key");
});
// Put tags on the object
Exchange putResult = template.request("direct:putObjectTagging", new Processor() {
@Override
public void process(Exchange exchange) {
Map<String, String> tags = new HashMap<>();
tags.put("Environment", "Development");
tags.put("Project", "Camel");
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test-tagging-key");
exchange.getIn().setHeader(AWS2S3Constants.OBJECT_TAGS, tags);
exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.putObjectTagging);
}
});
assertNotNull(putResult);
// Get tags from the object
Exchange getResult = template.request("direct:getObjectTagging", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test-tagging-key");
exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.getObjectTagging);
}
});
List<Tag> tags = getResult.getMessage().getBody(List.class);
assertNotNull(tags);
assertEquals(2, tags.size());
}
@Test
public void deleteObjectTagging() throws Exception {
// First upload an object
template.send("direct:putObject", exchange -> {
exchange.getIn().setBody("Test Content");
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test-delete-tagging-key");
});
// Put tags on the object
template.send("direct:putObjectTagging2", new Processor() {
@Override
public void process(Exchange exchange) {
Map<String, String> tags = new HashMap<>();
tags.put("Temp", "Value");
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test-delete-tagging-key");
exchange.getIn().setHeader(AWS2S3Constants.OBJECT_TAGS, tags);
exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.putObjectTagging);
}
});
// Delete tags
Exchange deleteResult = template.request("direct:deleteObjectTagging", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(AWS2S3Constants.KEY, "test-delete-tagging-key");
exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.deleteObjectTagging);
}
});
assertNotNull(deleteResult);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
String awsEndpoint = "aws2-s3://" + name.get() + "?autoCreateBucket=true";
from("direct:putObject")
.to(awsEndpoint);
from("direct:putObjectTagging")
.to(awsEndpoint);
from("direct:putObjectTagging2")
.to(awsEndpoint);
from("direct:getObjectTagging")
.to(awsEndpoint);
from("direct:deleteObjectTagging")
.to(awsEndpoint);
}
};
}
}
| S3ObjectTaggingOperationIT |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/json/CockroachDBJsonValueFunction.java | {
"start": 872,
"end": 4316
} | class ____ extends JsonValueFunction {
public CockroachDBJsonValueFunction(TypeConfiguration typeConfiguration) {
super( typeConfiguration, true, false );
}
@Override
protected void render(
SqlAppender sqlAppender,
JsonValueArguments arguments,
ReturnableType<?> returnType,
SqlAstTranslator<?> walker) {
// jsonb_path_query_first errors by default
if ( arguments.errorBehavior() != null && arguments.errorBehavior() != JsonValueErrorBehavior.ERROR ) {
throw new QueryException( "Can't emulate on error clause on CockroachDB" );
}
if ( arguments.emptyBehavior() != null && arguments.emptyBehavior() != JsonValueEmptyBehavior.NULL ) {
throw new QueryException( "Can't emulate on empty clause on CockroachDB" );
}
final String jsonPath;
try {
jsonPath = walker.getLiteralValue( arguments.jsonPath() );
}
catch (Exception ex) {
throw new QueryException( "CockroachDB json_value only support literal json paths, but got " + arguments.jsonPath() );
}
appendJsonValue(
sqlAppender,
arguments.jsonDocument(),
JsonPathHelper.parseJsonPathElements( jsonPath ),
arguments.isJsonType(),
arguments.passingClause(),
arguments.returningType(),
walker
);
}
static void appendJsonValue(SqlAppender sqlAppender, Expression jsonDocument, List<JsonPathHelper.JsonPathElement> jsonPathElements, boolean isJsonType, JsonPathPassingClause jsonPathPassingClause, CastTarget castTarget, SqlAstTranslator<?> walker) {
if ( castTarget != null ) {
sqlAppender.appendSql( "cast(" );
}
final boolean needsCast = !isJsonType && AbstractSqlAstTranslator.isParameter( jsonDocument );
if ( needsCast ) {
sqlAppender.appendSql( "cast(" );
}
else {
sqlAppender.appendSql( '(' );
}
jsonDocument.accept( walker );
if ( needsCast ) {
sqlAppender.appendSql( " as jsonb)" );
}
else {
sqlAppender.appendSql( ')' );
}
sqlAppender.appendSql( "#>>array" );
char separator = '[';
final Dialect dialect = walker.getSessionFactory().getJdbcServices().getDialect();
for ( JsonPathHelper.JsonPathElement jsonPathElement : jsonPathElements ) {
sqlAppender.appendSql( separator );
if ( jsonPathElement instanceof JsonPathHelper.JsonAttribute attribute ) {
dialect.appendLiteral( sqlAppender, attribute.attribute() );
}
else if ( jsonPathElement instanceof JsonPathHelper.JsonParameterIndexAccess ) {
assert jsonPathPassingClause != null;
final String parameterName = ( (JsonPathHelper.JsonParameterIndexAccess) jsonPathElement ).parameterName();
final Expression expression = jsonPathPassingClause.getPassingExpressions().get( parameterName );
if ( expression == null ) {
throw new QueryException( "JSON path [" + JsonPathHelper.toJsonPath( jsonPathElements ) + "] uses parameter [" + parameterName + "] that is not passed" );
}
sqlAppender.appendSql( "cast(" );
expression.accept( walker );
sqlAppender.appendSql( " as text)" );
}
else {
sqlAppender.appendSql( '\'' );
sqlAppender.appendSql( ( (JsonPathHelper.JsonIndexAccess) jsonPathElement ).index() );
sqlAppender.appendSql( '\'' );
}
separator = ',';
}
if ( jsonPathElements.isEmpty() ) {
sqlAppender.appendSql( '[' );
}
sqlAppender.appendSql( ']' );
if ( castTarget != null ) {
sqlAppender.appendSql( " as " );
castTarget.accept( walker );
sqlAppender.appendSql( ')' );
}
}
}
| CockroachDBJsonValueFunction |
java | apache__kafka | server/src/main/java/org/apache/kafka/server/ClientMetricsManager.java | {
"start": 3810,
"end": 23623
} | class ____ implements AutoCloseable {
public static final String CLIENT_METRICS_REAPER_THREAD_NAME = "client-metrics-reaper";
private static final Logger log = LoggerFactory.getLogger(ClientMetricsManager.class);
private static final List<Byte> SUPPORTED_COMPRESSION_TYPES = List.of(CompressionType.ZSTD.id, CompressionType.LZ4.id,
CompressionType.GZIP.id, CompressionType.SNAPPY.id);
// Max cache size (16k active client connections per broker)
private static final int CACHE_MAX_SIZE = 16384;
private static final int DEFAULT_CACHE_EXPIRY_MS = 60 * 1000;
private final ClientTelemetryExporterPlugin clientTelemetryExporterPlugin;
private final Cache<Uuid, ClientMetricsInstance> clientInstanceCache;
private final Map<String, Uuid> clientConnectionIdMap;
private final Timer expirationTimer;
private final Map<String, SubscriptionInfo> subscriptionMap;
private final int clientTelemetryMaxBytes;
private final Time time;
private final int cacheExpiryMs;
private final AtomicLong lastCacheErrorLogMs;
private final Metrics metrics;
private final ClientMetricsStats clientMetricsStats;
private final ConnectionDisconnectListener connectionDisconnectListener;
// The latest subscription version is used to determine if subscription has changed and needs
// to re-evaluate the client instance subscription id as per changed subscriptions.
private final AtomicInteger subscriptionUpdateVersion;
public ClientMetricsManager(ClientTelemetryExporterPlugin clientTelemetryExporterPlugin, int clientTelemetryMaxBytes, Time time, Metrics metrics) {
this(clientTelemetryExporterPlugin, clientTelemetryMaxBytes, time, DEFAULT_CACHE_EXPIRY_MS, metrics);
}
// Visible for testing
ClientMetricsManager(ClientTelemetryExporterPlugin clientTelemetryExporterPlugin, int clientTelemetryMaxBytes, Time time, int cacheExpiryMs, Metrics metrics) {
this.clientTelemetryExporterPlugin = clientTelemetryExporterPlugin;
this.subscriptionMap = new ConcurrentHashMap<>();
this.subscriptionUpdateVersion = new AtomicInteger(0);
this.clientInstanceCache = new SynchronizedCache<>(new LRUCache<>(CACHE_MAX_SIZE));
this.clientConnectionIdMap = new ConcurrentHashMap<>();
this.expirationTimer = new SystemTimerReaper(CLIENT_METRICS_REAPER_THREAD_NAME, new SystemTimer("client-metrics"));
this.clientTelemetryMaxBytes = clientTelemetryMaxBytes;
this.time = time;
this.cacheExpiryMs = cacheExpiryMs;
this.lastCacheErrorLogMs = new AtomicLong(0);
this.metrics = metrics;
this.clientMetricsStats = new ClientMetricsStats();
this.connectionDisconnectListener = new ClientConnectionDisconnectListener();
}
public Set<String> listClientMetricsResources() {
return subscriptionMap.keySet();
}
public void updateSubscription(String subscriptionName, Properties properties) {
// Validate the subscription properties.
ClientMetricsConfigs.validate(subscriptionName, properties);
// IncrementalAlterConfigs API will send empty configs when all the configs are deleted
// for respective subscription. In that case, we need to remove the subscription from the map.
if (properties.isEmpty()) {
// Remove the subscription from the map if it exists, else ignore the config update.
if (subscriptionMap.containsKey(subscriptionName)) {
log.info("Removing subscription [{}] from the subscription map", subscriptionName);
subscriptionMap.remove(subscriptionName);
subscriptionUpdateVersion.incrementAndGet();
}
return;
}
updateClientSubscription(subscriptionName, new ClientMetricsConfigs(properties));
/*
Increment subscription update version to indicate that there is a change in the subscription. This will
be used to determine if the next telemetry request needs to re-evaluate the subscription id
as per the changed subscriptions.
*/
subscriptionUpdateVersion.incrementAndGet();
}
public GetTelemetrySubscriptionsResponse processGetTelemetrySubscriptionRequest(
GetTelemetrySubscriptionsRequest request, RequestContext requestContext) {
long now = time.milliseconds();
Uuid clientInstanceId = Optional.ofNullable(request.data().clientInstanceId())
.filter(id -> !id.equals(Uuid.ZERO_UUID))
.orElse(generateNewClientId());
/*
Get the client instance from the cache or create a new one. If subscription has changed
since the last request, then the client instance will be re-evaluated. Validation of the
request will be done after the client instance is created. If client issues another get
telemetry request prior to push interval, then the client should get a throttle error but if
the subscription has changed since the last request then the client should get the updated
subscription immediately.
*/
ClientMetricsInstance clientInstance = clientInstance(clientInstanceId, requestContext);
try {
// Validate the get request parameters for the client instance.
validateGetRequest(request, clientInstance, now);
} catch (ApiException exception) {
return request.getErrorResponse(0, exception);
}
clientInstance.lastKnownError(Errors.NONE);
return createGetSubscriptionResponse(clientInstanceId, clientInstance);
}
public PushTelemetryResponse processPushTelemetryRequest(PushTelemetryRequest request, RequestContext requestContext) {
Uuid clientInstanceId = request.data().clientInstanceId();
if (clientInstanceId == null || Uuid.RESERVED.contains(clientInstanceId)) {
String msg = String.format("Invalid request from the client [%s], invalid client instance id",
clientInstanceId);
return request.getErrorResponse(0, new InvalidRequestException(msg));
}
long now = time.milliseconds();
ClientMetricsInstance clientInstance = clientInstance(clientInstanceId, requestContext);
try {
// Validate the push request parameters for the client instance.
validatePushRequest(request, clientInstance, now);
} catch (ApiException exception) {
log.debug("Error validating push telemetry request from client [{}]", clientInstanceId, exception);
clientInstance.lastKnownError(Errors.forException(exception));
return request.getErrorResponse(0, exception);
} finally {
// Update the client instance with the latest push request parameters.
clientInstance.terminating(request.data().terminating());
}
// Push the metrics to the external client receiver plugin.
ByteBuffer metrics = request.data().metrics();
if (metrics != null && metrics.limit() > 0) {
try {
long exportTimeStartMs = time.hiResClockMs();
clientTelemetryExporterPlugin.exportMetrics(requestContext, request, clientInstance.pushIntervalMs());
clientMetricsStats.recordPluginExport(clientInstanceId, time.hiResClockMs() - exportTimeStartMs);
} catch (Throwable exception) {
clientMetricsStats.recordPluginErrorCount(clientInstanceId);
clientInstance.lastKnownError(Errors.INVALID_RECORD);
log.error("Error exporting client metrics to the plugin for client instance id: {}", clientInstanceId, exception);
return request.errorResponse(0, Errors.INVALID_RECORD);
}
}
clientInstance.lastKnownError(Errors.NONE);
return new PushTelemetryResponse(new PushTelemetryResponseData());
}
public boolean isTelemetryExporterConfigured() {
return !clientTelemetryExporterPlugin.isEmpty();
}
public ConnectionDisconnectListener connectionDisconnectListener() {
return connectionDisconnectListener;
}
@Override
public void close() throws Exception {
subscriptionMap.clear();
expirationTimer.close();
clientMetricsStats.unregisterMetrics();
}
private void updateClientSubscription(String subscriptionName, ClientMetricsConfigs configs) {
List<String> metrics = configs.getList(ClientMetricsConfigs.METRICS_CONFIG);
int pushInterval = configs.getInt(ClientMetricsConfigs.INTERVAL_MS_CONFIG);
List<String> clientMatchPattern = configs.getList(ClientMetricsConfigs.MATCH_CONFIG);
SubscriptionInfo newSubscription =
new SubscriptionInfo(subscriptionName, metrics, pushInterval,
ClientMetricsConfigs.parseMatchingPatterns(clientMatchPattern));
subscriptionMap.put(subscriptionName, newSubscription);
}
private Uuid generateNewClientId() {
Uuid id = Uuid.randomUuid();
while (clientInstanceCache.get(id) != null) {
id = Uuid.randomUuid();
}
return id;
}
private ClientMetricsInstance clientInstance(Uuid clientInstanceId, RequestContext requestContext) {
ClientMetricsInstance clientInstance = clientInstanceCache.get(clientInstanceId);
if (clientInstance == null) {
/*
If the client instance is not present in the cache, then create a new client instance
and update the cache. This can also happen when the telemetry request is received by
the separate broker instance.
Though cache is synchronized, but it is possible that concurrent calls can create the same
client instance. Hence, safeguard the client instance creation with a double-checked lock
to ensure that only one instance is created.
*/
synchronized (this) {
clientInstance = clientInstanceCache.get(clientInstanceId);
if (clientInstance != null) {
return clientInstance;
}
ClientMetricsInstanceMetadata instanceMetadata = new ClientMetricsInstanceMetadata(
clientInstanceId, requestContext);
clientInstance = createClientInstanceAndUpdateCache(clientInstanceId, instanceMetadata, requestContext.connectionId());
}
} else if (clientInstance.subscriptionVersion() < subscriptionUpdateVersion.get()) {
/*
If the last subscription update version for client instance is older than the subscription
updated version, then re-evaluate the subscription information for the client as per the
updated subscriptions. This is to ensure that the client instance is always in sync with
the latest subscription information.
Though cache is synchronized, but it is possible that concurrent calls can create the same
client instance. Hence, safeguard the client instance update with a double-checked lock
to ensure that only one instance is created.
*/
synchronized (this) {
clientInstance = clientInstanceCache.get(clientInstanceId);
if (clientInstance.subscriptionVersion() >= subscriptionUpdateVersion.get()) {
return clientInstance;
}
// Cancel the existing expiration timer task for the old client instance.
clientInstance.cancelExpirationTimerTask();
clientInstance = createClientInstanceAndUpdateCache(clientInstanceId, clientInstance.instanceMetadata(), requestContext.connectionId());
}
}
// Update the expiration timer task for the client instance.
long expirationTimeMs = Math.max(cacheExpiryMs, clientInstance.pushIntervalMs() * 3);
TimerTask timerTask = new ExpirationTimerTask(clientInstanceId, requestContext.connectionId(), expirationTimeMs);
clientInstance.updateExpirationTimerTask(timerTask);
expirationTimer.add(timerTask);
return clientInstance;
}
private ClientMetricsInstance createClientInstanceAndUpdateCache(Uuid clientInstanceId,
ClientMetricsInstanceMetadata instanceMetadata, String connectionId) {
ClientMetricsInstance clientInstance = createClientInstance(clientInstanceId, instanceMetadata);
// Maybe add client metrics, if metrics not already added. Metrics might be already added
// if the client instance was evicted from the cache because of size limit.
clientMetricsStats.maybeAddClientInstanceMetrics(clientInstanceId);
clientInstanceCache.put(clientInstanceId, clientInstance);
clientConnectionIdMap.put(connectionId, clientInstanceId);
return clientInstance;
}
private ClientMetricsInstance createClientInstance(Uuid clientInstanceId, ClientMetricsInstanceMetadata instanceMetadata) {
int pushIntervalMs = ClientMetricsConfigs.INTERVAL_MS_DEFAULT;
// Keep a set of metrics to avoid duplicates in case of overlapping subscriptions.
Set<String> subscribedMetrics = new HashSet<>();
boolean allMetricsSubscribed = false;
int currentSubscriptionVersion = subscriptionUpdateVersion.get();
for (SubscriptionInfo info : subscriptionMap.values()) {
if (instanceMetadata.isMatch(info.matchPattern())) {
allMetricsSubscribed = allMetricsSubscribed || info.metrics().contains(
ClientMetricsConfigs.ALL_SUBSCRIBED_METRICS);
subscribedMetrics.addAll(info.metrics());
pushIntervalMs = Math.min(pushIntervalMs, info.intervalMs());
}
}
/*
If client matches with any subscription that has * metrics string, then it means that client
is subscribed to all the metrics, so just send the * string as the subscribed metrics.
*/
if (allMetricsSubscribed) {
// Only add an * to indicate that all metrics are subscribed.
subscribedMetrics.clear();
subscribedMetrics.add(ClientMetricsConfigs.ALL_SUBSCRIBED_METRICS);
}
int subscriptionId = computeSubscriptionId(subscribedMetrics, pushIntervalMs, clientInstanceId);
return new ClientMetricsInstance(clientInstanceId, instanceMetadata, subscriptionId,
currentSubscriptionVersion, subscribedMetrics, pushIntervalMs);
}
/**
* Computes the SubscriptionId as a unique identifier for a client instance's subscription set,
* the id is generated by calculating a CRC32C of the configured metrics subscriptions including
* the PushIntervalMs, XORed with the ClientInstanceId.
*/
private int computeSubscriptionId(Set<String> metrics, int pushIntervalMs, Uuid clientInstanceId) {
byte[] metricsBytes = (metrics.toString() + pushIntervalMs).getBytes(StandardCharsets.UTF_8);
long computedCrc = Crc32C.compute(metricsBytes, 0, metricsBytes.length);
return (int) computedCrc ^ clientInstanceId.hashCode();
}
private GetTelemetrySubscriptionsResponse createGetSubscriptionResponse(Uuid clientInstanceId,
ClientMetricsInstance clientInstance) {
GetTelemetrySubscriptionsResponseData data = new GetTelemetrySubscriptionsResponseData()
.setClientInstanceId(clientInstanceId)
.setSubscriptionId(clientInstance.subscriptionId())
.setRequestedMetrics(new ArrayList<>(clientInstance.metrics()))
.setAcceptedCompressionTypes(SUPPORTED_COMPRESSION_TYPES)
.setPushIntervalMs(clientInstance.pushIntervalMs())
.setTelemetryMaxBytes(clientTelemetryMaxBytes)
.setDeltaTemporality(true)
.setErrorCode(Errors.NONE.code());
return new GetTelemetrySubscriptionsResponse(data);
}
private void validateGetRequest(GetTelemetrySubscriptionsRequest request,
ClientMetricsInstance clientInstance, long timestamp) {
if (!clientInstance.maybeUpdateGetRequestTimestamp(timestamp) && (clientInstance.lastKnownError() != Errors.UNKNOWN_SUBSCRIPTION_ID
&& clientInstance.lastKnownError() != Errors.UNSUPPORTED_COMPRESSION_TYPE)) {
clientMetricsStats.recordThrottleCount(clientInstance.clientInstanceId());
String msg = String.format("Request from the client [%s] arrived before the next push interval time",
request.data().clientInstanceId());
throw new ThrottlingQuotaExceededException(msg);
}
}
private void validatePushRequest(PushTelemetryRequest request, ClientMetricsInstance clientInstance, long timestamp) {
if (clientInstance.terminating()) {
String msg = String.format(
"Client [%s] sent the previous request with state terminating to TRUE, can not accept"
+ "any requests after that", request.data().clientInstanceId());
throw new InvalidRequestException(msg);
}
if (!clientInstance.maybeUpdatePushRequestTimestamp(timestamp) && !request.data().terminating()) {
clientMetricsStats.recordThrottleCount(clientInstance.clientInstanceId());
String msg = String.format("Request from the client [%s] arrived before the next push interval time",
request.data().clientInstanceId());
throw new ThrottlingQuotaExceededException(msg);
}
if (request.data().subscriptionId() != clientInstance.subscriptionId()) {
clientMetricsStats.recordUnknownSubscriptionCount();
String msg = String.format("Unknown client subscription id for the client [%s]",
request.data().clientInstanceId());
throw new UnknownSubscriptionIdException(msg);
}
if (!isSupportedCompressionType(request.data().compressionType())) {
String msg = String.format("Unknown compression type [%s] is received in telemetry request from [%s]",
request.data().compressionType(), request.data().clientInstanceId());
throw new UnsupportedCompressionTypeException(msg);
}
if (request.data().metrics() != null && request.data().metrics().limit() > clientTelemetryMaxBytes) {
String msg = String.format("Telemetry request from [%s] is larger than the maximum allowed size [%s]",
request.data().clientInstanceId(), clientTelemetryMaxBytes);
throw new TelemetryTooLargeException(msg);
}
}
private static boolean isSupportedCompressionType(int id) {
try {
CompressionType.forId(id);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
// Visible for testing
SubscriptionInfo subscriptionInfo(String subscriptionName) {
return subscriptionMap.get(subscriptionName);
}
// Visible for testing
Collection<SubscriptionInfo> subscriptions() {
return Collections.unmodifiableCollection(subscriptionMap.values());
}
// Visible for testing
ClientMetricsInstance clientInstance(Uuid clientInstanceId) {
return clientInstanceCache.get(clientInstanceId);
}
// Visible for testing
int subscriptionUpdateVersion() {
return subscriptionUpdateVersion.get();
}
// Visible for testing
Timer expirationTimer() {
return expirationTimer;
}
// Visible for testing
Map<String, Uuid> clientConnectionIdMap() {
return clientConnectionIdMap;
}
private final | ClientMetricsManager |
java | mapstruct__mapstruct | integrationtest/src/test/resources/sealedSubclassTest/src/main/java/org/mapstruct/itest/sealedsubclass/BikeDto.java | {
"start": 206,
"end": 452
} | class ____ extends VehicleDto {
private int numberOfGears;
public int getNumberOfGears() {
return numberOfGears;
}
public void setNumberOfGears(int numberOfGears) {
this.numberOfGears = numberOfGears;
}
}
| BikeDto |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/GenericMappedSuperclassAssociationTest.java | {
"start": 4427,
"end": 4614
} | class ____ extends Child<ParentA> {
public ChildA() {
}
public ChildA(String name, ParentA parent) {
super( name, parent );
}
}
@Entity( name = "ChildB" )
public static | ChildA |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/onexception/OrderService.java | {
"start": 1000,
"end": 2096
} | class ____ {
/**
* This method handle our order input and return the order
*
* @param headers the in headers
* @param payload the in payload
* @return the out payload
* @throws OrderFailedException is thrown if the order cannot be processed
*/
public Object handleOrder(@Headers Map<String, Object> headers, @Body String payload)
throws OrderFailedException {
if ("Order: kaboom".equals(payload)) {
throw new OrderFailedException("Cannot order: kaboom");
} else {
headers.put("orderid", "123");
return "Order OK";
}
}
/**
* This method creates the response to the caller if the order could not be processed
*
* @param headers the in headers
* @param payload the in payload
* @return the out payload
*/
public Object orderFailed(@Headers Map<String, Object> headers, @Body String payload) {
headers.put("orderid", "failed");
return "Order ERROR";
}
}
| OrderService |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/asyncprocessing/operators/AbstractAsyncStateStreamOperatorTest.java | {
"start": 27389,
"end": 29462
} | class ____ extends TestOperator {
private final int numAsyncProcesses;
private final CompletableFuture<Void> lastProcessedFuture = new CompletableFuture<>();
private final LinkedList<Integer> processedOrders = new LinkedList<>();
private final LinkedList<Integer> expectedProcessedOrders = new LinkedList<>();
TestOperatorWithMultipleDirectAsyncProcess(
ElementOrder elementOrder, int numAsyncProcesses) {
super(elementOrder);
this.numAsyncProcesses = numAsyncProcesses;
}
@Override
public void processElement(StreamRecord<Tuple2<Integer, String>> element) throws Exception {
for (int i = 0; i < numAsyncProcesses; i++) {
final int finalI = i;
if (i < numAsyncProcesses - 1) {
asyncProcessWithKey(
element.getValue().f0,
() -> {
processed.incrementAndGet();
processedOrders.add(finalI);
});
} else {
asyncProcessWithKey(
element.getValue().f0,
() -> {
processed.incrementAndGet();
processedOrders.add(finalI);
if (!lastProcessedFuture.isDone()) {
lastProcessedFuture.complete(null);
}
});
}
expectedProcessedOrders.add(finalI);
}
}
CompletableFuture<Void> getLastProcessedFuture() {
return lastProcessedFuture;
}
LinkedList<Integer> getProcessedOrders() {
return processedOrders;
}
LinkedList<Integer> getExpectedProcessedOrders() {
return expectedProcessedOrders;
}
}
private static | TestOperatorWithMultipleDirectAsyncProcess |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/mapper/blockloader/docvalues/fn/MvMinBooleansFromDocValuesBlockLoaderTests.java | {
"start": 997,
"end": 3417
} | class ____ extends AbstractBooleansFromDocValuesBlockLoaderTests {
public MvMinBooleansFromDocValuesBlockLoaderTests(boolean blockAtATime, boolean multiValues, boolean missingValues) {
super(blockAtATime, multiValues, missingValues);
}
@Override
protected void innerTest(LeafReaderContext ctx, int mvCount) throws IOException {
var booleansLoader = new BooleansBlockLoader("field");
var mvMinBooleansLoader = new MvMinBooleansBlockLoader("field");
var booleansReader = booleansLoader.reader(ctx);
var mvMinBooleansReader = mvMinBooleansLoader.reader(ctx);
assertThat(mvMinBooleansReader, readerMatcher());
BlockLoader.Docs docs = TestBlock.docs(ctx);
try (
TestBlock doubles = read(booleansLoader, booleansReader, ctx, docs);
TestBlock minDoubles = read(mvMinBooleansLoader, mvMinBooleansReader, ctx, docs);
) {
checkBlocks(doubles, minDoubles);
}
booleansReader = booleansLoader.reader(ctx);
mvMinBooleansReader = mvMinBooleansLoader.reader(ctx);
for (int i = 0; i < ctx.reader().numDocs(); i += 10) {
int[] docsArray = new int[Math.min(10, ctx.reader().numDocs() - i)];
for (int d = 0; d < docsArray.length; d++) {
docsArray[d] = i + d;
}
docs = TestBlock.docs(docsArray);
try (
TestBlock booleans = read(booleansLoader, booleansReader, ctx, docs);
TestBlock minBooleans = read(mvMinBooleansLoader, mvMinBooleansReader, ctx, docs);
) {
checkBlocks(booleans, minBooleans);
}
}
}
private Matcher<Object> readerMatcher() {
if (multiValues) {
return hasToString("MvMinBooleansFromDocValues.Sorted");
}
return hasToString("BooleansFromDocValues.Singleton");
}
private void checkBlocks(TestBlock booleans, TestBlock mvMin) {
for (int i = 0; i < booleans.size(); i++) {
Object v = booleans.get(i);
if (v == null) {
assertThat(mvMin.get(i), nullValue());
continue;
}
Boolean max = (Boolean) (v instanceof List<?> l ? l.stream().allMatch(b -> (Boolean) b) : v);
assertThat(mvMin.get(i), equalTo(max));
}
}
}
| MvMinBooleansFromDocValuesBlockLoaderTests |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/balancer/TestBalancer.java | {
"start": 6879,
"end": 25984
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(TestBalancer.class);
static {
GenericTestUtils.setLogLevel(Balancer.LOG, Level.TRACE);
GenericTestUtils.setLogLevel(Dispatcher.LOG, Level.DEBUG);
}
final static long CAPACITY = 5000L;
final static String RACK0 = "/rack0";
final static String RACK1 = "/rack1";
final static String RACK2 = "/rack2";
final private static String fileName = "/tmp.txt";
final static Path filePath = new Path(fileName);
final static private String username = "balancer";
private static String principal;
private static File baseDir;
private static String keystoresDir;
private static String sslConfDir;
private static MiniKdc kdc;
private static File keytabFile;
private MiniDFSCluster cluster;
private AtomicInteger numGetBlocksCalls;
private AtomicLong startGetBlocksTime;
private AtomicLong endGetBlocksTime;
@BeforeEach
public void setup() {
numGetBlocksCalls = new AtomicInteger(0);
startGetBlocksTime = new AtomicLong(Long.MAX_VALUE);
endGetBlocksTime = new AtomicLong(Long.MIN_VALUE);
}
@AfterEach
public void shutdown() throws Exception {
if (cluster != null) {
cluster.shutdown();
cluster = null;
}
}
ClientProtocol client;
static final long TIMEOUT = 40000L; //msec
static final double CAPACITY_ALLOWED_VARIANCE = 0.005; // 0.5%
static final double BALANCE_ALLOWED_VARIANCE = 0.11; // 10%+delta
static final int DEFAULT_BLOCK_SIZE = 100;
private static final Random r = new Random();
static {
initTestSetup();
}
public static void initTestSetup() {
// do not create id file since it occupies the disk space
NameNodeConnector.setWrite2IdFile(false);
}
static void initConf(Configuration conf) {
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DEFAULT_BLOCK_SIZE);
conf.setInt(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, DEFAULT_BLOCK_SIZE);
conf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1L);
conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 500);
conf.setLong(DFSConfigKeys.DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_KEY,
1L);
SimulatedFSDataset.setFactory(conf);
conf.setLong(DFSConfigKeys.DFS_BALANCER_MOVEDWINWIDTH_KEY, 2000L);
conf.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, 1L);
conf.setInt(DFSConfigKeys.DFS_BALANCER_MAX_NO_MOVE_INTERVAL_KEY, 5*1000);
}
private final ErasureCodingPolicy ecPolicy =
StripedFileTestUtil.getDefaultECPolicy();
private final int dataBlocks = ecPolicy.getNumDataUnits();
private final int parityBlocks = ecPolicy.getNumParityUnits();
private final int groupSize = dataBlocks + parityBlocks;
private final int cellSize = ecPolicy.getCellSize();
private final int stripesPerBlock = 4;
private final int defaultBlockSize = cellSize * stripesPerBlock;
void initConfWithStripe(Configuration conf) {
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, defaultBlockSize);
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_REDUNDANCY_CONSIDERLOAD_KEY,
false);
conf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1L);
SimulatedFSDataset.setFactory(conf);
conf.setLong(DFSConfigKeys.DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_KEY,
1L);
conf.setLong(DFSConfigKeys.DFS_BALANCER_MOVEDWINWIDTH_KEY, 2000L);
conf.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, 1L);
}
static void initSecureConf(Configuration conf) throws Exception {
baseDir = GenericTestUtils.getTestDir(TestBalancer.class.getSimpleName());
FileUtil.fullyDelete(baseDir);
assertTrue(baseDir.mkdirs());
Properties kdcConf = MiniKdc.createConf();
kdc = new MiniKdc(kdcConf, baseDir);
kdc.start();
SecurityUtil.setAuthenticationMethod(
UserGroupInformation.AuthenticationMethod.KERBEROS, conf);
UserGroupInformation.setConfiguration(conf);
KerberosName.resetDefaultRealm();
assertTrue(UserGroupInformation.isSecurityEnabled(),
"Expected configuration to enable security");
keytabFile = new File(baseDir, username + ".keytab");
String keytab = keytabFile.getAbsolutePath();
// Windows will not reverse name lookup "127.0.0.1" to "localhost".
String krbInstance = Path.WINDOWS ? "127.0.0.1" : "localhost";
principal = username + "/" + krbInstance + "@" + kdc.getRealm();
String spnegoPrincipal = "HTTP/" + krbInstance + "@" + kdc.getRealm();
kdc.createPrincipal(keytabFile, username, username + "/" + krbInstance,
"HTTP/" + krbInstance);
conf.set(DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, principal);
conf.set(DFS_NAMENODE_KEYTAB_FILE_KEY, keytab);
conf.set(DFS_DATANODE_KERBEROS_PRINCIPAL_KEY, principal);
conf.set(DFS_DATANODE_KEYTAB_FILE_KEY, keytab);
conf.set(DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, spnegoPrincipal);
conf.setBoolean(DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, true);
conf.set(DFS_DATA_TRANSFER_PROTECTION_KEY, "authentication");
conf.set(DFS_HTTP_POLICY_KEY, HttpConfig.Policy.HTTPS_ONLY.name());
conf.set(DFS_NAMENODE_HTTPS_ADDRESS_KEY, "localhost:0");
conf.set(DFS_DATANODE_HTTPS_ADDRESS_KEY, "localhost:0");
conf.setInt(IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SASL_KEY, 10);
conf.setBoolean(DFS_BALANCER_KEYTAB_ENABLED_KEY, true);
conf.set(DFS_BALANCER_ADDRESS_KEY, "localhost:0");
conf.set(DFS_BALANCER_KEYTAB_FILE_KEY, keytab);
conf.set(DFS_BALANCER_KERBEROS_PRINCIPAL_KEY, principal);
keystoresDir = baseDir.getAbsolutePath();
sslConfDir = KeyStoreTestUtil.getClasspathDir(TestBalancer.class);
KeyStoreTestUtil.setupSSLConfig(keystoresDir, sslConfDir, conf, false);
conf.set(DFS_CLIENT_HTTPS_KEYSTORE_RESOURCE_KEY,
KeyStoreTestUtil.getClientSSLConfigFileName());
conf.set(DFS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY,
KeyStoreTestUtil.getServerSSLConfigFileName());
initConf(conf);
}
@AfterAll
public static void destroy() throws Exception {
if (kdc != null) {
kdc.stop();
FileUtil.fullyDelete(baseDir);
KeyStoreTestUtil.cleanupSSLConfig(keystoresDir, sslConfDir);
}
}
/* create a file with a length of <code>fileLen</code> */
public static void createFile(MiniDFSCluster cluster, Path filePath, long
fileLen,
short replicationFactor, int nnIndex)
throws IOException, InterruptedException, TimeoutException {
FileSystem fs = cluster.getFileSystem(nnIndex);
DFSTestUtil.createFile(fs, filePath, fileLen,
replicationFactor, r.nextLong());
DFSTestUtil.waitReplication(fs, filePath, replicationFactor);
}
/* fill up a cluster with <code>numNodes</code> datanodes
* whose used space to be <code>size</code>
*/
private ExtendedBlock[] generateBlocks(Configuration conf, long size,
short numNodes) throws IOException, InterruptedException, TimeoutException {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numNodes).build();
try {
cluster.waitActive();
client = NameNodeProxies.createProxy(conf, cluster.getFileSystem(0).getUri(),
ClientProtocol.class).getProxy();
short replicationFactor = (short)(numNodes-1);
long fileLen = size/replicationFactor;
createFile(cluster , filePath, fileLen, replicationFactor, 0);
List<LocatedBlock> locatedBlocks = client.
getBlockLocations(fileName, 0, fileLen).getLocatedBlocks();
int numOfBlocks = locatedBlocks.size();
ExtendedBlock[] blocks = new ExtendedBlock[numOfBlocks];
for(int i=0; i<numOfBlocks; i++) {
ExtendedBlock b = locatedBlocks.get(i).getBlock();
blocks[i] = new ExtendedBlock(b.getBlockPoolId(), b.getBlockId(), b
.getNumBytes(), b.getGenerationStamp());
}
return blocks;
} finally {
cluster.shutdown();
}
}
/* Distribute all blocks according to the given distribution */
static Block[][] distributeBlocks(ExtendedBlock[] blocks,
short replicationFactor, final long[] distribution) {
// make a copy
long[] usedSpace = new long[distribution.length];
System.arraycopy(distribution, 0, usedSpace, 0, distribution.length);
List<List<Block>> blockReports =
new ArrayList<List<Block>>(usedSpace.length);
Block[][] results = new Block[usedSpace.length][];
for(int i=0; i<usedSpace.length; i++) {
blockReports.add(new ArrayList<Block>());
}
for(int i=0; i<blocks.length; i++) {
for(int j=0; j<replicationFactor; j++) {
boolean notChosen = true;
while(notChosen) {
int chosenIndex = r.nextInt(usedSpace.length);
if( usedSpace[chosenIndex]>0 ) {
notChosen = false;
blockReports.get(chosenIndex).add(blocks[i].getLocalBlock());
usedSpace[chosenIndex] -= blocks[i].getNumBytes();
}
}
}
}
for(int i=0; i<usedSpace.length; i++) {
List<Block> nodeBlockList = blockReports.get(i);
results[i] = nodeBlockList.toArray(new Block[nodeBlockList.size()]);
}
return results;
}
static long sum(long[] x) {
long s = 0L;
for(long a : x) {
s += a;
}
return s;
}
/* we first start a cluster and fill the cluster up to a certain size.
* then redistribute blocks according the required distribution.
* Afterwards a balancer is running to balance the cluster.
*/
private void testUnevenDistribution(Configuration conf,
long distribution[], long capacities[], String[] racks) throws Exception {
int numDatanodes = distribution.length;
if (capacities.length != numDatanodes || racks.length != numDatanodes) {
throw new IllegalArgumentException("Array length is not the same");
}
// calculate total space that need to be filled
final long totalUsedSpace = sum(distribution);
// fill the cluster
ExtendedBlock[] blocks = generateBlocks(conf, totalUsedSpace,
(short) numDatanodes);
// redistribute blocks
Block[][] blocksDN = distributeBlocks(
blocks, (short)(numDatanodes-1), distribution);
// restart the cluster: do NOT format the cluster
conf.set(DFSConfigKeys.DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY, "0.0f");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes)
.format(false)
.racks(racks)
.simulatedCapacities(capacities)
.build();
cluster.waitActive();
client = NameNodeProxies.createProxy(conf, cluster.getFileSystem(0).getUri(),
ClientProtocol.class).getProxy();
for(int i = 0; i < blocksDN.length; i++)
cluster.injectBlocks(i, Arrays.asList(blocksDN[i]), null);
final long totalCapacity = sum(capacities);
runBalancer(conf, totalUsedSpace, totalCapacity);
cluster.shutdown();
}
/**
* Wait until heartbeat gives expected results, within CAPACITY_ALLOWED_VARIANCE,
* summed over all nodes. Times out after TIMEOUT msec.
* @param expectedUsedSpace
* @param expectedTotalSpace
* @throws IOException - if getStats() fails
* @throws TimeoutException
*/
static void waitForHeartBeat(long expectedUsedSpace,
long expectedTotalSpace, ClientProtocol client, MiniDFSCluster cluster)
throws IOException, TimeoutException {
long timeout = TIMEOUT;
long failtime = (timeout <= 0L) ? Long.MAX_VALUE
: Time.monotonicNow() + timeout;
while (true) {
long[] status = client.getStats();
double totalSpaceVariance = Math.abs((double)status[0] - expectedTotalSpace)
/ expectedTotalSpace;
double usedSpaceVariance = Math.abs((double)status[1] - expectedUsedSpace)
/ expectedUsedSpace;
if (totalSpaceVariance < CAPACITY_ALLOWED_VARIANCE
&& usedSpaceVariance < CAPACITY_ALLOWED_VARIANCE)
break; //done
if (Time.monotonicNow() > failtime) {
throw new TimeoutException("Cluster failed to reached expected values of "
+ "totalSpace (current: " + status[0]
+ ", expected: " + expectedTotalSpace
+ "), or usedSpace (current: " + status[1]
+ ", expected: " + expectedUsedSpace
+ "), in more than " + timeout + " msec.");
}
try {
Thread.sleep(100L);
} catch(InterruptedException ignored) {
}
}
}
/**
* Wait until balanced: each datanode gives utilization within
* BALANCE_ALLOWED_VARIANCE of average
* @throws IOException
* @throws TimeoutException
*/
static void waitForBalancer(long totalUsedSpace, long totalCapacity,
ClientProtocol client, MiniDFSCluster cluster, BalancerParameters p)
throws IOException, TimeoutException {
waitForBalancer(totalUsedSpace, totalCapacity, client, cluster, p, 0);
}
/**
* Wait until balanced: each datanode gives utilization within
* BALANCE_ALLOWED_VARIANCE of average
* @throws IOException
* @throws TimeoutException
*/
static void waitForBalancer(long totalUsedSpace, long totalCapacity,
ClientProtocol client, MiniDFSCluster cluster, BalancerParameters p,
int expectedExcludedNodes) throws IOException, TimeoutException {
waitForBalancer(totalUsedSpace, totalCapacity, client,
cluster, p, expectedExcludedNodes, true);
}
/**
* Wait until balanced: each datanode gives utilization within.
* BALANCE_ALLOWED_VARIANCE of average
* @throws IOException
* @throws TimeoutException
*/
static void waitForBalancer(long totalUsedSpace, long totalCapacity,
ClientProtocol client, MiniDFSCluster cluster, BalancerParameters p,
int expectedExcludedNodes, boolean checkExcludeNodesUtilization)
throws IOException, TimeoutException {
long timeout = TIMEOUT;
long failtime = (timeout <= 0L) ? Long.MAX_VALUE
: Time.monotonicNow() + timeout;
if (!p.getIncludedNodes().isEmpty()) {
totalCapacity = p.getIncludedNodes().size() * CAPACITY;
}
if (!p.getExcludedNodes().isEmpty()) {
totalCapacity -= p.getExcludedNodes().size() * CAPACITY;
}
if (!p.getExcludedTargetNodes().isEmpty()) {
totalCapacity -= p.getExcludedTargetNodes().size() * CAPACITY;
}
final double avgUtilization = ((double)totalUsedSpace) / totalCapacity;
boolean balanced;
do {
DatanodeInfo[] datanodeReport =
client.getDatanodeReport(DatanodeReportType.ALL);
assertEquals(datanodeReport.length, cluster.getDataNodes().size());
balanced = true;
int actualExcludedNodeCount = 0;
for (DatanodeInfo datanode : datanodeReport) {
double nodeUtilization =
((double) datanode.getDfsUsed() + datanode.getNonDfsUsed()) /
datanode.getCapacity();
if (Dispatcher.Util.isExcluded(p.getExcludedNodes(), datanode)) {
if (checkExcludeNodesUtilization) {
assertTrue(nodeUtilization == 0);
}
actualExcludedNodeCount++;
continue;
}
if (!Dispatcher.Util.isIncluded(p.getIncludedNodes(), datanode)) {
assertTrue(nodeUtilization == 0);
actualExcludedNodeCount++;
continue;
}
if (Math.abs(avgUtilization - nodeUtilization) > BALANCE_ALLOWED_VARIANCE) {
balanced = false;
if (Time.monotonicNow() > failtime) {
throw new TimeoutException(
"Rebalancing expected avg utilization to become "
+ avgUtilization + ", but on datanode " + datanode
+ " it remains at " + nodeUtilization
+ " after more than " + TIMEOUT + " msec.");
}
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
break;
}
}
assertEquals(expectedExcludedNodes, actualExcludedNodeCount);
} while (!balanced);
}
/**
* Wait until balanced: each datanode gives utilization within.
* Used when testing for included / excluded target and source nodes.
* BALANCE_ALLOWED_VARIANCE of average
* @throws IOException
* @throws TimeoutException
*/
static void waitForBalancer(long totalUsedSpace, long totalCapacity,
ClientProtocol client, MiniDFSCluster cluster, BalancerParameters p,
int expectedExcludedSourceNodes, int expectedExcludedTargetNodes)
throws IOException, TimeoutException {
long timeout = TIMEOUT;
long failtime = (timeout <= 0L) ? Long.MAX_VALUE
: Time.monotonicNow() + timeout;
if (!p.getExcludedTargetNodes().isEmpty()) {
totalCapacity -= p.getExcludedTargetNodes().size() * CAPACITY;
}
final double avgUtilization = ((double)totalUsedSpace) / totalCapacity;
boolean balanced;
do {
DatanodeInfo[] datanodeReport =
client.getDatanodeReport(DatanodeReportType.ALL);
assertEquals(datanodeReport.length, cluster.getDataNodes().size());
balanced = true;
int actualExcludedSourceNodeCount = 0;
int actualExcludedTargetNodeCount = 0;
for (DatanodeInfo datanode : datanodeReport) {
double nodeUtilization =
((double) datanode.getDfsUsed() + datanode.getNonDfsUsed()) /
datanode.getCapacity();
if(Dispatcher.Util.isExcluded(p.getExcludedTargetNodes(), datanode)) {
actualExcludedTargetNodeCount++;
}
if(!Dispatcher.Util.isIncluded(p.getTargetNodes(), datanode)) {
actualExcludedTargetNodeCount++;
}
if(Dispatcher.Util.isExcluded(p.getExcludedSourceNodes(), datanode)) {
actualExcludedSourceNodeCount++;
}
if(!Dispatcher.Util.isIncluded(p.getSourceNodes(), datanode)) {
actualExcludedSourceNodeCount++;
}
if (Math.abs(avgUtilization - nodeUtilization) > BALANCE_ALLOWED_VARIANCE) {
balanced = false;
if (Time.monotonicNow() > failtime) {
throw new TimeoutException(
"Rebalancing expected avg utilization to become "
+ avgUtilization + ", but on datanode " + datanode
+ " it remains at " + nodeUtilization
+ " after more than " + TIMEOUT + " msec.");
}
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
break;
}
}
assertEquals(expectedExcludedSourceNodes, actualExcludedSourceNodeCount);
assertEquals(expectedExcludedTargetNodes, actualExcludedTargetNodeCount);
} while (!balanced);
}
String long2String(long[] array) {
if (array.length == 0) {
return "<empty>";
}
StringBuilder b = new StringBuilder("[").append(array[0]);
for(int i = 1; i < array.length; i++) {
b.append(", ").append(array[i]);
}
return b.append("]").toString();
}
/**
* Class which contains information about the
* new nodes to be added to the cluster for balancing.
*/
static abstract | TestBalancer |
java | apache__camel | core/camel-base/src/main/java/org/apache/camel/impl/event/CamelContextRoutesStoppingEvent.java | {
"start": 951,
"end": 1389
} | class ____ extends AbstractContextEvent
implements CamelEvent.CamelContextRoutesStoppingEvent {
private static final @Serial long serialVersionUID = -1120225323715688981L;
public CamelContextRoutesStoppingEvent(CamelContext source) {
super(source);
}
@Override
public String toString() {
return "Stopping routes on CamelContext: " + getContext().getName();
}
}
| CamelContextRoutesStoppingEvent |
java | apache__camel | components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpSendDynamicAwareTest.java | {
"start": 1100,
"end": 2607
} | class ____ extends BaseNettyTest {
@Test
public void testDynamicAware() {
String out = fluentTemplate.to("direct:moes").withHeader("drink", "beer").request(String.class);
assertEquals("Drinking beer", out);
out = fluentTemplate.to("direct:joes").withHeader("drink", "wine").request(String.class);
assertEquals("Drinking wine", out);
// and there should only be one http endpoint as they are both on same host
boolean found = context.getEndpointRegistry()
.containsKey("netty-http://http://localhost:" + getPort() + "?throwExceptionOnFailure=false");
assertTrue(found, "Should find static uri");
// we only have 2xdirect and 2xnetty-http
assertEquals(4, context.getEndpointRegistry().size());
}
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:moes")
.toD("netty-http:http://localhost:{{port}}/moes?throwExceptionOnFailure=false&drink=${header.drink}");
from("direct:joes")
.toD("netty-http:http://localhost:{{port}}/joes?throwExceptionOnFailure=false&drink=${header.drink}");
from("netty-http:http://localhost:{{port}}/?matchOnUriPrefix=true")
.transform().simple("Drinking ${header.drink[0]}");
}
};
}
}
| NettyHttpSendDynamicAwareTest |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringScriptExternalTest.java | {
"start": 1158,
"end": 1835
} | class ____ extends ContextTestSupport {
protected MockEndpoint resultEndpoint;
@Test
public void testScriptExternal() throws Exception {
resultEndpoint.expectedBodiesReceived("Hello");
sendBody("direct:start", "Hello");
resultEndpoint.assertIsSatisfied();
}
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
resultEndpoint = getMockEndpoint("mock:result");
}
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/processor/script-external.xml");
}
}
| SpringScriptExternalTest |
java | elastic__elasticsearch | build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/release/UpdateVersionsTaskTests.java | {
"start": 4495,
"end": 5181
} | class ____ {
public static final Version V_8_10_0 = new Version(8_10_00_99);
public static final Version V_8_10_1 = new Version(8_10_01_99);
public static final Version V_8_11_0 = new Version(8_11_00_99);
public static final Version CURRENT = V_8_11_0;
}""";
CompilationUnit unit = StaticJavaParser.parse(versionJava);
var newUnit = UpdateVersionsTask.removeVersionConstant(unit, Version.fromString("8.10.2"));
assertThat(newUnit.isPresent(), is(false));
}
@Test
public void removeVersion_versionIsCurrent() {
final String versionJava = """
public | Version |
java | jhy__jsoup | src/test/java/org/jsoup/nodes/DataNodeTest.java | {
"start": 174,
"end": 3116
} | class ____ {
static QuietAppendable appendable() {
return QuietAppendable.wrap(new StringBuilder());
}
@Test
public void xmlOutputScriptWithCData() {
DataNode node = new DataNode("//<![CDATA[\nscript && <> data]]>");
node.parentNode = new Element("script");
QuietAppendable accum = appendable();
node.outerHtmlHead(accum, new Document.OutputSettings().syntax(Document.OutputSettings.Syntax.xml));
assertEquals("//<![CDATA[\nscript && <> data]]>", accum.toString());
}
@Test
public void xmlOutputScriptWithoutCData() {
DataNode node = new DataNode("script && <> data");
node.parentNode = new Element("script");
QuietAppendable accum = appendable();
node.outerHtmlHead(accum, new Document.OutputSettings().syntax(Document.OutputSettings.Syntax.xml));
assertEquals("//<![CDATA[\nscript && <> data\n//]]>", accum.toString());
}
@Test
public void xmlOutputStyleWithCData() {
DataNode node = new DataNode("/*<![CDATA[*/\nstyle && <> data]]>");
node.parentNode = new Element("style");
QuietAppendable accum = appendable();
node.outerHtmlHead(accum, new Document.OutputSettings().syntax(Document.OutputSettings.Syntax.xml));
assertEquals("/*<![CDATA[*/\nstyle && <> data]]>", accum.toString());
}
@Test
public void xmlOutputStyleWithoutCData() {
DataNode node = new DataNode("style && <> data");
node.parentNode = new Element("style");
QuietAppendable accum = appendable();
node.outerHtmlHead(accum, new Document.OutputSettings().syntax(Document.OutputSettings.Syntax.xml));
assertEquals("/*<![CDATA[*/\nstyle && <> data\n/*]]>*/", accum.toString());
}
@Test
public void xmlOutputOtherWithCData() {
DataNode node = new DataNode("<![CDATA[other && <> data]]>");
node.parentNode = new Element("other");
QuietAppendable accum = appendable();
node.outerHtmlHead(accum, new Document.OutputSettings().syntax(Document.OutputSettings.Syntax.xml));
assertEquals("<![CDATA[other && <> data]]>", accum.toString());
}
@Test
public void xmlOutputOtherWithoutCData() {
DataNode node = new DataNode("other && <> data");
node.parentNode = new Element("other");
QuietAppendable accum = appendable();
node.outerHtmlHead(accum, new Document.OutputSettings().syntax(Document.OutputSettings.Syntax.xml));
assertEquals("<![CDATA[other && <> data]]>", accum.toString());
}
@Test
public void xmlOutputOrphanWithoutCData() {
DataNode node = new DataNode("other && <> data");
QuietAppendable accum = appendable();
node.outerHtmlHead(accum, new Document.OutputSettings().syntax(Document.OutputSettings.Syntax.xml));
assertEquals("<![CDATA[other && <> data]]>", accum.toString());
}
}
| DataNodeTest |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng2926PluginPrefixOrderTest.java | {
"start": 1034,
"end": 3514
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that when resolving plugin prefixes the group org.apache.maven.plugins is searched before
* org.codehaus.mojo and that custom groups from the settings are searched before these standard ones.
*
* @throws Exception in case of failure
*/
@Test
public void testitMNG2926() throws Exception {
File testDir = extractResources("/mng-2926");
Verifier verifier;
verifier = newVerifier(testDir.getAbsolutePath());
verifier.deleteArtifacts("org.apache.maven.its.mng2926");
verifier.deleteArtifacts("org.apache.maven.plugins", "mng-2926", "0.1");
verifier.deleteArtifacts("org.apache.maven.plugins", "mng-2926", "0.1");
new File(verifier.getArtifactMetadataPath(
"org.apache.maven.plugins", null, null, "maven-metadata-maven-core-it.xml"))
.delete();
new File(verifier.getArtifactMetadataPath("org.apache.maven.plugins", null, null, "resolver-status.properties"))
.delete();
verifier.deleteArtifacts("org.codehaus.mojo", "mng-2926", "0.1");
verifier.deleteArtifacts("org.codehaus.mojo", "mng-2926", "0.1");
new File(verifier.getArtifactMetadataPath("org.codehaus.mojo", null, null, "maven-metadata-maven-core-it.xml"))
.delete();
new File(verifier.getArtifactMetadataPath("org.codehaus.mojo", null, null, "resolver-status.properties"))
.delete();
verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.setLogFileName("log-default.txt");
verifier.filterFile("settings-default-template.xml", "settings-default.xml");
verifier.addCliArgument("--settings");
verifier.addCliArgument("settings-default.xml");
verifier.addCliArgument("mng-2926:apache");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.setLogFileName("log-custom.txt");
verifier.filterFile("settings-custom-template.xml", "settings-custom.xml");
verifier.addCliArgument("--settings");
verifier.addCliArgument("settings-custom.xml");
verifier.addCliArgument("mng-2926:custom");
verifier.execute();
verifier.verifyErrorFreeLog();
}
}
| MavenITmng2926PluginPrefixOrderTest |
java | quarkusio__quarkus | extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/HibernateOrmRuntimeConfigPersistenceUnit.java | {
"start": 7942,
"end": 8761
} | interface ____ {
/**
* Select whether the database schema DDL files are generated or not.
*
* Accepted values: `none`, `create`, `drop-and-create`, `drop`, `update`, `validate`.
*/
@WithParentName
@WithDefault("none")
@WithConverter(TrimmedStringConverter.class)
String generation();
/**
* Filename or URL where the database create DDL file should be generated.
*/
Optional<@WithConverter(TrimmedStringConverter.class) String> createTarget();
/**
* Filename or URL where the database drop DDL file should be generated.
*/
Optional<@WithConverter(TrimmedStringConverter.class) String> dropTarget();
}
@ConfigGroup
| HibernateOrmConfigPersistenceUnitScriptGeneration |
java | google__dagger | javatests/dagger/hilt/android/AndroidEntryPointBaseClassTest.java | {
"start": 3458,
"end": 3543
} | class ____ extends S {}
@AndroidEntryPoint(ComponentActivity.class)
public static | SS |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/dancing/Pentomino.java | {
"start": 5520,
"end": 7232
} | enum ____ {UPPER_LEFT, MID_X, MID_Y, CENTER}
/**
* Find whether the solution has the x in the upper left quadrant, the
* x-midline, the y-midline or in the center.
* @param names the solution to check
* @return the catagory of the solution
*/
public SolutionCategory getCategory(List<List<ColumnName>> names) {
Piece xPiece = null;
// find the "x" piece
for(Piece p: pieces) {
if ("x".equals(p.name)) {
xPiece = p;
break;
}
}
// find the row containing the "x"
for(List<ColumnName> row: names) {
if (row.contains(xPiece)) {
// figure out where the "x" is located
int low_x = width;
int high_x = 0;
int low_y = height;
int high_y = 0;
for(ColumnName col: row) {
if (col instanceof Point) {
int x = ((Point) col).x;
int y = ((Point) col).y;
if (x < low_x) {
low_x = x;
}
if (x > high_x) {
high_x = x;
}
if (y < low_y) {
low_y = y;
}
if (y > high_y) {
high_y = y;
}
}
}
boolean mid_x = (low_x + high_x == width - 1);
boolean mid_y = (low_y + high_y == height - 1);
if (mid_x && mid_y) {
return SolutionCategory.CENTER;
} else if (mid_x) {
return SolutionCategory.MID_X;
} else if (mid_y) {
return SolutionCategory.MID_Y;
}
break;
}
}
return SolutionCategory.UPPER_LEFT;
}
/**
* A solution printer that just writes the solution to stdout.
*/
private static | SolutionCategory |
java | google__dagger | javatests/dagger/internal/codegen/MissingBindingValidationTest.java | {
"start": 85523,
"end": 86174
} | interface ____ {}");
CompilerTests.daggerCompiler(
parent, child, grandchild, parentModule, childModule, grandchildModule, foo, bar, qux)
.withProcessingOptions(compilerMode.processorOptions())
.compile(subject -> subject.hasErrorCount(0));
}
// Regression test for b/367426609
@Test
public void failsWithMissingBindingInGrandchild_dependencyTracePresent() {
Source parent =
CompilerTests.javaSource(
"test.Parent",
"package test;",
"",
"import dagger.Component;",
"",
"@Component(modules = ParentModule.class)",
" | Qux |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/MappedSuperclassAttributeInMultipleSubtypesTest.java | {
"start": 1296,
"end": 3471
} | class ____ {
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final BasicEntity basicEntity = new BasicEntity( 1, "basic" );
session.persist( basicEntity );
session.persist( new ChildOne( 1L, "test", 1, basicEntity ) );
session.persist( new ChildTwo( 2L, "test", 1D, basicEntity ) );
} );
}
@AfterAll
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction( session -> {
session.createMutationQuery( "delete from BaseEntity" ).executeUpdate();
session.createMutationQuery( "delete from BasicEntity" ).executeUpdate();
} );
}
@Test
public void testSameTypeAttribute(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final List<BaseEntity> resultList = session.createQuery(
"from BaseEntity e where e.stringProp = 'test'",
BaseEntity.class
).getResultList();
assertThat( resultList ).hasSize( 2 );
assertThat( resultList.stream().map( BaseEntity::getId ) ).contains( 1L, 2L );
} );
}
@Test
public void testDifferentTypeAttribute(SessionFactoryScope scope) {
scope.inTransaction( session -> {
try {
session.createQuery(
"from BaseEntity e where e.otherProp = 1",
BaseEntity.class
).getResultList();
fail( "This shouldn't work since the attribute is defined with different types" );
}
catch (Exception e) {
final Throwable cause = e.getCause();
assertThat( cause ).isInstanceOf( PathException.class );
assertThat( cause.getMessage() ).contains( "Could not resolve attribute 'otherProp'" );
}
} );
}
@Test
public void testToOneAttribute(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final BasicEntity basicEntity = session.find( BasicEntity.class, 1 );
final List<BaseEntity> resultList = session.createQuery(
"from BaseEntity e where e.toOneProp = :be",
BaseEntity.class
).setParameter( "be", basicEntity ).getResultList();
assertThat( resultList ).hasSize( 2 );
assertThat( resultList.stream().map( BaseEntity::getId ) ).contains( 1L, 2L );
} );
}
@Entity( name = "BaseEntity" )
public static | MappedSuperclassAttributeInMultipleSubtypesTest |
java | micronaut-projects__micronaut-core | inject-java/src/main/java/io/micronaut/annotation/processing/PostponeToNextRoundException.java | {
"start": 955,
"end": 2290
} | class ____ extends RuntimeException {
private final transient Object errorElement;
private final String path;
/**
* @param originatingElement Teh originating element
* @param path The originating element path
*/
public PostponeToNextRoundException(Object originatingElement, String path) {
this.errorElement = originatingElement;
this.path = path;
}
public Object getErrorElement() {
return errorElement;
}
public @Nullable Element getNativeErrorElement() {
return resolvedFailedElement(errorElement);
}
public static Element resolvedFailedElement(Object errorElement) {
Element failedElement;
if (errorElement instanceof Element el) {
failedElement = el;
} else if (errorElement instanceof JavaNativeElement jne) {
failedElement = jne.element();
} else if (errorElement instanceof AbstractJavaElement aje) {
failedElement = aje.getNativeType().element();
} else {
failedElement = null;
}
return failedElement;
}
public String getPath() {
return path;
}
@Override
public synchronized Throwable fillInStackTrace() {
// no-op: flow control exception
return this;
}
}
| PostponeToNextRoundException |
java | quarkusio__quarkus | integration-tests/main/src/main/java/io/quarkus/it/config/MicroProfileConfigResource.java | {
"start": 496,
"end": 1295
} | class ____ {
@ConfigProperty(name = "microprofile.custom.value")
MicroProfileCustomValue value;
@ConfigProperty(name = "microprofile.cidr-address")
CidrAddress cidrAddress;
@Inject
Config config;
@GET
@Path("/get-property-names")
public String getPropertyNames() throws Exception {
if (!config.getPropertyNames().iterator().hasNext()) {
return "No config property found. Some were expected.";
}
return "OK";
}
@GET
@Path("/get-custom-value")
public String getCustomValue() {
return Integer.toString(value.getNumber());
}
@GET
@Path("/get-cidr-address")
public String getCidrAddress() {
return cidrAddress.getNetworkAddress().getHostAddress();
}
}
| MicroProfileConfigResource |
java | processing__processing4 | java/src/processing/mode/java/AutoFormat.java | {
"start": 15164,
"end": 24436
} | class ____ ends
if (s_if_lev.length == curlyLvl) {
s_if_lev = PApplet.expand(s_if_lev);
s_if_flg = PApplet.expand(s_if_flg);
}
s_if_lev[curlyLvl] = if_lev;
s_if_flg[curlyLvl] = if_flg;
if_lev = 0;
if_flg = false;
curlyLvl++;
if (startFlag && p_flg[level] != 0) {
p_flg[level]--;
tabs--;
}
trimRight(buf);
if (buf.length() > 0 || (result.length() > 0 &&
!Character.isWhitespace(result.charAt(result.length() - 1)))) {
buf.append(" ");
}
buf.append(c);
writeIndentedLine();
readForNewLine();
writeIndentedLine();
result.append('\n');
tabs++;
startFlag = true;
if (p_flg[level] > 0) {
ind[level] = true;
level++;
s_level[level] = curlyLvl;
}
break;
case '}':
if (arrayLevel >= 0) {
// Even less fancy. Note that }s cannot end array behaviour;
// a semicolon is needed.
if (arrayLevel > 0) arrayLevel--;
if (arrayIndent > arrayLevel) arrayIndent = arrayLevel;
buf.append(c);
break;
}
// In a simple enum, there's not necessarily a `;` to end the statement.
inStatementFlag = false;
curlyLvl--;
if (curlyLvl < 0) {
curlyLvl = 0;
buf.append(c);
writeIndentedLine();
} else {
if_lev = s_if_lev[curlyLvl] - 1;
if (if_lev < 0) if_lev = 0;
if_levSafe();
if_flg = s_if_flg[curlyLvl];
trimRight(buf);
writeIndentedLine();
tabs--;
trimRight(result);
result.append('\n');
overflowFlag = false; // Would normally be done in writeIndentedLine.
printIndentation();
result.append(c);
if (peek() == ';') result.append(nextChar());
// doWhileFlags contains a TRUE if and only if the
// corresponding { was preceeded (bufEnds) by "do".
// Just checking for while would fail on if(){} while(){}.
if (doWhileFlags.empty() || !doWhileFlags.pop().booleanValue()
|| !new String(chars, pos+1, chars.length-pos-1).trim().startsWith("while")) {
readForNewLine();
writeIndentedLine();
result.append('\n');
startFlag = true;
} else {
// Correct spacing in "} while".
result.append(' ');
advanceToNonSpace(true);
startFlag = false;
}
if (curlyLvl < s_level[level] && level > 0) level--;
if (ind[level]) {
tabs -= p_flg[level];
p_flg[level] = 0;
ind[level] = false;
}
}
break;
case '"':
case 'β':
case 'β':
case '\'':
case 'β':
case 'β':
inStatementFlag = true;
char realQuote = c;
if (c == 'β' || c == 'β') realQuote = '"';
if (c == 'β' || c == 'β') realQuote = '\'';
buf.append(realQuote);
char otherQuote = c;
if (c == 'β') otherQuote = 'β';
if (c == 'β') otherQuote = 'β';
if (c == 'β') otherQuote = 'β';
if (c == 'β') otherQuote = 'β';
char cc = nextChar();
// In a proper string, all the quotes tested are c. In a curly-quoted
// string, there are three possible end quotes: c, its reverse, and
// the correct straight quote.
while (!EOF && cc != otherQuote && cc != realQuote && cc != c) {
buf.append(cc);
if (cc == '\\') {
buf.append(cc = nextChar());
}
// Syntax error: unterminated string. Leave \n in nextChar, so it
// feeds back into the loop.
if (peek() == '\n') break;
cc = nextChar();
}
if (cc == otherQuote || cc == realQuote || cc == c) {
buf.append(realQuote);
if (readForNewLine()) {
// push a newline into the stream
chars[pos--] = '\n';
}
} else {
// We've had a syntax error if the string wasn't terminated by EOL/
// EOF, just abandon this statement.
inStatementFlag = false;
}
break;
case ';':
if (forFlag) {
// This is like a comma.
trimRight(buf);
buf.append("; ");
// Not non-whitespace: allow \n.
advanceToNonSpace(false);
break;
}
buf.append(c);
inStatementFlag = false;
writeIndentedLine();
if (p_flg[level] > 0 && !ind[level]) {
tabs -= p_flg[level];
p_flg[level] = 0;
}
readForNewLine();
writeIndentedLine();
result.append("\n");
startFlag = true;
// Array behaviour ends at the end of a statement.
arrayLevel = -1;
if (if_lev > 0) {
if (if_flg) {
if_lev--;
if_flg = false;
} else {
if_lev = 0;
}
}
break;
case '\\':
buf.append(c);
buf.append(nextChar());
break;
case '?':
conditionalLevel++;
buf.append(c);
break;
case ':':
// Java 8 :: operator.
if (peek() == ':') {
buf.append(c).append(nextChar());
break;
}
// End a?b:c structures.
else if (conditionalLevel > 0) {
conditionalLevel--;
buf.append(c);
break;
}
else if (forFlag) {
trimRight(buf);
buf.append(" : ");
// Not to non-whitespace: allow \n.
advanceToNonSpace(false);
break;
}
buf.append(c);
inStatementFlag = false;
arrayLevel = -1; // Unlikely to be needed; just in case.
// Same format for case, default, and other labels.
if (tabs > 0) {
tabs--;
writeIndentedLine();
tabs++;
} else {
writeIndentedLine();
}
readForNewLine();
writeIndentedLine();
result.append('\n');
startFlag = true;
break;
case '/':
final char next = peek();
if (next == '/') {
// call nextChar to move on.
buf.append(c).append(nextChar());
handleSingleLineComment();
result.append("\n");
} else if (next == '*') {
if (buf.length() > 0) {
writeIndentedLine();
}
buf.append(c).append(nextChar());
handleMultiLineComment();
} else {
buf.append(c);
}
break;
case ')':
parenLevel--;
// If we're further back than the start of a for loop, we've
// left it.
if (forFlag && forParenthLevel > parenLevel) forFlag = false;
if (parenLevel < 0) parenLevel = 0;
buf.append(c);
boolean wasIfEtc = !ifWhileForFlags.empty() && ifWhileForFlags.pop().booleanValue();
if (wasIfEtc) {
inStatementFlag = false;
arrayLevel = -1; // This is important as it allows arrays in if statements.
}
writeIndentedLine();
// Short-circuiting means readForNewLine is only called for if/while/for;
// this is important.
if (wasIfEtc && readForNewLine()) {
chars[pos] = '\n';
pos--; // Make nextChar() return the new '\n'.
if (parenLevel == 0) {
p_flg[level]++;
tabs++;
ind[level] = false;
}
}
break;
case '(':
final boolean isFor = bufEnds("for");
final boolean isIf = bufEnds("if");
if (isFor || isIf || bufEnds("while")) {
if (!Character.isWhitespace(buf.charAt(buf.length() - 1))) {
buf.append(' ');
}
ifWhileForFlags.push(true);
} else {
ifWhileForFlags.push(false);
}
buf.append(c);
parenLevel++;
// isFor says "Is it the start of a for?". If it is, we set forFlag and
// forParenthLevel. If it is not parenth_lvl was incremented above and
// that's it.
if (isFor && !forFlag) {
forParenthLevel = parenLevel;
forFlag = true;
} else if (isIf) {
writeIndentedLine();
s_tabs[curlyLvl][if_lev] = tabs;
sp_flg[curlyLvl][if_lev] = p_flg[level];
s_ind[curlyLvl][if_lev] = ind[level];
if_lev++;
if_levSafe();
if_flg = true;
}
} // end switch
} // end while not EOF
if (buf.length() > 0) writeIndentedLine();
final String formatted = simpleRegexCleanup(result.toString());
return formatted.equals(cleanText) ? source : formatted;
}
/**
* Make minor regex-based find / replace changes to execute simple fixes to limited artifacts.
*
* @param result The code to format.
* @return The formatted code.
*/
static private String simpleRegexCleanup(String result) {
return result.replaceAll("([^ \n]+) +\n", "$1\n"); // Remove trail whitespace
}
}
| declaration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.