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 | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/LongTerms.java | {
"start": 1548,
"end": 10207
} | class ____ extends InternalTerms.Bucket<Bucket> {
long term;
public Bucket(
long term,
long docCount,
InternalAggregations aggregations,
boolean showDocCountError,
long docCountError,
DocValueFormat format
) {
super(docCount, aggregations, showDocCountError, docCountError, format);
this.term = term;
}
/**
* Read from a stream.
*/
public Bucket(StreamInput in, DocValueFormat format, boolean showDocCountError) throws IOException {
super(in, format, showDocCountError);
term = in.readLong();
}
@Override
protected void writeTermTo(StreamOutput out) throws IOException {
out.writeLong(term);
}
@Override
public String getKeyAsString() {
return format.format(term).toString();
}
@Override
public Object getKey() {
if (format == DocValueFormat.UNSIGNED_LONG_SHIFTED) {
return format.format(term);
} else {
return term;
}
}
@Override
public Number getKeyAsNumber() {
if (format == DocValueFormat.UNSIGNED_LONG_SHIFTED) {
return (Number) format.format(term);
} else {
return term;
}
}
@Override
public int compareKey(Bucket other) {
return Long.compare(term, other.term);
}
@Override
protected final XContentBuilder keyToXContent(XContentBuilder builder) throws IOException {
if (format == DocValueFormat.UNSIGNED_LONG_SHIFTED) {
builder.field(CommonFields.KEY.getPreferredName(), format.format(term));
} else {
builder.field(CommonFields.KEY.getPreferredName(), term);
}
if (format != DocValueFormat.RAW && format != DocValueFormat.UNSIGNED_LONG_SHIFTED) {
builder.field(CommonFields.KEY_AS_STRING.getPreferredName(), format.format(term).toString());
}
return builder;
}
@Override
public boolean equals(Object obj) {
return super.equals(obj) && Objects.equals(term, ((Bucket) obj).term);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), term);
}
}
public LongTerms(
String name,
BucketOrder reduceOrder,
BucketOrder order,
int requiredSize,
long minDocCount,
Map<String, Object> metadata,
DocValueFormat format,
int shardSize,
boolean showTermDocCountError,
long otherDocCount,
List<Bucket> buckets,
Long docCountError
) {
super(
name,
reduceOrder,
order,
requiredSize,
minDocCount,
metadata,
format,
shardSize,
showTermDocCountError,
otherDocCount,
buckets,
docCountError
);
}
/**
* Read from a stream.
*/
public LongTerms(StreamInput in) throws IOException {
super(in, Bucket::new);
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public LongTerms create(List<Bucket> buckets) {
return new LongTerms(
name,
reduceOrder,
order,
requiredSize,
minDocCount,
metadata,
format,
shardSize,
showTermDocCountError,
otherDocCount,
buckets,
docCountError
);
}
@Override
public Bucket createBucket(InternalAggregations aggregations, Bucket prototype) {
return new Bucket(
prototype.term,
prototype.docCount,
aggregations,
showTermDocCountError,
prototype.getDocCountError(),
prototype.format
);
}
@Override
protected LongTerms create(String name, List<Bucket> buckets, BucketOrder reduceOrder, long docCountError, long otherDocCount) {
return new LongTerms(
name,
reduceOrder,
order,
requiredSize,
minDocCount,
getMetadata(),
format,
shardSize,
showTermDocCountError,
otherDocCount,
buckets,
docCountError
);
}
@Override
protected AggregatorReducer getLeaderReducer(AggregationReduceContext reduceContext, int size) {
final Predicate<DocValueFormat> needsPromoting;
if (format == DocValueFormat.RAW) {
needsPromoting = docFormat -> docFormat == DocValueFormat.UNSIGNED_LONG_SHIFTED;
} else if (format == DocValueFormat.UNSIGNED_LONG_SHIFTED) {
needsPromoting = docFormat -> docFormat == DocValueFormat.RAW;
} else {
needsPromoting = Predicates.never();
}
return new AggregatorReducer() {
private List<InternalAggregation> aggregations = new ArrayList<>(size);
private boolean isPromotedToDouble = false;
@Override
public void accept(InternalAggregation aggregation) {
if (aggregation instanceof DoubleTerms doubleTerms) {
if (isPromotedToDouble == false) {
promoteToDouble(aggregations);
isPromotedToDouble = true;
}
aggregations.add(doubleTerms);
} else if (aggregation instanceof LongTerms longTerms) {
if (isPromotedToDouble || needsPromoting.test(longTerms.format)) {
if (isPromotedToDouble == false) {
promoteToDouble(aggregations);
isPromotedToDouble = true;
}
aggregations.add(LongTerms.convertLongTermsToDouble(longTerms, format));
} else {
aggregations.add(aggregation);
}
}
}
private void promoteToDouble(List<InternalAggregation> aggregations) {
aggregations.replaceAll(aggregation -> LongTerms.convertLongTermsToDouble((LongTerms) aggregation, format));
}
@Override
public InternalAggregation get() {
try (
AggregatorReducer processor = ((AbstractInternalTerms<?, ?>) aggregations.get(0)).termsAggregationReducer(
reduceContext,
size
)
) {
aggregations.forEach(processor::accept);
aggregations = null; // release memory
return processor.get();
}
}
};
}
@Override
protected Bucket createBucket(long docCount, InternalAggregations aggs, long docCountError, LongTerms.Bucket prototype) {
return new Bucket(prototype.term, docCount, aggs, showTermDocCountError, docCountError, format);
}
/**
* Converts a {@link LongTerms} into a {@link DoubleTerms}, returning the value of the specified long terms as doubles.
*/
public static DoubleTerms convertLongTermsToDouble(LongTerms longTerms, DocValueFormat decimalFormat) {
List<LongTerms.Bucket> buckets = longTerms.getBuckets();
List<DoubleTerms.Bucket> newBuckets = new ArrayList<>();
for (Terms.Bucket bucket : buckets) {
newBuckets.add(
new DoubleTerms.Bucket(
bucket.getKeyAsNumber().doubleValue(),
bucket.getDocCount(),
bucket.getAggregations(),
longTerms.showTermDocCountError,
longTerms.showTermDocCountError ? bucket.getDocCountError() : 0,
decimalFormat
)
);
}
return new DoubleTerms(
longTerms.getName(),
longTerms.reduceOrder,
longTerms.order,
longTerms.requiredSize,
longTerms.minDocCount,
longTerms.metadata,
longTerms.format,
longTerms.shardSize,
longTerms.showTermDocCountError,
longTerms.otherDocCount,
newBuckets,
longTerms.docCountError
);
}
}
| Bucket |
java | google__dagger | javatests/artifacts/hilt-android/simple/app/src/sharedTest/java/dagger/hilt/android/simple/Injection2Test.java | {
"start": 2326,
"end": 3045
} | class ____ extends AppCompatActivity {
@Inject @Named(ACTIVITY_QUALIFIER) String activityValue;
}
@Rule public HiltAndroidRule rule = new HiltAndroidRule(this);
@Inject @Named(APPLICATION_QUALIFIER) String applicationValue;
@Test
public void testApplicationInjection() throws Exception {
assertThat(applicationValue).isNull();
rule.inject();
assertThat(applicationValue).isEqualTo(APPLICATION_VALUE);
}
@Test
public void testActivityInjection() throws Exception {
try (ActivityScenario<TestActivity> scenario = ActivityScenario.launch(TestActivity.class)) {
scenario.onActivity(activity -> assertThat(activity.activityValue).isEqualTo(ACTIVITY_VALUE));
}
}
}
| TestActivity |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/MergeSorter.java | {
"start": 1660,
"end": 2607
} | class ____ extends BasicTypeSorterBase
implements Comparator<IntWritable> {
private static int progressUpdateFrequency = 10000;
private int progressCalls = 0;
/** The sort method derived from BasicTypeSorterBase and overridden here*/
public RawKeyValueIterator sort() {
MergeSort m = new MergeSort(this);
int count = super.count;
if (count == 0) return null;
int [] pointers = super.pointers;
int [] pointersCopy = new int[count];
System.arraycopy(pointers, 0, pointersCopy, 0, count);
m.mergeSort(pointers, pointersCopy, 0, count);
return new MRSortResultIterator(super.keyValBuffer, pointersCopy,
super.startOffsets, super.keyLengths, super.valueLengths);
}
/** The implementation of the compare method from Comparator. Note that
* Comparator.compare takes objects as inputs and so the int values are
* wrapped in (reusable) IntWritables from the | MergeSorter |
java | netty__netty | transport/src/test/java/io/netty/channel/DefaultChannelPipelineTailTest.java | {
"start": 7892,
"end": 8220
} | class ____ implements ChannelFactory<MyChannel> {
private final MyChannel channel;
MyChannelFactory(MyChannel channel) {
this.channel = channel;
}
@Override
public MyChannel newChannel() {
return channel;
}
}
private abstract static | MyChannelFactory |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java | {
"start": 101511,
"end": 114424
} | class ____ {
// @Outgoing
@Outgoing("channel1")
Publisher<Record<Double, java.nio.ByteBuffer>> method1() {
return null;
}
@Outgoing("channel3")
PublisherBuilder<Record<Double, java.nio.ByteBuffer>> method3() {
return null;
}
@Outgoing("channel5")
Multi<Record<Double, java.nio.ByteBuffer>> method5() {
return null;
}
@Outgoing("channel7")
Record<Double, java.nio.ByteBuffer> method7() {
return null;
}
@Outgoing("channel9")
CompletionStage<Record<Double, java.nio.ByteBuffer>> method9() {
return null;
}
@Outgoing("channel11")
Uni<Record<Double, java.nio.ByteBuffer>> method11() {
return null;
}
// @Incoming
@Incoming("channel13")
Subscriber<KafkaRecord<Integer, java.util.UUID>> method13() {
return null;
}
@Incoming("channel15")
SubscriberBuilder<KafkaRecord<Integer, java.util.UUID>, Void> method15() {
return null;
}
@Incoming("channel18")
CompletionStage<?> method18(KafkaRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel20")
Uni<?> method20(KafkaRecord<Integer, java.util.UUID> msg) {
return null;
}
// @Incoming @Outgoing
@Incoming("channel22")
@Outgoing("channel23")
Processor<KafkaRecord<Integer, java.util.UUID>, Record<Double, java.nio.ByteBuffer>> method22() {
return null;
}
@Incoming("channel26")
@Outgoing("channel27")
ProcessorBuilder<KafkaRecord<Integer, java.util.UUID>, Record<Double, java.nio.ByteBuffer>> method24() {
return null;
}
@Incoming("channel30")
@Outgoing("channel31")
Publisher<Record<Double, java.nio.ByteBuffer>> method26(KafkaRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel34")
@Outgoing("channel35")
PublisherBuilder<Record<Double, java.nio.ByteBuffer>> method28(KafkaRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel38")
@Outgoing("channel39")
Multi<Record<Double, java.nio.ByteBuffer>> method30(KafkaRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel42")
@Outgoing("channel43")
Record<Double, java.nio.ByteBuffer> method32(KafkaRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel46")
@Outgoing("channel47")
CompletionStage<Record<Double, java.nio.ByteBuffer>> method34(KafkaRecord<Integer, java.util.UUID> msg) {
return null;
}
@Incoming("channel50")
@Outgoing("channel51")
Uni<Record<Double, java.nio.ByteBuffer>> method36(KafkaRecord<Integer, java.util.UUID> msg) {
return null;
}
// @Incoming @Outgoing stream manipulation
@Incoming("channel54")
@Outgoing("channel55")
Publisher<Record<Double, java.nio.ByteBuffer>> method38(Publisher<KafkaRecord<Integer, java.util.UUID>> msg) {
return null;
}
@Incoming("channel58")
@Outgoing("channel59")
PublisherBuilder<Record<Double, java.nio.ByteBuffer>> method40(
PublisherBuilder<KafkaRecord<Integer, java.util.UUID>> msg) {
return null;
}
@Incoming("channel62")
@Outgoing("channel63")
Multi<Record<Double, java.nio.ByteBuffer>> method42(Multi<KafkaRecord<Integer, java.util.UUID>> msg) {
return null;
}
}
// ---
@Test
public void consumerRecordIntUuidInProducerRecordDoubleByteBufferOut() {
// @formatter:off
Tuple[] expectations = {
tuple("mp.messaging.outgoing.channel1.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel1.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.outgoing.channel3.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel3.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.outgoing.channel5.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel5.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.outgoing.channel7.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel7.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.outgoing.channel9.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel9.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.outgoing.channel11.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel11.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel13.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel13.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.incoming.channel15.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel15.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.incoming.channel18.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel18.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.incoming.channel20.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel20.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.incoming.channel22.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel22.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel23.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel23.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel26.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel26.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel27.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel27.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel30.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel30.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel31.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel31.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel34.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel34.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel35.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel35.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel38.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel38.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel39.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel39.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel42.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel42.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel43.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel43.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel46.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel46.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel47.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel47.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel50.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel50.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel51.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel51.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel54.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel54.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel55.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel55.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel58.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel58.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel59.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel59.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
tuple("mp.messaging.incoming.channel62.key.deserializer", "org.apache.kafka.common.serialization.IntegerDeserializer"),
tuple("mp.messaging.incoming.channel62.value.deserializer", "org.apache.kafka.common.serialization.UUIDDeserializer"),
tuple("mp.messaging.outgoing.channel63.key.serializer", "org.apache.kafka.common.serialization.DoubleSerializer"),
tuple("mp.messaging.outgoing.channel63.value.serializer", "org.apache.kafka.common.serialization.ByteBufferSerializer"),
};
// @formatter:on
doTest(expectations, ConsumerRecordIntUuidInProducerRecordDoubleByteBufferOut.class);
}
private static | KafkaRecordIntUuidInRecordDoubleByteBufferOut |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ExcessRedundancyMap.java | {
"start": 1333,
"end": 1359
} | class ____ thread safe.
*/
| is |
java | apache__camel | components/camel-aws/camel-aws2-eks/src/main/java/org/apache/camel/component/aws2/eks/EKS2Endpoint.java | {
"start": 1695,
"end": 3649
} | class ____ extends ScheduledPollEndpoint implements EndpointServiceLocation {
private EksClient eksClient;
@UriParam
private EKS2Configuration configuration;
public EKS2Endpoint(String uri, Component component, EKS2Configuration configuration) {
super(uri, component);
this.configuration = configuration;
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("You cannot receive messages from this endpoint");
}
@Override
public Producer createProducer() throws Exception {
return new EKS2Producer(this);
}
@Override
public EKS2Component getComponent() {
return (EKS2Component) super.getComponent();
}
@Override
public void doStart() throws Exception {
super.doStart();
eksClient = configuration.getEksClient() != null
? configuration.getEksClient() : EKS2ClientFactory.getEksClient(configuration).getEksClient();
}
@Override
public void doStop() throws Exception {
if (ObjectHelper.isEmpty(configuration.getEksClient())) {
if (eksClient != null) {
eksClient.close();
}
}
super.doStop();
}
public EKS2Configuration getConfiguration() {
return configuration;
}
public EksClient getEksClient() {
return eksClient;
}
@Override
public String getServiceUrl() {
if (!configuration.isOverrideEndpoint()) {
if (ObjectHelper.isNotEmpty(configuration.getRegion())) {
return configuration.getRegion();
}
} else if (ObjectHelper.isNotEmpty(configuration.getUriEndpointOverride())) {
return configuration.getUriEndpointOverride();
}
return null;
}
@Override
public String getServiceProtocol() {
return "eks";
}
}
| EKS2Endpoint |
java | google__guice | extensions/assistedinject/src/com/google/inject/assistedinject/FactoryModuleBuilder.java | {
"start": 7090,
"end": 7771
} | interface ____ {
* {@literal @}Named("fast") Car getFastCar(Color color);
* {@literal @}Named("clean") Car getCleanCar(Color color);
* }
* ...
* protected void configure() {
* install(new FactoryModuleBuilder()
* .implement(Car.class, Names.named("fast"), Porsche.class)
* .implement(Car.class, Names.named("clean"), Prius.class)
* .build(CarFactory.class));
* }</pre>
*
* <h3>Implementation limitations</h3>
*
* As a limitation of the implementation, it is prohibited to declare a factory method that accepts
* a {@code Provider} as one of its arguments.
*
* @since 3.0
* @author schmitt@google.com (Peter Schmitt)
*/
public final | CarFactory |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/HHH16122Test.java | {
"start": 1058,
"end": 1401
} | class ____ implements AttributeConverter<ConvertedValue, Long> {
@Override
public Long convertToDatabaseColumn( ConvertedValue value ) {
return value.value;
}
@Override
public ConvertedValue convertToEntityAttribute( Long value ) {
return new ConvertedValue(value);
}
}
@MappedSuperclass
public static abstract | ValueConverter |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/aop/introduction/delegation/DelegatingInterceptor.java | {
"start": 885,
"end": 1830
} | class ____ implements MethodInterceptor<Delegating, Object> {
@Nullable
@Override
public Object intercept(MethodInvocationContext<Delegating, Object> context) {
ExecutableMethod<Delegating, Object> executableMethod = context.getExecutableMethod();
Object[] parameterValues = context.getParameterValues();
if (executableMethod.getName().equals("test2")) {
DelegatingIntroduced instance = new DelegatingIntroduced() {
@Override
public String test2() {
return "good";
}
@Override
public String test() {
return "good";
}
};
return executableMethod.invoke(instance, parameterValues);
} else {
return executableMethod
.invoke(new DelegatingImpl(), parameterValues);
}
}
}
| DelegatingInterceptor |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/compound/CompoundNaturalIdMappingTest.java | {
"start": 979,
"end": 2182
} | class ____ {
@Test
public void test() {
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry();
try {
Metadata meta = new MetadataSources( ssr )
.addAnnotatedClass( PostalCarrier.class )
.addAnnotatedClass( Country.class )
.buildMetadata();
( (MetadataImplementor) meta ).orderColumns( false );
( (MetadataImplementor) meta ).validate();
final SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) meta.buildSessionFactory();
try {
final EntityMappingType entityMappingType = sessionFactory.getRuntimeMetamodels().getEntityMappingType( PostalCarrier.class );
final NaturalIdMapping naturalIdMapping = entityMappingType.getNaturalIdMapping();
final List<SingularAttributeMapping> naturalIdAttributes = naturalIdMapping.getNaturalIdAttributes();
assertThat( naturalIdAttributes.size(), is( 2 ) );
assertThat( naturalIdAttributes.get( 0 ).getAttributeName(), is( "code" ) );
assertThat( naturalIdAttributes.get( 1 ).getAttributeName(), is( "country" ) );
}
finally {
sessionFactory.close();
}
}
finally {
StandardServiceRegistryBuilder.destroy( ssr );
}
}
}
| CompoundNaturalIdMappingTest |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/service/invoker/RequestAttributeArgumentResolver.java | {
"start": 1389,
"end": 1979
} | class ____ extends AbstractNamedValueArgumentResolver {
@Override
protected @Nullable NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
RequestAttribute annot = parameter.getParameterAnnotation(RequestAttribute.class);
return (annot == null ? null :
new NamedValueInfo(annot.name(), annot.required(), null, "request attribute", false));
}
@Override
protected void addRequestValue(
String name, Object value, MethodParameter parameter, HttpRequestValues.Builder requestValues) {
requestValues.addAttribute(name, value);
}
}
| RequestAttributeArgumentResolver |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/slotmanager/AbstractFineGrainedSlotManagerITCase.java | {
"start": 2586,
"end": 6773
} | class ____ extends FineGrainedSlotManagerTestBase {
// ---------------------------------------------------------------------------------------------
// Requirement declaration
// ---------------------------------------------------------------------------------------------
/**
* Tests that a requirement declaration with no free slots will trigger the resource allocation.
*/
@Test
void testRequirementDeclarationWithoutFreeSlotsTriggersWorkerAllocation() throws Exception {
final ResourceRequirements resourceRequirements = createResourceRequirementsForSingleSlot();
final CompletableFuture<WorkerResourceSpec> allocateResourceFuture =
new CompletableFuture<>();
new Context() {
{
resourceAllocatorBuilder.setDeclareResourceNeededConsumer(
(resourceDeclarations) -> {
assertThat(resourceDeclarations).hasSize(1);
ResourceDeclaration resourceDeclaration =
resourceDeclarations.iterator().next();
allocateResourceFuture.complete(resourceDeclaration.getSpec());
});
runTest(
() -> {
runInMainThread(
() ->
getSlotManager()
.processResourceRequirements(
resourceRequirements));
assertFutureCompleteAndReturn(allocateResourceFuture);
});
}
};
}
/**
* Tests that resources continue to be considered missing if we cannot allocate more resources.
*/
@Test
void testRequirementDeclarationWithResourceAllocationFailure() throws Exception {
final ResourceRequirements resourceRequirements = createResourceRequirementsForSingleSlot();
final CompletableFuture<Void> allocateResourceFuture = new CompletableFuture<>();
new Context() {
{
resourceAllocatorBuilder
.setDeclareResourceNeededConsumer(
(resourceDeclarations) -> allocateResourceFuture.complete(null))
.setIsSupportedSupplier(() -> false);
runTest(
() -> {
runInMainThread(
() ->
getSlotManager()
.processResourceRequirements(
resourceRequirements));
assertFutureNotComplete(allocateResourceFuture);
assertThat(
getTotalResourceCount(
getResourceTracker()
.getMissingResources()
.get(resourceRequirements.getJobId())))
.isEqualTo(1);
});
}
};
}
/** Tests that resource requirements can be fulfilled with resource that are currently free. */
@Test
void testRequirementDeclarationWithFreeResource() throws Exception {
testRequirementDeclaration(
RequirementDeclarationScenario
.TASK_EXECUTOR_REGISTRATION_BEFORE_REQUIREMENT_DECLARATION);
}
/**
* Tests that resource requirements can be fulfilled with resource that are registered after the
* requirement declaration.
*/
@Test
void testRequirementDeclarationWithPendingResource() throws Exception {
testRequirementDeclaration(
RequirementDeclarationScenario
.TASK_EXECUTOR_REGISTRATION_AFTER_REQUIREMENT_DECLARATION);
}
private | AbstractFineGrainedSlotManagerITCase |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/engine/InternalEngineSettingsTests.java | {
"start": 896,
"end": 3321
} | class ____ extends ESSingleNodeTestCase {
public void testSettingsUpdate() {
final IndexService service = createIndex("foo");
InternalEngine engine = ((InternalEngine) EngineAccess.engine(service.getShardOrNull(0)));
assertThat(engine.getCurrentIndexWriterConfig().getUseCompoundFile(), is(true));
final int iters = between(1, 20);
for (int i = 0; i < iters; i++) {
// Tricky: TimeValue.parseTimeValue casts this long to a double, which steals 11 of the 64 bits for exponent, so we can't use
// the full long range here else the assert below fails:
long gcDeletes = random().nextLong() & (Long.MAX_VALUE >> 11);
Settings build = Settings.builder()
.put(IndexSettings.INDEX_GC_DELETES_SETTING.getKey(), gcDeletes, TimeUnit.MILLISECONDS)
.build();
assertEquals(gcDeletes, build.getAsTime(IndexSettings.INDEX_GC_DELETES_SETTING.getKey(), null).millis());
indicesAdmin().prepareUpdateSettings("foo").setSettings(build).get();
LiveIndexWriterConfig currentIndexWriterConfig = engine.getCurrentIndexWriterConfig();
assertEquals(currentIndexWriterConfig.getUseCompoundFile(), true);
assertEquals(engine.config().getIndexSettings().getGcDeletesInMillis(), gcDeletes);
assertEquals(engine.getGcDeletesInMillis(), gcDeletes);
}
Settings settings = Settings.builder().put(IndexSettings.INDEX_GC_DELETES_SETTING.getKey(), 1000, TimeUnit.MILLISECONDS).build();
indicesAdmin().prepareUpdateSettings("foo").setSettings(settings).get();
assertEquals(engine.getGcDeletesInMillis(), 1000);
assertTrue(engine.config().isEnableGcDeletes());
settings = Settings.builder().put(IndexSettings.INDEX_GC_DELETES_SETTING.getKey(), "0ms").build();
indicesAdmin().prepareUpdateSettings("foo").setSettings(settings).get();
assertEquals(engine.getGcDeletesInMillis(), 0);
assertTrue(engine.config().isEnableGcDeletes());
settings = Settings.builder().put(IndexSettings.INDEX_GC_DELETES_SETTING.getKey(), 1000, TimeUnit.MILLISECONDS).build();
indicesAdmin().prepareUpdateSettings("foo").setSettings(settings).get();
assertEquals(engine.getGcDeletesInMillis(), 1000);
assertTrue(engine.config().isEnableGcDeletes());
}
}
| InternalEngineSettingsTests |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-guava-tests/src/test/java/org/assertj/tests/guava/Module_Test.java | {
"start": 766,
"end": 1070
} | class ____ {
private final Module underTest = ModuleLayer.boot().findModule("org.assertj.guava").orElseThrow();
@Test
void should_export_all_packages() {
// WHEN
Set<String> packages = underTest.getPackages();
// THEN
then(packages).allMatch(underTest::isExported);
}
}
| Module_Test |
java | spring-projects__spring-security | rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocketTests.java | {
"start": 2990,
"end": 24351
} | class ____ {
static final MimeType COMPOSITE_METADATA = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
@Mock
RSocket delegate;
@Mock
PayloadInterceptor interceptor;
@Mock
PayloadInterceptor interceptor2;
@Mock
Payload payload;
@Captor
private ArgumentCaptor<PayloadExchange> exchange;
PublisherProbe<Void> voidResult = PublisherProbe.empty();
TestPublisher<Payload> payloadResult = TestPublisher.createCold();
private MimeType metadataMimeType = COMPOSITE_METADATA;
private MimeType dataMimeType = MediaType.APPLICATION_JSON;
@Test
public void constructorWhenNullDelegateThenException() {
this.delegate = null;
List<PayloadInterceptor> interceptors = Arrays.asList(this.interceptor);
assertThatIllegalArgumentException().isThrownBy(() -> new PayloadInterceptorRSocket(this.delegate, interceptors,
this.metadataMimeType, this.dataMimeType));
}
@Test
public void constructorWhenNullInterceptorsThenException() {
List<PayloadInterceptor> interceptors = null;
assertThatIllegalArgumentException().isThrownBy(() -> new PayloadInterceptorRSocket(this.delegate, interceptors,
this.metadataMimeType, this.dataMimeType));
}
@Test
public void constructorWhenEmptyInterceptorsThenException() {
List<PayloadInterceptor> interceptors = Collections.emptyList();
assertThatIllegalArgumentException().isThrownBy(() -> new PayloadInterceptorRSocket(this.delegate, interceptors,
this.metadataMimeType, this.dataMimeType));
}
// single interceptor
@Test
public void fireAndForgetWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.fireAndForget(this.payload))
.then(() -> this.voidResult.assertWasSubscribed())
.verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void fireAndForgetWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.fireAndForget(this.payload))
.then(() -> this.voidResult.assertWasNotSubscribed())
.verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void fireAndForgetWhenSecurityContextThenDelegateContext() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication));
given(this.delegate.fireAndForget(any())).willReturn(Mono.empty());
RSocket assertAuthentication = new RSocketProxy(this.delegate) {
@Override
public Mono<Void> fireAndForget(Payload payload) {
return assertAuthentication(authentication).flatMap((a) -> super.fireAndForget(payload));
}
};
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(assertAuthentication,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).fireAndForget(this.payload);
}
@Test
public void requestResponseWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.requestResponse(any())).willReturn(this.payloadResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestResponse(this.payload))
.then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(this.payload))
.expectNext(this.payload)
.verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestResponse(this.payload);
}
@Test
public void requestResponseWhenInterceptorErrorsThenDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> interceptor.requestResponse(this.payload).block())
.isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verifyNoMoreInteractions(this.delegate);
}
@Test
public void requestResponseWhenSecurityContextThenDelegateContext() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication));
given(this.delegate.requestResponse(any())).willReturn(this.payloadResult.mono());
RSocket assertAuthentication = new RSocketProxy(this.delegate) {
@Override
public Mono<Payload> requestResponse(Payload payload) {
return assertAuthentication(authentication).flatMap((a) -> super.requestResponse(payload));
}
};
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(assertAuthentication,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestResponse(this.payload))
.then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(this.payload))
.expectNext(this.payload)
.verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestResponse(this.payload);
}
@Test
public void requestStreamWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.requestStream(any())).willReturn(this.payloadResult.flux());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestStream(this.payload))
.then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(this.payload))
.expectNext(this.payload)
.verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void requestStreamWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestStream(this.payload))
.then(() -> this.payloadResult.assertNoSubscribers())
.verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void requestStreamWhenSecurityContextThenDelegateContext() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication));
given(this.delegate.requestStream(any())).willReturn(this.payloadResult.flux());
RSocket assertAuthentication = new RSocketProxy(this.delegate) {
@Override
public Flux<Payload> requestStream(Payload payload) {
return assertAuthentication(authentication).flatMapMany((a) -> super.requestStream(payload));
}
};
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(assertAuthentication,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestStream(this.payload))
.then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(this.payload))
.expectNext(this.payload)
.verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestStream(this.payload);
}
@Test
public void requestChannelWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.requestChannel(any())).willReturn(this.payloadResult.flux());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestChannel(Flux.just(this.payload)))
.then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(this.payload))
.expectNext(this.payload)
.verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestChannel(any());
}
// gh-9345
@Test
public void requestChannelWhenInterceptorCompletesThenAllPayloadsRetained() {
ExecutorService executors = Executors.newSingleThreadExecutor();
Payload payload = ByteBufPayload.create("data");
Payload payloadTwo = ByteBufPayload.create("moredata");
Payload payloadThree = ByteBufPayload.create("stillmoredata");
Context ctx = Context.empty();
Flux<Payload> payloads = this.payloadResult.flux();
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty())
.willReturn(Mono.error(() -> new AccessDeniedException("Access Denied")));
given(this.delegate.requestChannel(any())).willAnswer((invocation) -> {
Flux<Payload> input = invocation.getArgument(0);
return Flux.from(input)
.switchOnFirst((signal, innerFlux) -> innerFlux.map(Payload::getDataUtf8)
.transform((data) -> Flux.<String>create((emitter) -> {
Runnable run = () -> data.subscribe(new CoreSubscriber<String>() {
@Override
public void onSubscribe(Subscription s) {
s.request(3);
}
@Override
public void onNext(String s) {
emitter.next(s);
}
@Override
public void onError(Throwable t) {
emitter.error(t);
}
@Override
public void onComplete() {
emitter.complete();
}
});
executors.execute(run);
}))
.map(DefaultPayload::create));
});
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType, ctx);
StepVerifier.create(interceptor.requestChannel(payloads).doOnDiscard(Payload.class, Payload::release))
.then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(payload, payloadTwo, payloadThree))
.assertNext((next) -> assertThat(next.getDataUtf8()).isEqualTo(payload.getDataUtf8()))
.verifyError(AccessDeniedException.class);
verify(this.interceptor, times(2)).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(payloadTwo);
verify(this.delegate).requestChannel(any());
}
@Test
public void requestChannelWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestChannel(Flux.just(this.payload)))
.then(() -> this.payloadResult.assertNoSubscribers())
.verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void requestChannelWhenSecurityContextThenDelegateContext() {
Mono<Payload> payload = Mono.just(this.payload);
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication));
given(this.delegate.requestChannel(any())).willReturn(this.payloadResult.flux());
RSocket assertAuthentication = new RSocketProxy(this.delegate) {
@Override
public Flux<Payload> requestChannel(Publisher<Payload> payload) {
return assertAuthentication(authentication).flatMapMany((a) -> super.requestChannel(payload));
}
};
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(assertAuthentication,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestChannel(payload))
.then(() -> this.payloadResult.assertSubscribers())
.then(() -> this.payloadResult.emit(this.payload))
.expectNext(this.payload)
.verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestChannel(any());
}
@Test
public void metadataPushWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.metadataPush(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.metadataPush(this.payload))
.then(() -> this.voidResult.assertWasSubscribed())
.verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void metadataPushWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.metadataPush(this.payload))
.then(() -> this.voidResult.assertWasNotSubscribed())
.verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@Test
public void metadataPushWhenSecurityContextThenDelegateContext() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication));
given(this.delegate.metadataPush(any())).willReturn(this.voidResult.mono());
RSocket assertAuthentication = new RSocketProxy(this.delegate) {
@Override
public Mono<Void> metadataPush(Payload payload) {
return assertAuthentication(authentication).flatMap((a) -> super.metadataPush(payload));
}
};
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(assertAuthentication,
Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.metadataPush(this.payload)).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).metadataPush(this.payload);
this.voidResult.assertWasSubscribed();
}
// multiple interceptors
@Test
public void fireAndForgetWhenInterceptorsCompleteThenDelegateInvoked() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
this.voidResult.assertWasSubscribed();
}
@Test
public void fireAndForgetWhenInterceptorsMutatesPayloadThenDelegateInvoked() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
verify(this.delegate).fireAndForget(eq(this.payload));
this.voidResult.assertWasSubscribed();
}
@Test
public void fireAndForgetWhenInterceptor1ErrorsThenInterceptor2AndDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> interceptor.fireAndForget(this.payload).block())
.isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verifyNoMoreInteractions(this.interceptor2);
this.voidResult.assertWasNotSubscribed();
}
@Test
public void fireAndForgetWhenInterceptor2ErrorsThenInterceptor2AndDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate,
Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> interceptor.fireAndForget(this.payload).block())
.isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
this.voidResult.assertWasNotSubscribed();
}
private Mono<Authentication> assertAuthentication(Authentication authentication) {
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.doOnNext((a) -> assertThat(a).isEqualTo(authentication));
}
private Answer<Object> withAuthenticated(Authentication authentication) {
return (invocation) -> {
PayloadInterceptorChain c = (PayloadInterceptorChain) invocation.getArguments()[1];
return c
.next(new DefaultPayloadExchange(PayloadExchangeType.REQUEST_CHANNEL, this.payload,
this.metadataMimeType, this.dataMimeType))
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
};
}
private static Answer<Mono<Void>> withChainNext() {
return (invocation) -> {
PayloadExchange exchange = (PayloadExchange) invocation.getArguments()[0];
PayloadInterceptorChain chain = (PayloadInterceptorChain) invocation.getArguments()[1];
return chain.next(exchange);
};
}
}
| PayloadInterceptorRSocketTests |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/charsequence/CharSequenceAssert_matchesSatisfying_Pattern_Test.java | {
"start": 1330,
"end": 2701
} | class ____ {
@Test
void should_pass_if_string_matches_given_pattern_and_first_match_satisfies_assertion() {
// GIVEN
Pattern pattern = Pattern.compile("..(o.o)");
// WHEN/THEN
then("Frodo").matchesSatisfying(pattern, matcher -> assertThat(matcher.group(1)).isEqualTo("odo"));
}
@Test
void should_fail_if_string_does_not_match_given_pattern() {
// GIVEN
Pattern pattern = Pattern.compile(".*(a).*");
// WHEN
var assertionError = expectAssertionError(() -> assertThat("Frodo").matchesSatisfying(pattern,
matcher -> assertThat(true).isTrue()));
// THEN
then(assertionError).hasMessage(shouldMatch("Frodo", pattern.toString()).create());
}
@Test
void should_pass_if_string_matches_given_pattern_but_match_does_not_satisfy_assertion() {
// GIVEN
Pattern pattern = Pattern.compile(".*(a).*");
// WHEN
var assertionError = expectAssertionError(() -> assertThat("bar").matchesSatisfying(pattern,
matcher -> assertThat(matcher.group(1)).contains("b")));
// THEN
then(assertionError).hasMessage(shouldContain("a", "b", StandardComparisonStrategy.instance()).create());
}
}
| CharSequenceAssert_matchesSatisfying_Pattern_Test |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetomany/OrderID.java | {
"start": 256,
"end": 715
} | class ____ implements Serializable {
private String schoolId;
private Integer academicYear;
@Column( name = "Academic_Yr" )
public Integer getAcademicYear() {
return this.academicYear;
}
public void setAcademicYear(Integer academicYear) {
this.academicYear = academicYear;
}
@Column( name = "School_Id" )
public String getSchoolId() {
return this.schoolId;
}
public void setSchoolId(String schoolId) {
this.schoolId = schoolId;
}
}
| OrderID |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/audit/impl/ActiveAuditManagerS3A.java | {
"start": 4433,
"end": 4559
} | class ____ a reference to the span,
* the active span will be retained.
*
*
*/
@InterfaceAudience.Private
public final | retains |
java | spring-projects__spring-framework | framework-docs/src/main/java/org/springframework/docs/integration/observability/config/conventions/ServerRequestObservationFilter.java | {
"start": 936,
"end": 1484
} | class ____ implements ObservationFilter {
@Override
public Observation.Context map(Observation.Context context) {
if (context instanceof ServerRequestObservationContext serverContext) {
context.setName("custom.observation.name");
context.addLowCardinalityKeyValue(KeyValue.of("project", "spring"));
String customAttribute = (String) serverContext.getCarrier().getAttribute("customAttribute");
context.addLowCardinalityKeyValue(KeyValue.of("custom.attribute", customAttribute));
}
return context;
}
}
| ServerRequestObservationFilter |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/StatelessSession.java | {
"start": 456,
"end": 3708
} | interface ____ called, any necessary interaction with the database happens
* immediately and synchronously.
* <p>
* Viewed in opposition to {@link Session}, the {@code StatelessSession} is
* a whole competing programming model, one preferred by some developers
* for its simplicity and somewhat lower level of abstraction. But the two
* kinds of session are not enemies, and may comfortably coexist in a single
* program.
* <p>
* A stateless session comes some with designed-in limitations:
* <ul>
* <li>it does not have a first-level cache,
* <li>nor does it implement transactional write-behind or automatic dirty
* checking.
* </ul>
* <p>
* Furthermore, the basic operations of a stateless session do not have
* corresponding {@linkplain jakarta.persistence.CascadeType cascade types},
* and so an operation performed via a stateless session never cascades to
* associated instances.
* <p>
* The basic operations of a stateless session are {@link #get(Class, Object)},
* {@link #insert(Object)}, {@link #update(Object)}, {@link #delete(Object)},
* and {@link #upsert(Object)}. These operations are always performed
* synchronously, resulting in immediate access to the database. Notice that
* update is an explicit operation. There is no "flush" operation for a
* stateless session, and so modifications to entities are never automatically
* detected and made persistent.
* <p>
* Similarly, lazy association fetching is an explicit operation. A collection
* or proxy may be fetched by calling {@link #fetch(Object)}.
* <p>
* Stateless sessions are vulnerable to data aliasing effects, due to the
* lack of a first-level cache.
* <p>
* On the other hand, for certain kinds of transactions, a stateless session
* may perform slightly faster than a stateful session.
* <p>
* Certain rules applying to stateful sessions are relaxed in a stateless
* session:
* <ul>
* <li>it's not necessary to discard a stateless session and its entities
* after an exception is thrown by the stateless session, and
* <li>when an exception is thrown by a stateless session, the current
* transaction is not automatically marked for rollback.
* </ul>
* <p>
* Since version 7, the configuration property
* {@value org.hibernate.cfg.BatchSettings#STATEMENT_BATCH_SIZE} has no effect
* on a stateless session. Automatic batching may be enabled by explicitly
* {@linkplain #setJdbcBatchSize setting the batch size}. However, automatic
* batching has the side effect of delaying execution of the batched operation,
* thus undermining the synchronous nature of operations performed through a
* stateless session. A preferred approach is to explicitly batch operations via
* {@link #insertMultiple}, {@link #updateMultiple}, or {@link #deleteMultiple}.
* <p>
* Since version 7, a stateless session makes use of the second-level cache by
* default. To bypass the second-level cache, call {@link #setCacheMode(CacheMode)},
* passing {@link CacheMode#IGNORE}, or set the configuration properties
* {@value org.hibernate.cfg.CacheSettings#JAKARTA_SHARED_CACHE_RETRIEVE_MODE}
* and {@value org.hibernate.cfg.CacheSettings#JAKARTA_SHARED_CACHE_STORE_MODE}
* to {@code BYPASS}.
*
* @author Gavin King
*/
public | is |
java | spring-projects__spring-boot | module/spring-boot-security-saml2/src/main/java/org/springframework/boot/security/saml2/autoconfigure/Saml2RelyingPartyProperties.java | {
"start": 1287,
"end": 1601
} | class ____ {
/**
* SAML2 relying party registrations.
*/
private final Map<String, Registration> registration = new LinkedHashMap<>();
public Map<String, Registration> getRegistration() {
return this.registration;
}
/**
* Represents a SAML Relying Party.
*/
public static | Saml2RelyingPartyProperties |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/convert/ConvertingSerializerTest.java | {
"start": 515,
"end": 619
} | class ____
{
@JsonSerialize(converter=ConvertingBeanConverter.class)
static | ConvertingSerializerTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/deser/ConstructorErrorTest_initError.java | {
"start": 598,
"end": 785
} | class ____ {
public Model(){
}
public void setName(String name) {
throw new IllegalStateException();
}
}
}
| Model |
java | apache__hadoop | hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/response/WRITE3Response.java | {
"start": 1133,
"end": 2730
} | class ____ extends NFS3Response {
private final WccData fileWcc; // return on both success and failure
private final int count;
private final WriteStableHow stableHow;
private final long verifer;
public WRITE3Response(int status) {
this(status, new WccData(null, null), 0, WriteStableHow.UNSTABLE,
Nfs3Constant.WRITE_COMMIT_VERF);
}
public WRITE3Response(int status, WccData fileWcc, int count,
WriteStableHow stableHow, long verifier) {
super(status);
this.fileWcc = fileWcc;
this.count = count;
this.stableHow = stableHow;
this.verifer = verifier;
}
public int getCount() {
return count;
}
public WriteStableHow getStableHow() {
return stableHow;
}
public long getVerifer() {
return verifer;
}
public static WRITE3Response deserialize(XDR xdr) {
int status = xdr.readInt();
WccData fileWcc = WccData.deserialize(xdr);
int count = 0;
WriteStableHow stableHow = null;
long verifier = 0;
if (status == Nfs3Status.NFS3_OK) {
count = xdr.readInt();
int how = xdr.readInt();
stableHow = WriteStableHow.values()[how];
verifier = xdr.readHyper();
}
return new WRITE3Response(status, fileWcc, count, stableHow, verifier);
}
@Override
public XDR serialize(XDR out, int xid, Verifier verifier) {
super.serialize(out, xid, verifier);
fileWcc.serialize(out);
if (getStatus() == Nfs3Status.NFS3_OK) {
out.writeInt(count);
out.writeInt(stableHow.getValue());
out.writeLongAsHyper(verifer);
}
return out;
}
}
| WRITE3Response |
java | elastic__elasticsearch | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/aggs/kstest/BucketCountKSTestAggregationBuilderTests.java | {
"start": 1075,
"end": 4046
} | class ____ extends BasePipelineAggregationTestCase<BucketCountKSTestAggregationBuilder> {
private static final String NAME = "ks-test-agg";
@Override
protected List<SearchPlugin> plugins() {
return List.of(MachineLearningTests.createTrialLicensedMachineLearning(Settings.EMPTY));
}
@Override
protected BucketCountKSTestAggregationBuilder createTestAggregatorFactory() {
return new BucketCountKSTestAggregationBuilder(
NAME,
randomAlphaOfLength(10),
Stream.generate(ESTestCase::randomDouble).limit(100).collect(Collectors.toList()),
Stream.generate(() -> randomFrom(Alternative.GREATER, Alternative.LESS, Alternative.TWO_SIDED))
.limit(4)
.map(Alternative::toString)
.collect(Collectors.toList()),
randomFrom(new SamplingMethod.UpperTail(), new SamplingMethod.LowerTail(), new SamplingMethod.Uniform())
);
}
public void testValidate() {
AggregationBuilder singleBucketAgg = new GlobalAggregationBuilder("global");
AggregationBuilder multiBucketAgg = new TermsAggregationBuilder("terms").userValueTypeHint(ValueType.STRING);
final Set<AggregationBuilder> aggBuilders = new HashSet<>();
aggBuilders.add(singleBucketAgg);
aggBuilders.add(multiBucketAgg);
// First try to point to a non-existent agg
assertThat(
validate(
aggBuilders,
new BucketCountKSTestAggregationBuilder(
NAME,
"missing>metric",
Stream.generate(ESTestCase::randomDouble).limit(100).collect(Collectors.toList()),
Stream.generate(() -> randomFrom(Alternative.GREATER, Alternative.LESS, Alternative.TWO_SIDED))
.limit(4)
.map(Alternative::toString)
.collect(Collectors.toList()),
new SamplingMethod.UpperTail()
)
),
containsString("aggregation does not exist for aggregation")
);
// Now validate with a single bucket agg
assertThat(
validate(
aggBuilders,
new BucketCountKSTestAggregationBuilder(
NAME,
"global>metric",
Stream.generate(ESTestCase::randomDouble).limit(100).collect(Collectors.toList()),
Stream.generate(() -> randomFrom(Alternative.GREATER, Alternative.LESS, Alternative.TWO_SIDED))
.limit(4)
.map(Alternative::toString)
.collect(Collectors.toList()),
new SamplingMethod.UpperTail()
)
),
containsString("Unable to find unqualified multi-bucket aggregation in buckets_path")
);
}
}
| BucketCountKSTestAggregationBuilderTests |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java | {
"start": 18763,
"end": 23769
} | class ____ {
private Long millis;
private Long styleMillis;
@DateTimeFormat(style = "S-")
private Calendar styleCalendar;
@DateTimeFormat(style = "S-", fallbackPatterns = { "yyyy-MM-dd", "yyyyMMdd", "yyyy.MM.dd" })
private Calendar styleCalendarWithFallbackPatterns;
@DateTimeFormat(style = "S-")
private Date styleDate;
@DateTimeFormat(style = "S-", fallbackPatterns = { "yyyy-MM-dd", "yyyyMMdd", "yyyy.MM.dd" })
private Date styleDateWithFallbackPatterns;
// "SS" style matches either a standard space or a narrow non-breaking space (NNBSP) before AM/PM,
// depending on the version of the JDK.
// Fallback patterns match a standard space OR a narrow non-breaking space (NNBSP) before AM/PM.
@DateTimeFormat(style = "SS", fallbackPatterns = { "M/d/yy, h:mm a", "M/d/yy, h:mm\u202Fa" })
private Date styleDateTimeWithFallbackPatternsForPreAndPostJdk20;
@DateTimeFormat(pattern = "M/d/yy h:mm")
private Date patternDate;
@DateTimeFormat(pattern = "yyyy-MM-dd", fallbackPatterns = { "M/d/yy", "yyyyMMdd", "yyyy.MM.dd" })
private Date patternDateWithFallbackPatterns;
// Primary pattern matches a standard space before AM/PM.
// Fallback pattern matches a narrow non-breaking space (NNBSP) before AM/PM.
@DateTimeFormat(pattern = "MM/dd/yy h:mm a", fallbackPatterns = "MM/dd/yy h:mm\u202Fa")
private Date patternDateTimeWithFallbackPatternForPreAndPostJdk20;
@DateTimeFormat(iso = ISO.DATE)
private Date isoDate;
@DateTimeFormat(iso = ISO.DATE, fallbackPatterns = { "M/d/yy", "yyyyMMdd", "yyyy.MM.dd" })
private Date isoDateWithFallbackPatterns;
@DateTimeFormat(iso = ISO.TIME)
private Date isoTime;
@DateTimeFormat(iso = ISO.DATE_TIME)
private Date isoDateTime;
private final List<SimpleDateBean> children = new ArrayList<>();
public Long getMillis() {
return this.millis;
}
public void setMillis(Long millis) {
this.millis = millis;
}
@DateTimeFormat(style="S-")
public Long getStyleMillis() {
return this.styleMillis;
}
public void setStyleMillis(@DateTimeFormat(style="S-") Long styleMillis) {
this.styleMillis = styleMillis;
}
public Calendar getStyleCalendar() {
return this.styleCalendar;
}
public void setStyleCalendar(Calendar styleCalendar) {
this.styleCalendar = styleCalendar;
}
public Calendar getStyleCalendarWithFallbackPatterns() {
return this.styleCalendarWithFallbackPatterns;
}
public void setStyleCalendarWithFallbackPatterns(Calendar styleCalendarWithFallbackPatterns) {
this.styleCalendarWithFallbackPatterns = styleCalendarWithFallbackPatterns;
}
public Date getStyleDate() {
return this.styleDate;
}
public void setStyleDate(Date styleDate) {
this.styleDate = styleDate;
}
public Date getStyleDateWithFallbackPatterns() {
return this.styleDateWithFallbackPatterns;
}
public void setStyleDateWithFallbackPatterns(Date styleDateWithFallbackPatterns) {
this.styleDateWithFallbackPatterns = styleDateWithFallbackPatterns;
}
public Date getStyleDateTimeWithFallbackPatternsForPreAndPostJdk20() {
return this.styleDateTimeWithFallbackPatternsForPreAndPostJdk20;
}
public void setStyleDateTimeWithFallbackPatternsForPreAndPostJdk20(Date styleDateTimeWithFallbackPatternsForPreAndPostJdk20) {
this.styleDateTimeWithFallbackPatternsForPreAndPostJdk20 = styleDateTimeWithFallbackPatternsForPreAndPostJdk20;
}
public Date getPatternDate() {
return this.patternDate;
}
public void setPatternDate(Date patternDate) {
this.patternDate = patternDate;
}
public Date getPatternDateWithFallbackPatterns() {
return this.patternDateWithFallbackPatterns;
}
public void setPatternDateWithFallbackPatterns(Date patternDateWithFallbackPatterns) {
this.patternDateWithFallbackPatterns = patternDateWithFallbackPatterns;
}
public Date getPatternDateTimeWithFallbackPatternForPreAndPostJdk20() {
return this.patternDateTimeWithFallbackPatternForPreAndPostJdk20;
}
public void setPatternDateTimeWithFallbackPatternForPreAndPostJdk20(Date patternDateTimeWithFallbackPatternForPreAndPostJdk20) {
this.patternDateTimeWithFallbackPatternForPreAndPostJdk20 = patternDateTimeWithFallbackPatternForPreAndPostJdk20;
}
public Date getIsoDate() {
return this.isoDate;
}
public void setIsoDate(Date isoDate) {
this.isoDate = isoDate;
}
public Date getIsoDateWithFallbackPatterns() {
return this.isoDateWithFallbackPatterns;
}
public void setIsoDateWithFallbackPatterns(Date isoDateWithFallbackPatterns) {
this.isoDateWithFallbackPatterns = isoDateWithFallbackPatterns;
}
public Date getIsoTime() {
return this.isoTime;
}
public void setIsoTime(Date isoTime) {
this.isoTime = isoTime;
}
public Date getIsoDateTime() {
return this.isoDateTime;
}
public void setIsoDateTime(Date isoDateTime) {
this.isoDateTime = isoDateTime;
}
public List<SimpleDateBean> getChildren() {
return this.children;
}
}
}
| SimpleDateBean |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/component/StructComponentManyToManyTest.java | {
"start": 3439,
"end": 3908
} | class ____ {
private String name;
@ManyToMany
private Set<Book> books;
public Author() {
}
public Author(String name, Book book) {
this.name = name;
this.books = book == null ? null : Set.of( book );
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
}
}
| Author |
java | apache__flink | flink-core/src/test/java/org/apache/flink/core/security/FlinkSecurityManagerTest.java | {
"start": 1724,
"end": 15189
} | class ____ {
@RegisterExtension
static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE =
TestingUtils.defaultExecutorExtension();
private static final int TEST_EXIT_CODE = 123;
SecurityManager originalSecurityManager;
@BeforeEach
void setUp() {
originalSecurityManager = System.getSecurityManager();
}
@AfterEach
void tearDown() {
System.setSecurityManager(originalSecurityManager);
}
@Test
void testThrowUserExit() {
assertThatThrownBy(
() -> {
FlinkSecurityManager flinkSecurityManager =
new FlinkSecurityManager(
ClusterOptions.UserSystemExitMode.THROW, false);
flinkSecurityManager.monitorUserSystemExit();
flinkSecurityManager.checkExit(TEST_EXIT_CODE);
})
.isInstanceOf(UserSystemExitException.class);
}
@Test
void testToggleUserExit() {
FlinkSecurityManager flinkSecurityManager =
new FlinkSecurityManager(ClusterOptions.UserSystemExitMode.THROW, false);
flinkSecurityManager.checkExit(TEST_EXIT_CODE);
flinkSecurityManager.monitorUserSystemExit();
assertThatThrownBy(() -> flinkSecurityManager.checkExit(TEST_EXIT_CODE))
.isInstanceOf(UserSystemExitException.class);
flinkSecurityManager.unmonitorUserSystemExit();
flinkSecurityManager.checkExit(TEST_EXIT_CODE);
}
@Test
void testPerThreadThrowUserExit() throws Exception {
FlinkSecurityManager flinkSecurityManager =
new FlinkSecurityManager(ClusterOptions.UserSystemExitMode.THROW, false);
ExecutorService executorService = EXECUTOR_RESOURCE.getExecutor();
// Async thread test before enabling monitoring ensures it does not throw while prestarting
// worker thread, which is to be unmonitored and tested after enabling monitoring enabled.
CompletableFuture<Void> future =
CompletableFuture.runAsync(
() -> flinkSecurityManager.checkExit(TEST_EXIT_CODE), executorService);
future.get();
flinkSecurityManager.monitorUserSystemExit();
assertThatThrownBy(() -> flinkSecurityManager.checkExit(TEST_EXIT_CODE))
.isInstanceOf(UserSystemExitException.class);
// This threaded exit should be allowed as thread is not spawned while monitor is enabled.
future =
CompletableFuture.runAsync(
() -> flinkSecurityManager.checkExit(TEST_EXIT_CODE), executorService);
future.get();
}
@Test
void testInheritedThrowUserExit() throws Exception {
FlinkSecurityManager flinkSecurityManager =
new FlinkSecurityManager(ClusterOptions.UserSystemExitMode.THROW, false);
flinkSecurityManager.monitorUserSystemExit();
assertThatThrownBy(() -> flinkSecurityManager.checkExit(TEST_EXIT_CODE))
.isInstanceOf(UserSystemExitException.class);
CheckedThread thread =
new CheckedThread() {
@Override
public void go() {
assertThatThrownBy(() -> flinkSecurityManager.checkExit(TEST_EXIT_CODE))
.isInstanceOf(UserSystemExitException.class);
}
};
thread.start();
thread.sync();
}
@Test
void testLogUserExit() {
// Log mode enables monitor but only logging allowing exit, hence not expecting exception.
// NOTE - Do not specifically test warning logging.
FlinkSecurityManager flinkSecurityManager =
new FlinkSecurityManager(ClusterOptions.UserSystemExitMode.LOG, false);
flinkSecurityManager.monitorUserSystemExit();
flinkSecurityManager.checkExit(TEST_EXIT_CODE);
}
@Test
void testDisabledConfiguration() {
// Default case (no provided option) - allowing everything, so null security manager is
// expected.
Configuration configuration = new Configuration();
FlinkSecurityManager flinkSecurityManager =
FlinkSecurityManager.fromConfiguration(configuration);
assertThat(flinkSecurityManager).isNull();
// Disabled case (same as default)
configuration.set(
ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT,
ClusterOptions.UserSystemExitMode.DISABLED);
flinkSecurityManager = FlinkSecurityManager.fromConfiguration(configuration);
assertThat(flinkSecurityManager).isNull();
// No halt (same as default)
configuration.set(ClusterOptions.HALT_ON_FATAL_ERROR, false);
flinkSecurityManager = FlinkSecurityManager.fromConfiguration(configuration);
assertThat(flinkSecurityManager).isNull();
}
@Test
void testLogConfiguration() {
// Enabled - log case (logging as warning but allowing exit)
Configuration configuration = new Configuration();
configuration.set(
ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT, ClusterOptions.UserSystemExitMode.LOG);
FlinkSecurityManager flinkSecurityManager =
FlinkSecurityManager.fromConfiguration(configuration);
assertThat(flinkSecurityManager).isNotNull();
assertThat(flinkSecurityManager.userSystemExitMonitored()).isFalse();
flinkSecurityManager.monitorUserSystemExit();
assertThat(flinkSecurityManager.userSystemExitMonitored()).isTrue();
flinkSecurityManager.checkExit(TEST_EXIT_CODE);
flinkSecurityManager.unmonitorUserSystemExit();
assertThat(flinkSecurityManager.userSystemExitMonitored()).isFalse();
}
@Test
void testThrowConfiguration() {
// Enabled - throw case (disallowing by throwing exception)
Configuration configuration = new Configuration();
configuration.set(
ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT, ClusterOptions.UserSystemExitMode.THROW);
FlinkSecurityManager flinkSecurityManager =
FlinkSecurityManager.fromConfiguration(configuration);
assertThat(flinkSecurityManager).isNotNull();
assertThat(flinkSecurityManager.userSystemExitMonitored()).isFalse();
flinkSecurityManager.monitorUserSystemExit();
assertThat(flinkSecurityManager.userSystemExitMonitored()).isTrue();
FlinkSecurityManager finalFlinkSecurityManager = flinkSecurityManager;
assertThatThrownBy(() -> finalFlinkSecurityManager.checkExit(TEST_EXIT_CODE))
.isInstanceOf(UserSystemExitException.class);
flinkSecurityManager.unmonitorUserSystemExit();
assertThat(flinkSecurityManager.userSystemExitMonitored()).isFalse();
// Test for disabled test to check if exit is still allowed (fromConfiguration gives null
// since currently
// there is only one option to have a valid security manager, so test with constructor).
flinkSecurityManager =
new FlinkSecurityManager(ClusterOptions.UserSystemExitMode.DISABLED, false);
flinkSecurityManager.monitorUserSystemExit();
assertThat(flinkSecurityManager.userSystemExitMonitored()).isTrue();
flinkSecurityManager.checkExit(TEST_EXIT_CODE);
}
@Test
void testHaltConfiguration() {
// Halt as forceful shutdown replacing graceful system exit
Configuration configuration = new Configuration();
configuration.set(ClusterOptions.HALT_ON_FATAL_ERROR, true);
FlinkSecurityManager flinkSecurityManager =
FlinkSecurityManager.fromConfiguration(configuration);
assertThat(flinkSecurityManager).isNotNull();
}
@Test
void testInvalidConfiguration() {
assertThatThrownBy(
() -> {
Configuration configuration = new Configuration();
configuration.set(ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT, null);
FlinkSecurityManager.fromConfiguration(configuration);
})
.isInstanceOf(NullPointerException.class);
}
@Test
void testExistingSecurityManagerRespected() {
// Don't set the following security manager directly to system, which makes test hang.
SecurityManager originalSecurityManager =
new SecurityManager() {
@Override
public void checkPermission(Permission perm) {
throw new SecurityException("not allowed");
}
};
FlinkSecurityManager flinkSecurityManager =
new FlinkSecurityManager(
ClusterOptions.UserSystemExitMode.DISABLED, false, originalSecurityManager);
assertThatThrownBy(() -> flinkSecurityManager.checkExit(TEST_EXIT_CODE))
.isInstanceOf(SecurityException.class)
.hasMessage("not allowed");
}
@Test
void testRegistrationNotAllowedByExistingSecurityManager() {
Configuration configuration = new Configuration();
configuration.set(
ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT, ClusterOptions.UserSystemExitMode.THROW);
System.setSecurityManager(
new SecurityManager() {
private boolean fired;
@Override
public void checkPermission(Permission perm) {
if (!fired && perm.getName().equals("setSecurityManager")) {
try {
throw new SecurityException("not allowed");
} finally {
// Allow removing this manager again
fired = true;
}
}
}
});
assertThatThrownBy(() -> FlinkSecurityManager.setFromConfiguration(configuration))
.isInstanceOf(IllegalConfigurationException.class)
.hasMessageContaining("Could not register security manager");
}
@Test
void testMultiSecurityManagersWithSetFirstAndMonitored() {
Configuration configuration = new Configuration();
configuration.set(
ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT, ClusterOptions.UserSystemExitMode.THROW);
configuration.set(ClusterOptions.HALT_ON_FATAL_ERROR, false);
FlinkSecurityManager.setFromConfiguration(configuration);
TestExitSecurityManager newSecurityManager = new TestExitSecurityManager();
System.setSecurityManager(newSecurityManager);
FlinkSecurityManager.monitorUserSystemExitForCurrentThread();
assertThatThrownBy(() -> newSecurityManager.checkExit(TEST_EXIT_CODE))
.isInstanceOf(UserSystemExitException.class);
assertThat(newSecurityManager.getExitStatus()).isEqualTo(TEST_EXIT_CODE);
}
@Test
void testMultiSecurityManagersWithSetLastAndMonitored() {
Configuration configuration = new Configuration();
configuration.set(
ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT, ClusterOptions.UserSystemExitMode.THROW);
configuration.set(ClusterOptions.HALT_ON_FATAL_ERROR, false);
TestExitSecurityManager oldSecurityManager = new TestExitSecurityManager();
System.setSecurityManager(oldSecurityManager);
FlinkSecurityManager.setFromConfiguration(configuration);
FlinkSecurityManager.monitorUserSystemExitForCurrentThread();
assertThatThrownBy(() -> System.getSecurityManager().checkExit(TEST_EXIT_CODE))
.isInstanceOf(UserSystemExitException.class);
assertThat(oldSecurityManager.getExitStatus()).isNull();
}
@Test
void testMultiSecurityManagersWithSetFirstAndUnmonitored() {
Configuration configuration = new Configuration();
configuration.set(
ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT, ClusterOptions.UserSystemExitMode.THROW);
configuration.set(ClusterOptions.HALT_ON_FATAL_ERROR, false);
FlinkSecurityManager.setFromConfiguration(configuration);
TestExitSecurityManager newSecurityManager = new TestExitSecurityManager();
System.setSecurityManager(newSecurityManager);
newSecurityManager.checkExit(TEST_EXIT_CODE);
assertThat(newSecurityManager.getExitStatus()).isEqualTo(TEST_EXIT_CODE);
}
@Test
void testMultiSecurityManagersWithSetLastAndUnmonitored() {
Configuration configuration = new Configuration();
configuration.set(
ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT, ClusterOptions.UserSystemExitMode.THROW);
configuration.set(ClusterOptions.HALT_ON_FATAL_ERROR, false);
TestExitSecurityManager oldSecurityManager = new TestExitSecurityManager();
System.setSecurityManager(oldSecurityManager);
FlinkSecurityManager.setFromConfiguration(configuration);
System.getSecurityManager().checkExit(TEST_EXIT_CODE);
assertThat(oldSecurityManager.getExitStatus()).isEqualTo(TEST_EXIT_CODE);
}
private | FlinkSecurityManagerTest |
java | elastic__elasticsearch | modules/reindex/src/internalClusterTest/java/org/elasticsearch/index/reindex/ReindexNodeShutdownIT.java | {
"start": 2048,
"end": 6537
} | class ____ extends ESIntegTestCase {
protected static final String INDEX = "reindex-shutdown-index";
protected static final String DEST_INDEX = "dest-index";
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Arrays.asList(ReindexPlugin.class);
}
protected ReindexRequestBuilder reindex(String nodeName) {
return new ReindexRequestBuilder(internalCluster().client(nodeName));
}
public void testReindexWithShutdown() throws Exception {
final String masterNodeName = internalCluster().startMasterOnlyNode();
final String dataNodeName = internalCluster().startDataOnlyNode();
/* Maximum time to wait for reindexing tasks to complete before shutdown */
final Settings coordSettings = Settings.builder()
.put(MAXIMUM_REINDEXING_TIMEOUT_SETTING.getKey(), TimeValue.timeValueSeconds(60))
.build();
final String coordNodeName = internalCluster().startCoordinatingOnlyNode(coordSettings);
ensureStableCluster(3);
int numDocs = 20000;
createIndex(numDocs);
createReindexTaskAndShutdown(coordNodeName);
checkDestinationIndex(dataNodeName, numDocs);
}
private void createIndex(int numDocs) {
// INDEX will be created on the dataNode
createIndex(INDEX);
logger.debug("setting up [{}] docs", numDocs);
indexRandom(
true,
false,
true,
IntStream.range(0, numDocs)
.mapToObj(i -> prepareIndex(INDEX).setId(String.valueOf(i)).setSource("n", i))
.collect(Collectors.toList())
);
// Checks that the all documents have been indexed and correctly counted
assertHitCount(prepareSearch(INDEX).setSize(0).setTrackTotalHits(true), numDocs);
}
private void createReindexTaskAndShutdown(final String coordNodeName) throws Exception {
AbstractBulkByScrollRequestBuilder<?, ?> builder = reindex(coordNodeName).source(INDEX).destination(DEST_INDEX);
AbstractBulkByScrollRequest<?> reindexRequest = builder.request();
ShutdownPrepareService shutdownPrepareService = internalCluster().getInstance(ShutdownPrepareService.class, coordNodeName);
TaskManager taskManager = internalCluster().getInstance(TransportService.class, coordNodeName).getTaskManager();
// Now execute the reindex action...
ActionListener<BulkByScrollResponse> reindexListener = new ActionListener<BulkByScrollResponse>() {
@Override
public void onResponse(BulkByScrollResponse bulkByScrollResponse) {
assertNull(bulkByScrollResponse.getReasonCancelled());
logger.debug(bulkByScrollResponse.toString());
}
@Override
public void onFailure(Exception e) {
logger.debug("Encounterd " + e.toString());
fail(e, "Encounterd " + e.toString());
}
};
internalCluster().client(coordNodeName).execute(ReindexAction.INSTANCE, reindexRequest, reindexListener);
// Check for reindex task to appear in the tasks list and Immediately stop coordinating node
waitForTask(ReindexAction.INSTANCE.name(), coordNodeName);
shutdownPrepareService.prepareForShutdown(taskManager);
internalCluster().stopNode(coordNodeName);
}
// Make sure all documents from the source index have been re-indexed into the destination index
private void checkDestinationIndex(String dataNodeName, int numDocs) throws Exception {
assertTrue(indexExists(DEST_INDEX));
flushAndRefresh(DEST_INDEX);
assertBusy(() -> { assertHitCount(prepareSearch(DEST_INDEX).setSize(0).setTrackTotalHits(true), numDocs); });
}
private static void waitForTask(String actionName, String nodeName) throws Exception {
assertBusy(() -> {
ListTasksResponse tasks = clusterAdmin().prepareListTasks(nodeName).setActions(actionName).setDetailed(true).get();
tasks.rethrowFailures("Find my task");
for (TaskInfo taskInfo : tasks.getTasks()) {
// Skip tasks with a parent because those are children of the task we want
if (taskInfo.parentTaskId().isSet() == false) return;
}
fail("Couldn't find task after waiting, tasks=" + tasks.getTasks());
}, 10, TimeUnit.SECONDS);
}
}
| ReindexNodeShutdownIT |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/SingularAttributeSourceOneToOne.java | {
"start": 205,
"end": 362
} | interface ____ extends SingularAttributeSourceToOne {
List<DerivedValueSource> getFormulaSources();
boolean isConstrained();
}
| SingularAttributeSourceOneToOne |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/network/netty/NettyPartitionRequestClient.java | {
"start": 13328,
"end": 13701
} | class ____ extends ClientOutboundMessage {
private ResumeConsumptionMessage(RemoteInputChannel inputChannel) {
super(checkNotNull(inputChannel));
}
@Override
Object buildMessage() {
return new NettyMessage.ResumeConsumption(inputChannel.getInputChannelId());
}
}
private static | ResumeConsumptionMessage |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/FluxZipIterable.java | {
"start": 1214,
"end": 2194
} | class ____<T, U, R> extends InternalFluxOperator<T, R> {
final Iterable<? extends U> other;
final BiFunction<? super T, ? super U, ? extends R> zipper;
FluxZipIterable(Flux<? extends T> source,
Iterable<? extends U> other,
BiFunction<? super T, ? super U, ? extends R> zipper) {
super(source);
this.other = Objects.requireNonNull(other, "other");
this.zipper = Objects.requireNonNull(zipper, "zipper");
}
@Override
public @Nullable CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super R> actual) {
Iterator<? extends U> it = Objects.requireNonNull(other.iterator(),
"The other iterable produced a null iterator");
boolean b = it.hasNext();
if (!b) {
Operators.complete(actual);
return null;
}
return new ZipSubscriber<>(actual, it, zipper);
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return super.scanUnsafe(key);
}
static final | FluxZipIterable |
java | micronaut-projects__micronaut-core | context/src/main/java/io/micronaut/scheduling/cron/CronExpression.java | {
"start": 12614,
"end": 12673
} | class ____ represent a cron field part.
*/
static | that |
java | apache__maven | api/maven-api-xml/src/main/java/org/apache/maven/api/xml/XmlNode.java | {
"start": 1878,
"end": 11311
} | interface ____ {
@Deprecated(since = "4.0.0", forRemoval = true)
String CHILDREN_COMBINATION_MODE_ATTRIBUTE = XmlService.CHILDREN_COMBINATION_MODE_ATTRIBUTE;
@Deprecated(since = "4.0.0", forRemoval = true)
String CHILDREN_COMBINATION_MERGE = XmlService.CHILDREN_COMBINATION_MERGE;
@Deprecated(since = "4.0.0", forRemoval = true)
String CHILDREN_COMBINATION_APPEND = XmlService.CHILDREN_COMBINATION_APPEND;
/**
* This default mode for combining children DOMs during merge means that where element names match, the process will
* try to merge the element data, rather than putting the dominant and recessive elements (which share the same
* element name) as siblings in the resulting DOM.
*/
@Deprecated(since = "4.0.0", forRemoval = true)
String DEFAULT_CHILDREN_COMBINATION_MODE = XmlService.DEFAULT_CHILDREN_COMBINATION_MODE;
@Deprecated(since = "4.0.0", forRemoval = true)
String SELF_COMBINATION_MODE_ATTRIBUTE = XmlService.SELF_COMBINATION_MODE_ATTRIBUTE;
@Deprecated(since = "4.0.0", forRemoval = true)
String SELF_COMBINATION_OVERRIDE = XmlService.SELF_COMBINATION_OVERRIDE;
@Deprecated(since = "4.0.0", forRemoval = true)
String SELF_COMBINATION_MERGE = XmlService.SELF_COMBINATION_MERGE;
@Deprecated(since = "4.0.0", forRemoval = true)
String SELF_COMBINATION_REMOVE = XmlService.SELF_COMBINATION_REMOVE;
/**
* In case of complex XML structures, combining can be done based on id.
*/
@Deprecated(since = "4.0.0", forRemoval = true)
String ID_COMBINATION_MODE_ATTRIBUTE = XmlService.ID_COMBINATION_MODE_ATTRIBUTE;
/**
* In case of complex XML structures, combining can be done based on keys.
* This is a comma separated list of attribute names.
*/
@Deprecated(since = "4.0.0", forRemoval = true)
String KEYS_COMBINATION_MODE_ATTRIBUTE = XmlService.KEYS_COMBINATION_MODE_ATTRIBUTE;
/**
* This default mode for combining a DOM node during merge means that where element names match, the process will
* try to merge the element attributes and values, rather than overriding the recessive element completely with the
* dominant one. This means that wherever the dominant element doesn't provide the value or a particular attribute,
* that value or attribute will be set from the recessive DOM node.
*/
@Deprecated(since = "4.0.0", forRemoval = true)
String DEFAULT_SELF_COMBINATION_MODE = XmlService.DEFAULT_SELF_COMBINATION_MODE;
/**
* Returns the local name of this XML node.
*
* @return the node name, never {@code null}
*/
@Nonnull
String name();
/**
* Returns the namespace URI of this XML node.
*
* @return the namespace URI, never {@code null} (empty string if no namespace)
*/
@Nonnull
String namespaceUri();
/**
* Returns the namespace prefix of this XML node.
*
* @return the namespace prefix, never {@code null} (empty string if no prefix)
*/
@Nonnull
String prefix();
/**
* Returns the text content of this XML node.
*
* @return the node's text value, or {@code null} if none exists
*/
@Nullable
String value();
/**
* Returns an immutable map of all attributes defined on this XML node.
*
* @return map of attribute names to values, never {@code null}
*/
@Nonnull
Map<String, String> attributes();
/**
* Returns the value of a specific attribute.
*
* @param name the name of the attribute to retrieve
* @return the attribute value, or {@code null} if the attribute doesn't exist
* @throws NullPointerException if name is null
*/
@Nullable
String attribute(@Nonnull String name);
/**
* Returns an immutable list of all child nodes.
*
* @return list of child nodes, never {@code null}
*/
@Nonnull
List<XmlNode> children();
/**
* Returns the first child node with the specified name.
*
* @param name the name of the child node to find
* @return the first matching child node, or {@code null} if none found
*/
@Nullable
XmlNode child(String name);
/**
* Returns the input location information for this node, if available.
* This can be useful for error reporting and debugging.
*
* @return the input location object, or {@code null} if not available
*/
@Nullable
Object inputLocation();
// Deprecated methods that delegate to new ones
@Deprecated(since = "4.0.0", forRemoval = true)
@Nonnull
default String getName() {
return name();
}
@Deprecated(since = "4.0.0", forRemoval = true)
@Nonnull
default String getNamespaceUri() {
return namespaceUri();
}
@Deprecated(since = "4.0.0", forRemoval = true)
@Nonnull
default String getPrefix() {
return prefix();
}
@Deprecated(since = "4.0.0", forRemoval = true)
@Nullable
default String getValue() {
return value();
}
@Deprecated(since = "4.0.0", forRemoval = true)
@Nonnull
default Map<String, String> getAttributes() {
return attributes();
}
@Deprecated(since = "4.0.0", forRemoval = true)
@Nullable
default String getAttribute(@Nonnull String name) {
return attribute(name);
}
@Deprecated(since = "4.0.0", forRemoval = true)
@Nonnull
default List<XmlNode> getChildren() {
return children();
}
@Deprecated(since = "4.0.0", forRemoval = true)
@Nullable
default XmlNode getChild(String name) {
return child(name);
}
@Deprecated(since = "4.0.0", forRemoval = true)
@Nullable
default Object getInputLocation() {
return inputLocation();
}
/**
* @deprecated use {@link XmlService#merge(XmlNode, XmlNode, Boolean)} instead
*/
@Deprecated(since = "4.0.0", forRemoval = true)
default XmlNode merge(@Nullable XmlNode source) {
return XmlService.merge(this, source);
}
/**
* @deprecated use {@link XmlService#merge(XmlNode, XmlNode, Boolean)} instead
*/
@Deprecated(since = "4.0.0", forRemoval = true)
default XmlNode merge(@Nullable XmlNode source, @Nullable Boolean childMergeOverride) {
return XmlService.merge(this, source, childMergeOverride);
}
/**
* Merge recessive into dominant and return either {@code dominant}
* with merged information or a clone of {@code recessive} if
* {@code dominant} is {@code null}.
*
* @param dominant the node
* @param recessive if {@code null}, nothing will happen
* @return the merged node
*
* @deprecated use {@link XmlService#merge(XmlNode, XmlNode, Boolean)} instead
*/
@Deprecated(since = "4.0.0", forRemoval = true)
@Nullable
static XmlNode merge(@Nullable XmlNode dominant, @Nullable XmlNode recessive) {
return XmlService.merge(dominant, recessive, null);
}
@Nullable
static XmlNode merge(
@Nullable XmlNode dominant, @Nullable XmlNode recessive, @Nullable Boolean childMergeOverride) {
return XmlService.merge(dominant, recessive, childMergeOverride);
}
/**
* Creates a new XmlNode instance with the specified name.
*
* @param name the name for the new node
* @return a new XmlNode instance
* @throws NullPointerException if name is null
*/
static XmlNode newInstance(String name) {
return newBuilder().name(name).build();
}
/**
* Creates a new XmlNode instance with the specified name and value.
*
* @param name the name for the new node
* @param value the value for the new node
* @return a new XmlNode instance
* @throws NullPointerException if name is null
*/
static XmlNode newInstance(String name, String value) {
return newBuilder().name(name).value(value).build();
}
/**
* Creates a new XmlNode instance with the specified name and children.
*
* @param name the name for the new node
* @param children the list of child nodes
* @return a new XmlNode instance
* @throws NullPointerException if name is null
*/
static XmlNode newInstance(String name, List<XmlNode> children) {
return newBuilder().name(name).children(children).build();
}
/**
* Creates a new XmlNode instance with all properties specified.
*
* @param name the name for the new node
* @param value the value for the new node
* @param attrs the attributes for the new node
* @param children the list of child nodes
* @param location the input location information
* @return a new XmlNode instance
* @throws NullPointerException if name is null
*/
static XmlNode newInstance(
String name, String value, Map<String, String> attrs, List<XmlNode> children, Object location) {
return newBuilder()
.name(name)
.value(value)
.attributes(attrs)
.children(children)
.inputLocation(location)
.build();
}
/**
* Returns a new builder for creating XmlNode instances.
*
* @return a new Builder instance
*/
static Builder newBuilder() {
return new Builder();
}
/**
* Builder | XmlNode |
java | apache__dubbo | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/command/HttpChannelQueueCommand.java | {
"start": 1030,
"end": 1426
} | class ____ extends CompletableFuture<Void>
implements QueueCommand, HttpChannelHolder {
private HttpChannelHolder httpChannelHolder;
public void setHttpChannel(HttpChannelHolder httpChannelHolder) {
this.httpChannelHolder = httpChannelHolder;
}
public HttpChannel getHttpChannel() {
return httpChannelHolder.getHttpChannel();
}
}
| HttpChannelQueueCommand |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/subscriptions/DeferredScalarSubscription.java | {
"start": 1549,
"end": 6981
} | class ____<@NonNull T> extends BasicIntQueueSubscription<T> {
private static final long serialVersionUID = -2151279923272604993L;
/** The Subscriber to emit the value to. */
protected final Subscriber<? super T> downstream;
/** The value is stored here if there is no request yet or in fusion mode. */
protected T value;
/** Indicates this Subscription has no value and not requested yet. */
static final int NO_REQUEST_NO_VALUE = 0;
/** Indicates this Subscription has a value but not requested yet. */
static final int NO_REQUEST_HAS_VALUE = 1;
/** Indicates this Subscription has been requested but there is no value yet. */
static final int HAS_REQUEST_NO_VALUE = 2;
/** Indicates this Subscription has both request and value. */
static final int HAS_REQUEST_HAS_VALUE = 3;
/** Indicates the Subscription has been cancelled. */
static final int CANCELLED = 4;
/** Indicates this Subscription is in fusion mode and is currently empty. */
static final int FUSED_EMPTY = 8;
/** Indicates this Subscription is in fusion mode and has a value. */
static final int FUSED_READY = 16;
/** Indicates this Subscription is in fusion mode and its value has been consumed. */
static final int FUSED_CONSUMED = 32;
/**
* Creates a DeferredScalarSubscription by wrapping the given Subscriber.
* @param downstream the Subscriber to wrap, not null (not verified)
*/
public DeferredScalarSubscription(Subscriber<? super T> downstream) {
this.downstream = downstream;
}
@Override
public final void request(long n) {
if (SubscriptionHelper.validate(n)) {
for (;;) {
int state = get();
// if the any bits 1-31 are set, we are either in fusion mode (FUSED_*)
// or request has been called (HAS_REQUEST_*)
if ((state & ~NO_REQUEST_HAS_VALUE) != 0) {
return;
}
if (state == NO_REQUEST_HAS_VALUE) {
if (compareAndSet(NO_REQUEST_HAS_VALUE, HAS_REQUEST_HAS_VALUE)) {
T v = value;
if (v != null) {
value = null;
Subscriber<? super T> a = downstream;
a.onNext(v);
if (get() != CANCELLED) {
a.onComplete();
}
}
}
return;
}
if (compareAndSet(NO_REQUEST_NO_VALUE, HAS_REQUEST_NO_VALUE)) {
return;
}
}
}
}
/**
* Completes this subscription by indicating the given value should
* be emitted when the first request arrives.
* <p>Make sure this is called exactly once.
* @param v the value to signal, not null (not validated)
*/
public final void complete(T v) {
int state = get();
for (;;) {
if (state == FUSED_EMPTY) {
value = v;
lazySet(FUSED_READY);
Subscriber<? super T> a = downstream;
a.onNext(null);
if (get() != CANCELLED) {
a.onComplete();
}
return;
}
// if state is >= CANCELLED or bit zero is set (*_HAS_VALUE) case, return
if ((state & ~HAS_REQUEST_NO_VALUE) != 0) {
return;
}
if (state == HAS_REQUEST_NO_VALUE) {
lazySet(HAS_REQUEST_HAS_VALUE);
Subscriber<? super T> a = downstream;
a.onNext(v);
if (get() != CANCELLED) {
a.onComplete();
}
return;
}
value = v;
if (compareAndSet(NO_REQUEST_NO_VALUE, NO_REQUEST_HAS_VALUE)) {
return;
}
state = get();
if (state == CANCELLED) {
value = null;
return;
}
}
}
@Override
public final int requestFusion(int mode) {
if ((mode & ASYNC) != 0) {
lazySet(FUSED_EMPTY);
return ASYNC;
}
return NONE;
}
@Nullable
@Override
public final T poll() {
if (get() == FUSED_READY) {
lazySet(FUSED_CONSUMED);
T v = value;
value = null;
return v;
}
return null;
}
@Override
public final boolean isEmpty() {
return get() != FUSED_READY;
}
@Override
public final void clear() {
lazySet(FUSED_CONSUMED);
value = null;
}
@Override
public void cancel() {
set(CANCELLED);
value = null;
}
/**
* Returns true if this Subscription has been cancelled.
* @return true if this Subscription has been cancelled
*/
public final boolean isCancelled() {
return get() == CANCELLED;
}
/**
* Atomically sets a cancelled state and returns true if
* the current thread did it successfully.
* @return true if the current thread cancelled
*/
public final boolean tryCancel() {
return getAndSet(CANCELLED) != CANCELLED;
}
}
| DeferredScalarSubscription |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/targetclass/mixed/AroundInvokeOnTargetClassAndOutsideAndSuperclassesTest.java | {
"start": 1937,
"end": 2205
} | class ____ {
@AroundInvoke
Object superIntercept(InvocationContext ctx) throws Exception {
return "super-outside: " + ctx.proceed();
}
}
@MyInterceptorBinding
@Interceptor
@Priority(1)
static | MyInterceptorSuperclass |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/pi/math/Summation.java | {
"start": 1110,
"end": 8094
} | class ____ implements Container<Summation>, Combinable<Summation> {
/** Variable n in the summation. */
public final ArithmeticProgression N;
/** Variable e in the summation. */
public final ArithmeticProgression E;
private Double value = null;
/** Constructor */
public Summation(ArithmeticProgression N, ArithmeticProgression E) {
if (N.getSteps() != E.getSteps()) {
throw new IllegalArgumentException("N.getSteps() != E.getSteps(),"
+ "\n N.getSteps()=" + N.getSteps() + ", N=" + N
+ "\n E.getSteps()=" + E.getSteps() + ", E=" + E);
}
this.N = N;
this.E = E;
}
/** Constructor */
Summation(long valueN, long deltaN,
long valueE, long deltaE, long limitE) {
this(valueN, deltaN, valueN - deltaN*((valueE - limitE)/deltaE),
valueE, deltaE, limitE);
}
/** Constructor */
Summation(long valueN, long deltaN, long limitN,
long valueE, long deltaE, long limitE) {
this(new ArithmeticProgression('n', valueN, deltaN, limitN),
new ArithmeticProgression('e', valueE, deltaE, limitE));
}
/** {@inheritDoc} */
@Override
public Summation getElement() {return this;}
/** Return the number of steps of this summation */
long getSteps() {return E.getSteps();}
/** Return the value of this summation */
public Double getValue() {return value;}
/** Set the value of this summation */
public void setValue(double v) {this.value = v;}
/** {@inheritDoc} */
@Override
public String toString() {
return "[" + N + "; " + E + (value == null? "]": "]value=" + Double.doubleToLongBits(value));
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj != null && obj instanceof Summation) {
final Summation that = (Summation)obj;
return this.N.equals(that.N) && this.E.equals(that.E);
}
throw new IllegalArgumentException(obj == null? "obj == null":
"obj.getClass()=" + obj.getClass());
}
/** Not supported */
@Override
public int hashCode() {
throw new UnsupportedOperationException();
}
/** Covert a String to a Summation. */
public static Summation valueOf(final String s) {
int i = 1;
int j = s.indexOf("; ", i);
if (j < 0)
throw new IllegalArgumentException("i=" + i + ", j=" + j + " < 0, s=" + s);
final ArithmeticProgression N = ArithmeticProgression.valueOf(s.substring(i, j));
i = j + 2;
j = s.indexOf("]", i);
if (j < 0)
throw new IllegalArgumentException("i=" + i + ", j=" + j + " < 0, s=" + s);
final ArithmeticProgression E = ArithmeticProgression.valueOf(s.substring(i, j));
final Summation sigma = new Summation(N, E);
i = j + 1;
if (s.length() > i) {
final String value = Util.parseStringVariable("value", s.substring(i));
sigma.setValue(value.indexOf('.') < 0?
Double.longBitsToDouble(Long.parseLong(value)):
Double.parseDouble(value));
}
return sigma;
}
/** Compute the value of the summation. */
public double compute() {
if (value == null)
value = N.limit <= MAX_MODULAR? compute_modular(): compute_montgomery();
return value;
}
private static final long MAX_MODULAR = 1L << 32;
/** Compute the value using {@link Modular#mod(long, long)}. */
double compute_modular() {
long e = E.value;
long n = N.value;
double s = 0;
for(; e > E.limit; e += E.delta) {
s = Modular.addMod(s, Modular.mod(e, n)/(double)n);
n += N.delta;
}
return s;
}
final Montgomery montgomery = new Montgomery();
/** Compute the value using {@link Montgomery#mod(long)}. */
double compute_montgomery() {
long e = E.value;
long n = N.value;
double s = 0;
for(; e > E.limit; e += E.delta) {
s = Modular.addMod(s, montgomery.set(n).mod(e)/(double)n);
n += N.delta;
}
return s;
}
/** {@inheritDoc} */
@Override
public int compareTo(Summation that) {
final int de = this.E.compareTo(that.E);
if (de != 0) return de;
return this.N.compareTo(that.N);
}
/** {@inheritDoc} */
@Override
public Summation combine(Summation that) {
if (this.N.delta != that.N.delta || this.E.delta != that.E.delta)
throw new IllegalArgumentException(
"this.N.delta != that.N.delta || this.E.delta != that.E.delta"
+ ",\n this=" + this
+ ",\n that=" + that);
if (this.E.limit == that.E.value && this.N.limit == that.N.value) {
final double v = Modular.addMod(this.value, that.value);
final Summation s = new Summation(
new ArithmeticProgression(N.symbol, N.value, N.delta, that.N.limit),
new ArithmeticProgression(E.symbol, E.value, E.delta, that.E.limit));
s.setValue(v);
return s;
}
return null;
}
/** Find the remaining terms. */
public <T extends Container<Summation>> List<Summation> remainingTerms(List<T> sorted) {
final List<Summation> results = new ArrayList<Summation>();
Summation remaining = this;
if (sorted != null)
for(Container<Summation> c : sorted) {
final Summation sigma = c.getElement();
if (!remaining.contains(sigma))
throw new IllegalArgumentException("!remaining.contains(s),"
+ "\n remaining = " + remaining
+ "\n s = " + sigma
+ "\n this = " + this
+ "\n sorted = " + sorted);
final Summation s = new Summation(sigma.N.limit, N.delta, remaining.N.limit,
sigma.E.limit, E.delta, remaining.E.limit);
if (s.getSteps() > 0)
results.add(s);
remaining = new Summation(remaining.N.value, N.delta, sigma.N.value,
remaining.E.value, E.delta, sigma.E.value);
}
if (remaining.getSteps() > 0)
results.add(remaining);
return results;
}
/** Does this contains that? */
public boolean contains(Summation that) {
return this.N.contains(that.N) && this.E.contains(that.E);
}
/** Partition the summation. */
public Summation[] partition(final int nParts) {
final Summation[] parts = new Summation[nParts];
final long steps = (E.limit - E.value)/E.delta + 1;
long prevN = N.value;
long prevE = E.value;
for(int i = 1; i < parts.length; i++) {
final long k = (i * steps)/parts.length;
final long currN = N.skip(k);
final long currE = E.skip(k);
parts[i - 1] = new Summation(
new ArithmeticProgression(N.symbol, prevN, N.delta, currN),
new ArithmeticProgression(E.symbol, prevE, E.delta, currE));
prevN = currN;
prevE = currE;
}
parts[parts.length - 1] = new Summation(
new ArithmeticProgression(N.symbol, prevN, N.delta, N.limit),
new ArithmeticProgression(E.symbol, prevE, E.delta, E.limit));
return parts;
}
} | Summation |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/flowable/NotificationLiteTest.java | {
"start": 1066,
"end": 4609
} | class ____ extends RxJavaTest {
@Test
public void complete() {
Object n = NotificationLite.next("Hello");
Object c = NotificationLite.complete();
assertTrue(NotificationLite.isComplete(c));
assertFalse(NotificationLite.isComplete(n));
assertEquals("Hello", NotificationLite.getValue(n));
}
@Test
public void valueKind() {
assertSame(1, NotificationLite.next(1));
}
@Test
public void soloEnum() {
TestHelper.checkEnum(NotificationLite.class);
}
@Test
public void errorNotification() {
Object o = NotificationLite.error(new TestException());
assertEquals("NotificationLite.Error[io.reactivex.rxjava3.exceptions.TestException]", o.toString());
assertTrue(NotificationLite.isError(o));
assertFalse(NotificationLite.isComplete(o));
assertFalse(NotificationLite.isDisposable(o));
assertFalse(NotificationLite.isSubscription(o));
assertTrue(NotificationLite.getError(o) instanceof TestException);
}
@Test
public void completeNotification() {
Object o = NotificationLite.complete();
Object o2 = NotificationLite.complete();
assertSame(o, o2);
assertFalse(NotificationLite.isError(o));
assertTrue(NotificationLite.isComplete(o));
assertFalse(NotificationLite.isDisposable(o));
assertFalse(NotificationLite.isSubscription(o));
assertEquals("NotificationLite.Complete", o.toString());
assertTrue(NotificationLite.isComplete(o));
}
@Test
public void disposableNotification() {
Object o = NotificationLite.disposable(Disposable.empty());
assertEquals("NotificationLite.Disposable[RunnableDisposable(disposed=false, EmptyRunnable)]", o.toString());
assertFalse(NotificationLite.isError(o));
assertFalse(NotificationLite.isComplete(o));
assertTrue(NotificationLite.isDisposable(o));
assertFalse(NotificationLite.isSubscription(o));
assertNotNull(NotificationLite.getDisposable(o));
}
@Test
public void subscriptionNotification() {
Object o = NotificationLite.subscription(new BooleanSubscription());
assertEquals("NotificationLite.Subscription[BooleanSubscription(cancelled=false)]", o.toString());
assertFalse(NotificationLite.isError(o));
assertFalse(NotificationLite.isComplete(o));
assertFalse(NotificationLite.isDisposable(o));
assertTrue(NotificationLite.isSubscription(o));
assertNotNull(NotificationLite.getSubscription(o));
}
// TODO this test is no longer relevant as nulls are not allowed and value maps to itself
// @Test
// public void testValueKind() {
// assertTrue(NotificationLite.isNull(NotificationLite.next(null)));
// assertFalse(NotificationLite.isNull(NotificationLite.next(1)));
// assertFalse(NotificationLite.isNull(NotificationLite.error(new TestException())));
// assertFalse(NotificationLite.isNull(NotificationLite.completed()));
// assertFalse(NotificationLite.isNull(null));
//
// assertTrue(NotificationLite.isNext(NotificationLite.next(null)));
// assertTrue(NotificationLite.isNext(NotificationLite.next(1)));
// assertFalse(NotificationLite.isNext(NotificationLite.completed()));
// assertFalse(NotificationLite.isNext(null));
// assertFalse(NotificationLite.isNext(NotificationLite.error(new TestException())));
// }
}
| NotificationLiteTest |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/dispatcher/cleanup/DispatcherResourceCleanerFactoryTest.java | {
"start": 2521,
"end": 9793
} | class ____ {
private static final JobID JOB_ID = new JobID();
private CleanableBlobServer blobServer;
private CompletableFuture<JobID> jobManagerRunnerRegistryLocalCleanupFuture;
private CompletableFuture<Void> jobManagerRunnerRegistryLocalCleanupResultFuture;
private CompletableFuture<JobID> executionPlanWriterLocalCleanupFuture;
private CompletableFuture<JobID> executionPlanWriterGlobalCleanupFuture;
private CompletableFuture<JobID> highAvailabilityServicesGlobalCleanupFuture;
private JobManagerMetricGroup jobManagerMetricGroup;
private DispatcherResourceCleanerFactory testInstance;
@BeforeEach
public void setup() throws Exception {
blobServer = new CleanableBlobServer();
MetricRegistry metricRegistry = TestingMetricRegistry.builder().build();
jobManagerMetricGroup =
JobManagerMetricGroup.createJobManagerMetricGroup(
metricRegistry, "ignored hostname");
jobManagerMetricGroup.addJob(JOB_ID, "ignored job name");
testInstance =
new DispatcherResourceCleanerFactory(
Executors.directExecutor(),
TestingRetryStrategies.NO_RETRY_STRATEGY,
createJobManagerRunnerRegistry(),
createExecutionPlanWriter(),
blobServer,
createHighAvailabilityServices(),
jobManagerMetricGroup);
}
private JobManagerRunnerRegistry createJobManagerRunnerRegistry() {
jobManagerRunnerRegistryLocalCleanupFuture = new CompletableFuture<>();
jobManagerRunnerRegistryLocalCleanupResultFuture = new CompletableFuture<>();
return TestingJobManagerRunnerRegistry.builder()
.withLocalCleanupAsyncFunction(
(jobId, executor) -> {
jobManagerRunnerRegistryLocalCleanupFuture.complete(jobId);
return jobManagerRunnerRegistryLocalCleanupResultFuture;
})
.build();
}
private ExecutionPlanWriter createExecutionPlanWriter() throws Exception {
executionPlanWriterLocalCleanupFuture = new CompletableFuture<>();
executionPlanWriterGlobalCleanupFuture = new CompletableFuture<>();
final TestingExecutionPlanStore executionPlanStore =
TestingExecutionPlanStore.newBuilder()
.setGlobalCleanupFunction(
(jobId, executor) -> {
executionPlanWriterGlobalCleanupFuture.complete(jobId);
return FutureUtils.completedVoidFuture();
})
.setLocalCleanupFunction(
(jobId, ignoredExecutor) -> {
executionPlanWriterLocalCleanupFuture.complete(jobId);
return FutureUtils.completedVoidFuture();
})
.build();
executionPlanStore.start(null);
return executionPlanStore;
}
private HighAvailabilityServices createHighAvailabilityServices() {
highAvailabilityServicesGlobalCleanupFuture = new CompletableFuture<>();
final TestingHighAvailabilityServices haServices = new TestingHighAvailabilityServices();
haServices.setGlobalCleanupFuture(highAvailabilityServicesGlobalCleanupFuture);
return haServices;
}
@Test
public void testLocalResourceCleaning() {
assertCleanupNotTriggered();
final CompletableFuture<Void> cleanupResultFuture =
testInstance
.createLocalResourceCleaner(
ComponentMainThreadExecutorServiceAdapter.forMainThread())
.cleanupAsync(JOB_ID);
assertWaitingForPrioritizedCleanupToFinish();
assertThat(cleanupResultFuture).isNotCompleted();
// makes the prioritized JobManagerRunner cleanup result terminate so that other cleanups
// are triggered
jobManagerRunnerRegistryLocalCleanupResultFuture.complete(null);
assertThat(jobManagerRunnerRegistryLocalCleanupFuture).isCompleted();
assertThat(executionPlanWriterLocalCleanupFuture).isCompleted();
assertThat(executionPlanWriterGlobalCleanupFuture).isNotDone();
assertThat(blobServer.getLocalCleanupFuture()).isCompleted();
assertThat(blobServer.getGlobalCleanupFuture()).isNotDone();
assertThat(highAvailabilityServicesGlobalCleanupFuture).isNotDone();
assertJobMetricGroupCleanedUp();
assertThat(cleanupResultFuture).isCompleted();
}
@Test
public void testGlobalResourceCleaning()
throws ExecutionException, InterruptedException, TimeoutException {
assertCleanupNotTriggered();
final CompletableFuture<Void> cleanupResultFuture =
testInstance
.createGlobalResourceCleaner(
ComponentMainThreadExecutorServiceAdapter.forMainThread())
.cleanupAsync(JOB_ID);
assertWaitingForPrioritizedCleanupToFinish();
assertThat(cleanupResultFuture).isNotCompleted();
// makes the prioritized JobManagerRunner cleanup result terminate so that other cleanups
// are triggered
jobManagerRunnerRegistryLocalCleanupResultFuture.complete(null);
assertThat(jobManagerRunnerRegistryLocalCleanupFuture).isCompleted();
assertThat(executionPlanWriterLocalCleanupFuture).isNotDone();
assertThat(executionPlanWriterGlobalCleanupFuture).isCompleted();
assertThat(blobServer.getLocalCleanupFuture()).isNotDone();
assertThat(blobServer.getGlobalCleanupFuture()).isCompleted();
assertThat(highAvailabilityServicesGlobalCleanupFuture).isCompleted();
assertJobMetricGroupCleanedUp();
assertThat(cleanupResultFuture).isCompleted();
}
private void assertCleanupNotTriggered() {
assertThat(jobManagerRunnerRegistryLocalCleanupFuture).isNotDone();
assertNoRegularCleanupsTriggered();
}
private void assertWaitingForPrioritizedCleanupToFinish() {
assertThat(jobManagerRunnerRegistryLocalCleanupFuture).isCompleted();
assertNoRegularCleanupsTriggered();
}
private void assertNoRegularCleanupsTriggered() {
assertThat(executionPlanWriterLocalCleanupFuture).isNotDone();
assertThat(executionPlanWriterGlobalCleanupFuture).isNotDone();
assertThat(blobServer.getLocalCleanupFuture()).isNotDone();
assertThat(blobServer.getGlobalCleanupFuture()).isNotDone();
assertThat(highAvailabilityServicesGlobalCleanupFuture).isNotDone();
// check whether the registered job is still listed
assertThat(jobManagerMetricGroup.numRegisteredJobMetricGroups()).isEqualTo(1);
}
private void assertJobMetricGroupCleanedUp() {
assertThat(jobManagerMetricGroup.numRegisteredJobMetricGroups()).isEqualTo(0);
}
private static | DispatcherResourceCleanerFactoryTest |
java | apache__camel | components/camel-aws/camel-aws-xray/src/test/java/org/apache/camel/component/aws/xray/json/JsonTest.java | {
"start": 1149,
"end": 10799
} | class ____ {
@Test
public void testJsonParse() {
JsonStructure json = JsonParser.parse("{\n"
+ " \"test\": \"some string\",\n"
+ " \"otherKey\": true,\n"
+ " \"nextKey\": 1234,\n"
+ " \"doubleKey\": 1234.567,\n"
+ " \"subElement\": {\n"
+ " \"subKey\": \"some other string\",\n"
+ " \"complexString\": \"String with JSON syntax elements like .,\\\" { or }\"\n"
+ " },\n"
+ " \"arrayElement\": [\n"
+ " {\n"
+ " \"id\": 1,\n"
+ " \"name\": \"test1\"\n"
+ " },\n"
+ " {\n"
+ " \"id\": 2,\n"
+ " \"name\": \"test2\"\n"
+ " }\n"
+ " ]\n"
+ "}");
assertThat(json, is(notNullValue()));
assertThat(json, is(instanceOf(JsonObject.class)));
JsonObject jsonObj = (JsonObject) json;
assertThat(jsonObj.getKeys().size(), is(equalTo(6)));
assertThat(jsonObj.getString("test"), is(equalTo("some string")));
assertThat(jsonObj.getBoolean("otherKey"), is(equalTo(true)));
assertThat(jsonObj.getInteger("nextKey"), is(equalTo(1234)));
assertThat(jsonObj.getDouble("doubleKey"), is(equalTo(1234.567)));
assertThat(jsonObj.get("subElement"), is(instanceOf(JsonObject.class)));
JsonObject jsonSub = (JsonObject) jsonObj.get("subElement");
assertThat(jsonSub.getString("subKey"), is(equalTo("some other string")));
assertThat(jsonSub.getString("complexString"), is(equalTo("String with JSON syntax elements like .,\\\" { or }")));
assertThat(jsonObj.get("arrayElement"), is(instanceOf(JsonArray.class)));
JsonArray jsonArr = (JsonArray) jsonObj.get("arrayElement");
assertThat(jsonArr.size(), is(equalTo(2)));
assertThat(jsonArr.get(0), is(instanceOf(JsonObject.class)));
JsonObject arrElem0 = (JsonObject) jsonArr.get(0);
assertThat(arrElem0.getInteger("id"), is(equalTo(1)));
assertThat(arrElem0.getString("name"), is(equalTo("test1")));
assertThat(jsonArr.get(1), is(instanceOf(JsonObject.class)));
JsonObject arrElem1 = (JsonObject) jsonArr.get(1);
assertThat(arrElem1.getInteger("id"), is(equalTo(2)));
assertThat(arrElem1.getString("name"), is(equalTo("test2")));
}
@Test
public void testJsonParseSample() {
JsonStructure json = JsonParser.parse("{"
+ " \"name\":\"b\","
+ " \"id\":\"6ae1778525198ce8\","
+ " \"start_time\":1.50947752281E9,"
+ " \"trace_id\":\"1-59f8cc92-4819a77b4109de34405a5643\","
+ " \"end_time\":1.50947752442E9,"
+ " \"aws\":{"
+ " \"xray\":{"
+ " \"sdk_version\":\"1.2.0\","
+ " \"sdk\":\"X-Ray for Java\""
+ " }"
+ " },"
+ " \"service\":{"
+ " \"runtime\":\"Java HotSpot(TM) 64-Bit Server VM\","
+ " \"runtime_version\":\"1.8.0_144\""
+ " }"
+ "}"
+ "}");
assertThat(json, is(notNullValue()));
JsonObject jsonObj = (JsonObject) json;
assertThat(jsonObj.getKeys().size(), is(equalTo(7)));
assertThat(jsonObj.getString("name"), is(equalTo("b")));
assertThat(jsonObj.getString("id"), is(equalTo("6ae1778525198ce8")));
assertThat(jsonObj.getString("trace_id"), is(equalTo("1-59f8cc92-4819a77b4109de34405a5643")));
assertThat(jsonObj.getDouble("start_time"), is(equalTo(1.50947752281E9)));
assertThat(jsonObj.getDouble("end_time"), is(equalTo(1.50947752442E9)));
assertThat(jsonObj.get("aws"), is(instanceOf(JsonObject.class)));
JsonObject aws = (JsonObject) jsonObj.get("aws");
assertThat(aws.get("xray"), is(instanceOf(JsonObject.class)));
JsonObject xray = (JsonObject) aws.get("xray");
assertThat(xray.getString("sdk_version"), is(equalTo("1.2.0")));
assertThat(xray.getString("sdk"), is(equalTo("X-Ray for Java")));
assertThat(jsonObj.get("service"), is(instanceOf(JsonObject.class)));
JsonObject service = (JsonObject) jsonObj.get("service");
assertThat(service.getString("runtime"), is(equalTo("Java HotSpot(TM) 64-Bit Server VM")));
assertThat(service.getString("runtime_version"), is(equalTo("1.8.0_144")));
}
@Test
public void testJsonParseWithArray() {
JsonStructure json = JsonParser.parse("{"
+ " \"name\":\"c\","
+ " \"id\":\"6ada7c7013b2c681\","
+ " \"start_time\":1.509484895232E9,"
+ " \"trace_id\":\"1-59f8e935-11c64d09c90803f69534c9af\","
+ " \"end_time\":1.509484901458E9,"
+ " \"subsegments\":["
+ " {"
+ " \"name\":\"SendingTo_log_test\","
+ " \"id\":\"545118f5c69e2973\","
+ " \"start_time\":1.509484895813E9,"
+ " \"end_time\":1.509484896709E9"
+ " }"
+ " ],"
+ " \"aws\":{"
+ " \"xray\":{"
+ " \"sdk_version\":\"1.2.0\","
+ " \"sdk\":\"X-Ray for Java\""
+ " }"
+ " },"
+ " \"service\":{"
+ " \"runtime\":\"Java HotSpot(TM) 64-Bit Server VM\","
+ " \"runtime_version\":\"1.8.0_144\""
+ " }"
+ "}\u0000\u0000");
assertThat(json, is(notNullValue()));
JsonObject jsonObj = (JsonObject) json;
assertThat(jsonObj.getKeys().size(), is(equalTo(8)));
assertThat(jsonObj.getString("name"), is(equalTo("c")));
assertThat(jsonObj.getString("id"), is(equalTo("6ada7c7013b2c681")));
assertThat(jsonObj.getString("trace_id"), is(equalTo("1-59f8e935-11c64d09c90803f69534c9af")));
assertThat(jsonObj.getDouble("start_time"), is(equalTo(1.509484895232E9)));
assertThat(jsonObj.getDouble("end_time"), is(equalTo(1.509484901458E9)));
assertThat(jsonObj.get("aws"), is(instanceOf(JsonObject.class)));
JsonObject aws = (JsonObject) jsonObj.get("aws");
assertThat(aws.get("xray"), is(instanceOf(JsonObject.class)));
JsonObject xray = (JsonObject) aws.get("xray");
assertThat(xray.getString("sdk_version"), is(equalTo("1.2.0")));
assertThat(xray.getString("sdk"), is(equalTo("X-Ray for Java")));
assertThat(jsonObj.get("service"), is(instanceOf(JsonObject.class)));
JsonObject service = (JsonObject) jsonObj.get("service");
assertThat(service.getString("runtime"), is(equalTo("Java HotSpot(TM) 64-Bit Server VM")));
assertThat(service.getString("runtime_version"), is(equalTo("1.8.0_144")));
assertThat(jsonObj.get("subsegments"), is(instanceOf(JsonArray.class)));
JsonArray array = (JsonArray) jsonObj.get("subsegments");
assertThat(array.size(), is(equalTo(1)));
assertThat(array.get(0), is(instanceOf(JsonObject.class)));
JsonObject arrItem = (JsonObject) array.get(0);
assertThat(arrItem.getKeys().size(), is(equalTo(4)));
assertThat(arrItem.getString("name"), is(equalTo("SendingTo_log_test")));
assertThat(arrItem.getString("id"), is(equalTo("545118f5c69e2973")));
assertThat(arrItem.getDouble("start_time"), is(equalTo(1.509484895813E9)));
assertThat(arrItem.getDouble("end_time"), is(equalTo(1.509484896709E9)));
}
}
| JsonTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/util/BytesRefArray.java | {
"start": 1073,
"end": 7691
} | class ____ implements Accountable, Releasable, Writeable {
// base size of the bytes ref array
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(BytesRefArray.class);
private final BigArrays bigArrays;
private LongArray startOffsets;
private ByteArray bytes;
private long size;
public BytesRefArray(long capacity, BigArrays bigArrays) {
this.bigArrays = bigArrays;
boolean success = false;
try {
startOffsets = bigArrays.newLongArray(capacity + 1, false);
startOffsets.set(0, 0);
bytes = bigArrays.newByteArray(capacity * 3, false);
success = true;
} finally {
if (false == success) {
close();
}
}
size = 0;
}
public BytesRefArray(StreamInput in, BigArrays bigArrays) throws IOException {
this.bigArrays = bigArrays;
// we allocate big arrays so we have to `close` if we fail here or we'll leak them.
boolean success = false;
try {
// startOffsets
size = in.readVLong();
long sizeOfStartOffsets = size + 1;
startOffsets = bigArrays.newLongArray(sizeOfStartOffsets, false);
for (long i = 0; i < sizeOfStartOffsets; ++i) {
startOffsets.set(i, in.readVLong());
}
// bytes
long sizeOfBytes = in.readVLong();
bytes = bigArrays.newByteArray(sizeOfBytes, false);
bytes.fillWith(in);
success = true;
} finally {
if (success == false) {
close();
}
}
}
public BytesRefArray(LongArray startOffsets, ByteArray bytes, long size, BigArrays bigArrays) {
this.bytes = bytes;
this.startOffsets = startOffsets;
this.size = size;
this.bigArrays = bigArrays;
}
public void append(BytesRef key) {
assert startOffsets != null : "using BytesRefArray after ownership taken";
final long startOffset = startOffsets.get(size);
startOffsets = bigArrays.grow(startOffsets, size + 2);
startOffsets.set(size + 1, startOffset + key.length);
++size;
if (key.length > 0) {
bytes = bigArrays.grow(bytes, startOffset + key.length);
bytes.set(startOffset, key.bytes, key.offset, key.length);
}
}
/**
* Return the key at <code>0 <= index <= capacity()</code>. The result is undefined if the slot is unused.
* <p>Beware that the content of the {@link BytesRef} may become invalid as soon as {@link #close()} is called</p>
*/
public BytesRef get(long id, BytesRef dest) {
assert startOffsets != null : "using BytesRefArray after ownership taken";
final long startOffset = startOffsets.get(id);
final int length = (int) (startOffsets.get(id + 1) - startOffset);
bytes.get(startOffset, length, dest);
return dest;
}
public long size() {
return size;
}
@Override
public void close() {
Releasables.close(bytes, startOffsets);
}
/**
* Create new instance and pass ownership of this array to the new one.
*
* Note, this closes this array. Don't use it after passing ownership.
*
* @param other BytesRefArray to claim ownership from
* @return a new BytesRefArray instance with the payload of other
*/
public static BytesRefArray takeOwnershipOf(BytesRefArray other) {
BytesRefArray b = new BytesRefArray(other.startOffsets, other.bytes, other.size, other.bigArrays);
// don't leave a broken array behind, although it isn't used any longer
// on append both arrays get re-allocated
other.startOffsets = null;
other.bytes = null;
other.size = 0;
return b;
}
/**
* Creates a deep copy of the given BytesRefArray.
*/
public static BytesRefArray deepCopy(BytesRefArray other) {
LongArray startOffsets = null;
ByteArray bytes = null;
BytesRefArray result = null;
try {
startOffsets = other.bigArrays.newLongArray(other.startOffsets.size());
for (long i = 0; i < other.startOffsets.size(); i++) {
startOffsets.set(i, other.startOffsets.get(i));
}
bytes = other.bigArrays.newByteArray(other.bytes.size());
BytesRefIterator it = other.bytes.iterator();
BytesRef ref;
long pos = 0;
try {
while ((ref = it.next()) != null) {
bytes.set(pos, ref.bytes, ref.offset, ref.length);
pos += ref.length;
}
} catch (IOException e) {
assert false : new AssertionError("BytesRefIterator should not throw IOException", e);
throw new UncheckedIOException(e);
}
result = new BytesRefArray(startOffsets, bytes, other.size, other.bigArrays);
return result;
} finally {
if (result == null) {
Releasables.closeExpectNoException(startOffsets, bytes);
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
assert startOffsets != null : "using BytesRefArray after ownership taken";
out.writeVLong(size);
long sizeOfStartOffsets = size + 1;
// start offsets have 1 extra bucket
for (long i = 0; i < sizeOfStartOffsets; ++i) {
out.writeVLong(startOffsets.get(i));
}
// bytes might be overallocated, the last bucket of startOffsets contains the real size
final long sizeOfBytes = startOffsets.get(size);
out.writeVLong(sizeOfBytes);
final BytesRefIterator bytesIt = bytes.iterator();
BytesRef bytesRef;
long remained = sizeOfBytes;
while (remained > 0 && (bytesRef = bytesIt.next()) != null) {
int length = Math.toIntExact(Math.min(remained, bytesRef.length));
remained -= length;
out.writeBytes(bytesRef.bytes, bytesRef.offset, length);
}
assert remained == 0 : remained;
}
@Override
public long ramBytesUsed() {
return BASE_RAM_BYTES_USED + bigArraysRamBytesUsed();
}
/**
* Memory used by the {@link BigArrays} portion of this {@link BytesRefArray}.
*/
public long bigArraysRamBytesUsed() {
return startOffsets.ramBytesUsed() + bytes.ramBytesUsed();
}
}
| BytesRefArray |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/stork/StorkWithPathIntegrationTest.java | {
"start": 682,
"end": 3121
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(HelloClient.class, HelloResource.class))
.withConfigurationResource("stork-application-with-path.properties");
@RestClient
HelloClient client;
@Test
void shouldDetermineUrlViaStork() {
String greeting = RestClientBuilder.newBuilder().baseUri(URI.create("stork://hello-service"))
.build(HelloClient.class)
.echo("black and white bird");
assertThat(greeting).isEqualTo("hello, black and white bird");
greeting = RestClientBuilder.newBuilder().baseUri(URI.create("stork://hello-service"))
.build(HelloClient.class)
.helloWithPathParam("black and white bird");
assertThat(greeting).isEqualTo("Hello, black and white bird");
}
@Test
void shouldDetermineUrlViaStorkWhenUsingTarget() throws URISyntaxException {
String greeting = ClientBuilder.newClient().target("stork://hello-service").request().get(String.class);
assertThat(greeting).isEqualTo("Hello, World!");
greeting = ClientBuilder.newClient().target(new URI("stork://hello-service")).request().get(String.class);
assertThat(greeting).isEqualTo("Hello, World!");
greeting = ClientBuilder.newClient().target(UriBuilder.fromUri("stork://hello-service/")).request()
.get(String.class);
assertThat(greeting).isEqualTo("Hello, World!");
greeting = ClientBuilder.newClient().target("stork://hello-service/").path("big bird").request()
.get(String.class);
assertThat(greeting).isEqualTo("Hello, big bird");
}
@Test
void shouldDetermineUrlViaStorkCDI() {
String greeting = client.echo("big bird");
assertThat(greeting).isEqualTo("hello, big bird");
greeting = client.helloWithPathParam("big bird");
assertThat(greeting).isEqualTo("Hello, big bird");
}
@Test
@Timeout(20)
void shouldFailOnUnknownService() {
HelloClient client = RestClientBuilder.newBuilder()
.baseUri(URI.create("stork://nonexistent-service"))
.build(HelloClient.class);
assertThatThrownBy(() -> client.echo("foo")).isInstanceOf(NoSuchServiceDefinitionException.class);
}
}
| StorkWithPathIntegrationTest |
java | elastic__elasticsearch | modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/DissectProcessor.java | {
"start": 843,
"end": 2154
} | class ____ extends AbstractProcessor {
public static final String TYPE = "dissect";
// package private members for testing
final String field;
final boolean ignoreMissing;
final String pattern;
final String appendSeparator;
final DissectParser dissectParser;
DissectProcessor(String tag, String description, String field, String pattern, String appendSeparator, boolean ignoreMissing) {
super(tag, description);
this.field = field;
this.ignoreMissing = ignoreMissing;
this.pattern = pattern;
this.appendSeparator = appendSeparator;
this.dissectParser = new DissectParser(pattern, appendSeparator);
}
@Override
public IngestDocument execute(IngestDocument ingestDocument) {
String input = ingestDocument.getFieldValue(field, String.class, ignoreMissing);
if (input == null && ignoreMissing) {
return ingestDocument;
} else if (input == null) {
throw new IllegalArgumentException("field [" + field + "] is null, cannot process it.");
}
dissectParser.forceParse(input).forEach(ingestDocument::setFieldValue);
return ingestDocument;
}
@Override
public String getType() {
return TYPE;
}
public static final | DissectProcessor |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/NLineInputFormat.java | {
"start": 2615,
"end": 6116
} | class ____ extends FileInputFormat<LongWritable, Text> {
public static final String LINES_PER_MAP =
"mapreduce.input.lineinputformat.linespermap";
public RecordReader<LongWritable, Text> createRecordReader(
InputSplit genericSplit, TaskAttemptContext context)
throws IOException {
context.setStatus(genericSplit.toString());
return new LineRecordReader();
}
/**
* Logically splits the set of input files for the job, splits N lines
* of the input as one split.
*
* @see FileInputFormat#getSplits(JobContext)
*/
public List<InputSplit> getSplits(JobContext job)
throws IOException {
List<InputSplit> splits = new ArrayList<InputSplit>();
int numLinesPerSplit = getNumLinesPerSplit(job);
for (FileStatus status : listStatus(job)) {
splits.addAll(getSplitsForFile(status,
job.getConfiguration(), numLinesPerSplit));
}
return splits;
}
public static List<FileSplit> getSplitsForFile(FileStatus status,
Configuration conf, int numLinesPerSplit) throws IOException {
List<FileSplit> splits = new ArrayList<FileSplit> ();
Path fileName = status.getPath();
if (status.isDirectory()) {
throw new IOException("Not a file: " + fileName);
}
LineReader lr = null;
try {
final FutureDataInputStreamBuilder builder =
fileName.getFileSystem(conf).openFile(fileName);
FutureIO.propagateOptions(builder, conf,
MRJobConfig.INPUT_FILE_OPTION_PREFIX,
MRJobConfig.INPUT_FILE_MANDATORY_PREFIX);
FSDataInputStream in = FutureIO.awaitFuture(builder.build());
lr = new LineReader(in, conf);
Text line = new Text();
int numLines = 0;
long begin = 0;
long length = 0;
int num = -1;
while ((num = lr.readLine(line)) > 0) {
numLines++;
length += num;
if (numLines == numLinesPerSplit) {
splits.add(createFileSplit(fileName, begin, length));
begin += length;
length = 0;
numLines = 0;
}
}
if (numLines != 0) {
splits.add(createFileSplit(fileName, begin, length));
}
} finally {
if (lr != null) {
lr.close();
}
}
return splits;
}
/**
* NLineInputFormat uses LineRecordReader, which always reads
* (and consumes) at least one character out of its upper split
* boundary. So to make sure that each mapper gets N lines, we
* move back the upper split limits of each split
* by one character here.
* @param fileName Path of file
* @param begin the position of the first byte in the file to process
* @param length number of bytes in InputSplit
* @return FileSplit
*/
protected static FileSplit createFileSplit(Path fileName, long begin, long length) {
return (begin == 0)
? new FileSplit(fileName, begin, length - 1, new String[] {})
: new FileSplit(fileName, begin - 1, length, new String[] {});
}
/**
* Set the number of lines per split
* @param job the job to modify
* @param numLines the number of lines per split
*/
public static void setNumLinesPerSplit(Job job, int numLines) {
job.getConfiguration().setInt(LINES_PER_MAP, numLines);
}
/**
* Get the number of lines per split
* @param job the job
* @return the number of lines per split
*/
public static int getNumLinesPerSplit(JobContext job) {
return job.getConfiguration().getInt(LINES_PER_MAP, 1);
}
}
| NLineInputFormat |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java | {
"start": 52546,
"end": 53316
} | class ____ {
@JsonView(MyJacksonView1.class)
private String withView1;
@JsonView(MyJacksonView2.class)
private String withView2;
private String withoutView;
public String getWithView1() {
return withView1;
}
public void setWithView1(String withView1) {
this.withView1 = withView1;
}
public @Nullable String getWithView2() {
return withView2;
}
public void setWithView2(String withView2) {
this.withView2 = withView2;
}
public @Nullable String getWithoutView() {
return withoutView;
}
public void setWithoutView(String withoutView) {
this.withoutView = withoutView;
}
}
@SuppressWarnings("NotNullFieldNotInitialized")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
public static | JacksonViewBean |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/TestIOUtils.java | {
"start": 2152,
"end": 9557
} | class ____ {
private static final String TEST_FILE_NAME = "test_file";
private static final Logger LOG = LoggerFactory.getLogger(TestIOUtils.class);
@Test
public void testCopyBytesShouldCloseStreamsWhenCloseIsTrue() throws Exception {
InputStream inputStream = mock(InputStream.class);
OutputStream outputStream = mock(OutputStream.class);
doReturn(-1).when(inputStream).read(new byte[1]);
IOUtils.copyBytes(inputStream, outputStream, 1, true);
verify(inputStream, atLeastOnce()).close();
verify(outputStream, atLeastOnce()).close();
}
@Test
public void testCopyBytesShouldCloseInputSteamWhenOutputStreamCloseThrowsException()
throws Exception {
InputStream inputStream = mock(InputStream.class);
OutputStream outputStream = mock(OutputStream.class);
doReturn(-1).when(inputStream).read(new byte[1]);
doThrow(new IOException()).when(outputStream).close();
try{
IOUtils.copyBytes(inputStream, outputStream, 1, true);
} catch (IOException e) {
}
verify(inputStream, atLeastOnce()).close();
verify(outputStream, atLeastOnce()).close();
}
@Test
public void testCopyBytesShouldCloseInputSteamWhenOutputStreamCloseThrowsRunTimeException()
throws Exception {
InputStream inputStream = mock(InputStream.class);
OutputStream outputStream = mock(OutputStream.class);
doReturn(-1).when(inputStream).read(new byte[1]);
doThrow(new RuntimeException()).when(outputStream).close();
try {
IOUtils.copyBytes(inputStream, outputStream, 1, true);
fail("Didn't throw exception");
} catch (RuntimeException e) {
}
verify(outputStream, atLeastOnce()).close();
}
@Test
public void testCopyBytesShouldCloseInputSteamWhenInputStreamCloseThrowsRunTimeException()
throws Exception {
InputStream inputStream = mock(InputStream.class);
OutputStream outputStream = mock(OutputStream.class);
doReturn(-1).when(inputStream).read(new byte[1]);
doThrow(new RuntimeException()).when(inputStream).close();
try {
IOUtils.copyBytes(inputStream, outputStream, 1, true);
fail("Didn't throw exception");
} catch (RuntimeException e) {
}
verify(inputStream, atLeastOnce()).close();
}
@Test
public void testCopyBytesShouldNotCloseStreamsWhenCloseIsFalse()
throws Exception {
InputStream inputStream = mock(InputStream.class);
OutputStream outputStream = mock(OutputStream.class);
doReturn(-1).when(inputStream).read(new byte[1]);
IOUtils.copyBytes(inputStream, outputStream, 1, false);
verify(inputStream, atMost(0)).close();
verify(outputStream, atMost(0)).close();
}
@Test
public void testCopyBytesWithCountShouldCloseStreamsWhenCloseIsTrue()
throws Exception {
InputStream inputStream = mock(InputStream.class);
OutputStream outputStream = mock(OutputStream.class);
doReturn(-1).when(inputStream).read(new byte[4096], 0, 1);
IOUtils.copyBytes(inputStream, outputStream, (long) 1, true);
verify(inputStream, atLeastOnce()).close();
verify(outputStream, atLeastOnce()).close();
}
@Test
public void testCopyBytesWithCountShouldNotCloseStreamsWhenCloseIsFalse()
throws Exception {
InputStream inputStream = mock(InputStream.class);
OutputStream outputStream = mock(OutputStream.class);
doReturn(-1).when(inputStream).read(new byte[4096], 0, 1);
IOUtils.copyBytes(inputStream, outputStream, (long) 1, false);
verify(inputStream, atMost(0)).close();
verify(outputStream, atMost(0)).close();
}
@Test
public void testCopyBytesWithCountShouldThrowOutTheStreamClosureExceptions()
throws Exception {
InputStream inputStream = mock(InputStream.class);
OutputStream outputStream = mock(OutputStream.class);
doReturn(-1).when(inputStream).read(new byte[4096], 0, 1);
doThrow(new IOException("Exception in closing the stream")).when(
outputStream).close();
try {
IOUtils.copyBytes(inputStream, outputStream, (long) 1, true);
fail("Should throw out the exception");
} catch (IOException e) {
assertEquals("Exception in closing the stream", e.getMessage(),
"Not throwing the expected exception.");
}
verify(inputStream, atLeastOnce()).close();
verify(outputStream, atLeastOnce()).close();
}
@Test
public void testWriteFully() throws IOException {
final int INPUT_BUFFER_LEN = 10000;
final int HALFWAY = 1 + (INPUT_BUFFER_LEN / 2);
byte[] input = new byte[INPUT_BUFFER_LEN];
for (int i = 0; i < input.length; i++) {
input[i] = (byte)(i & 0xff);
}
byte[] output = new byte[input.length];
try {
RandomAccessFile raf = new RandomAccessFile(TEST_FILE_NAME, "rw");
FileChannel fc = raf.getChannel();
ByteBuffer buf = ByteBuffer.wrap(input);
IOUtils.writeFully(fc, buf);
raf.seek(0);
raf.read(output);
for (int i = 0; i < input.length; i++) {
assertEquals(input[i], output[i]);
}
buf.rewind();
IOUtils.writeFully(fc, buf, HALFWAY);
for (int i = 0; i < HALFWAY; i++) {
assertEquals(input[i], output[i]);
}
raf.seek(0);
raf.read(output);
for (int i = HALFWAY; i < input.length; i++) {
assertEquals(input[i - HALFWAY], output[i]);
}
raf.close();
} finally {
File f = new File(TEST_FILE_NAME);
if (f.exists()) {
f.delete();
}
}
}
@Test
public void testWrappedReadForCompressedData() throws IOException {
byte[] buf = new byte[2];
InputStream mockStream = mock(InputStream.class);
when(mockStream.read(buf, 0, 1)).thenReturn(1);
when(mockStream.read(buf, 0, 2)).thenThrow(
new java.lang.InternalError());
try {
assertEquals(1, IOUtils.wrappedReadForCompressedData(mockStream, buf, 0, 1),
"Check expected value");
} catch (IOException ioe) {
fail("Unexpected error while reading");
}
try {
IOUtils.wrappedReadForCompressedData(mockStream, buf, 0, 2);
} catch (IOException ioe) {
GenericTestUtils.assertExceptionContains(
"Error while reading compressed data", ioe);
}
}
@Test
public void testSkipFully() throws IOException {
byte inArray[] = new byte[] {0, 1, 2, 3, 4};
ByteArrayInputStream in = new ByteArrayInputStream(inArray);
try {
in.mark(inArray.length);
IOUtils.skipFully(in, 2);
IOUtils.skipFully(in, 2);
try {
IOUtils.skipFully(in, 2);
fail("expected to get a PrematureEOFException");
} catch (EOFException e) {
assertEquals("Premature EOF from inputStream " +
"after skipping 1 byte(s).",e.getMessage());
}
in.reset();
try {
IOUtils.skipFully(in, 20);
fail("expected to get a PrematureEOFException");
} catch (EOFException e) {
assertEquals("Premature EOF from inputStream " +
"after skipping 5 byte(s).",e.getMessage());
}
in.reset();
IOUtils.skipFully(in, 5);
try {
IOUtils.skipFully(in, 10);
fail("expected to get a PrematureEOFException");
} catch (EOFException e) {
assertEquals("Premature EOF from inputStream " +
"after skipping 0 byte(s).",e.getMessage());
}
} finally {
in.close();
}
}
private | TestIOUtils |
java | quarkusio__quarkus | extensions/spring-di/deployment/src/test/java/io/quarkus/spring/di/deployment/ListOfBeansTest.java | {
"start": 2855,
"end": 2917
} | interface ____ {
String ping();
}
public | Service |
java | apache__camel | components/camel-aws/camel-aws2-athena/src/main/java/org/apache/camel/component/aws2/athena/Athena2Operations.java | {
"start": 1050,
"end": 1171
} | enum ____ {
getQueryExecution,
getQueryResults,
listQueryExecutions,
startQueryExecution,
}
| Athena2Operations |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/stork/PassThroughResource.java | {
"start": 340,
"end": 1289
} | class ____ {
@RestClient
HelloClient client;
@GET
public String invokeClient() {
HelloClient client = RestClientBuilder.newBuilder()
.baseUri(URI.create("stork://hello-service/hello"))
.build(HelloClient.class);
return client.hello();
}
@Path("/v2/{name}")
@GET
public String invokeClientWithPathParamContainingSlash(@PathParam("name") String name) {
return client.helloWithPathParam(name + "/" + name);
}
@Path("/v2/query")
@GET
public String invokeClientWithQueryParam(@QueryParam("foo") String foo) {
return client.helloWithQueryParam(foo);
}
@Path("/{name}")
@GET
public String invokeClientWithPathParam(@PathParam("name") String name) {
return client.helloWithPathParam(name);
}
@Path("/cdi")
@GET
public String invokeCdiClient() {
return client.hello();
}
}
| PassThroughResource |
java | apache__camel | components/camel-cxf/camel-cxf-spring-soap/src/test/java/org/apache/camel/component/cxf/wssecurity/camel/WSSecurityRouteTest.java | {
"start": 1638,
"end": 5488
} | class ____ extends CamelSpringTestSupport {
static final int PORT = CXFTestSupport.getPort1();
static CxfServer cxfServer;
@BeforeAll
public static void setupContext() throws Exception {
cxfServer = new CxfServer();
}
@Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/component/cxf/wssecurity/camel/camel-context.xml");
}
@Test
public void testSignature() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
URL busFile = WSSecurityRouteTest.class.getResource("../client/wssec.xml");
Bus bus = bf.createBus(busFile.toString());
BusFactory.setDefaultBus(bus);
BusFactory.setThreadDefaultBus(bus);
GreeterService gs = new GreeterService();
Greeter greeter = gs.getGreeterSignaturePort();
((BindingProvider) greeter).getRequestContext().put(
BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"http://localhost:" + CXFTestSupport.getPort2()
+ "/WSSecurityRouteTest/GreeterSignaturePort");
assertEquals("Hello Security", greeter.greetMe("Security"), "Get a wrong response");
}
@Test
public void testUsernameToken() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
URL busFile = WSSecurityRouteTest.class.getResource("../client/wssec.xml");
Bus bus = bf.createBus(busFile.toString());
BusFactory.setDefaultBus(bus);
BusFactory.setThreadDefaultBus(bus);
GreeterService gs = new GreeterService();
Greeter greeter = gs.getGreeterUsernameTokenPort();
((BindingProvider) greeter).getRequestContext().put(
BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"http://localhost:" + CXFTestSupport.getPort2()
+ "/WSSecurityRouteTest/GreeterUsernameTokenPort");
assertEquals("Hello Security", greeter.greetMe("Security"), "Get a wrong response");
}
@Test
public void testEncryption() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
URL busFile = WSSecurityRouteTest.class.getResource("../client/wssec.xml");
Bus bus = bf.createBus(busFile.toString());
BusFactory.setDefaultBus(bus);
BusFactory.setThreadDefaultBus(bus);
GreeterService gs = new GreeterService();
Greeter greeter = gs.getGreeterEncryptionPort();
((BindingProvider) greeter).getRequestContext().put(
BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"http://localhost:" + CXFTestSupport.getPort2()
+ "/WSSecurityRouteTest/GreeterEncryptionPort");
assertEquals("Hello Security", greeter.greetMe("Security"), "Get a wrong response");
}
@Test
public void testSecurityPolicy() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
URL busFile = WSSecurityRouteTest.class.getResource("../client/wssec.xml");
Bus bus = bf.createBus(busFile.toString());
BusFactory.setDefaultBus(bus);
BusFactory.setThreadDefaultBus(bus);
GreeterService gs = new GreeterService();
Greeter greeter = gs.getGreeterSecurityPolicyPort();
((BindingProvider) greeter).getRequestContext().put(
BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"http://localhost:" + CXFTestSupport.getPort2()
+ "/WSSecurityRouteTest/GreeterSecurityPolicyPort");
assertEquals("Hello Security", greeter.greetMe("Security"), "Get a wrong response");
}
}
| WSSecurityRouteTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/basic/InheritedTest.java | {
"start": 4299,
"end": 4583
} | class ____ extends DefaultEnhancementContext {
@Override
public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) {
// HHH-10981 - Without lazy loading, the generation of getters and setters has a different code path
return false;
}
}
}
| EagerEnhancementContext |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/RxReturnValueIgnoredTest.java | {
"start": 7940,
"end": 10227
} | class ____ implements CanIgnoreMethod {
@Override
public Observable<Object> getObservable() {
return null;
}
@Override
public Single<Object> getSingle() {
return null;
}
@Override
public Flowable<Object> getFlowable() {
return null;
}
@Override
public Maybe<Object> getMaybe() {
return null;
}
}
static void callIgnoredInterfaceMethod() {
new CanIgnoreImpl().getObservable();
new CanIgnoreImpl().getSingle();
new CanIgnoreImpl().getFlowable();
new CanIgnoreImpl().getMaybe();
}
static void putInMap() {
Map<Object, Observable<?>> map1 = new HashMap<>();
Map<Object, Single<?>> map2 = new HashMap<>();
Map<Object, Maybe<?>> map3 = new HashMap<>();
HashMap<Object, Flowable<?>> map4 = new HashMap<>();
map1.put(new Object(), null);
map2.put(new Object(), null);
map3.put(new Object(), null);
map4.put(new Object(), null);
}
@CanIgnoreReturnValue
Observable<Object> getObservable() {
return null;
}
@CanIgnoreReturnValue
Single<Object> getSingle() {
return null;
}
@CanIgnoreReturnValue
Flowable<Object> getFlowable() {
return null;
}
@CanIgnoreReturnValue
Maybe<Object> getMaybe() {
return null;
}
void checkIgnore() {
getObservable();
getSingle();
getFlowable();
getMaybe();
}
}\
""")
.doTest();
}
@Test
public void rx2Observable() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import io.reactivex.Observable;
| CanIgnoreImpl |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/internal/util/StringHelper.java | {
"start": 27218,
"end": 29120
} | interface ____<T> {
String render(T value);
}
/**
* @param firstExpression the first expression
* @param secondExpression the second expression
* @return if {@code firstExpression} and {@code secondExpression} are both non-empty,
* then "( " + {@code firstExpression} + " ) and ( " + {@code secondExpression} + " )" is returned;
* if {@code firstExpression} is non-empty and {@code secondExpression} is empty,
* then {@code firstExpression} is returned;
* if {@code firstExpression} is empty and {@code secondExpression} is non-empty,
* then {@code secondExpression} is returned;
* if both {@code firstExpression} and {@code secondExpression} are empty, then null is returned.
*/
public static String getNonEmptyOrConjunctionIfBothNonEmpty( String firstExpression, String secondExpression ) {
final boolean isFirstExpressionNonEmpty = isNotEmpty( firstExpression );
final boolean isSecondExpressionNonEmpty = isNotEmpty( secondExpression );
if ( isFirstExpressionNonEmpty && isSecondExpressionNonEmpty ) {
return "( " + firstExpression + " ) and ( " + secondExpression + " )";
}
else if ( isFirstExpressionNonEmpty ) {
return firstExpression;
}
else if ( isSecondExpressionNonEmpty ) {
return secondExpression;
}
else {
return null;
}
}
/**
* Return the interned form of a String, or null if the parameter is null.
* <p>
* Use with caution: excessive interning is known to cause issues.
* Best to use only with strings which are known to be long-lived constants,
* and for which the chances of being actual duplicates is proven.
* (Even better: avoid needing interning by design changes such as reusing
* the known reference)
*
* @param string The string to intern.
* @return The interned string.
*/
public static String safeInterning(final String string) {
return string == null ? null : string.intern();
}
}
| Renderer |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/bean/BeanPackageScopeTest.java | {
"start": 1748,
"end": 1951
} | class ____ {
String doSomething(String body) {
return "Hello " + body;
}
private String doSomethingElse(String foo) {
return "foo";
}
}
}
| MyBean |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/mixins/TestMixinDeserForClass.java | {
"start": 1020,
"end": 1135
} | interface ____ {
@Override
@JsonProperty
public int hashCode();
}
public | HashCodeMixIn |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/ContextHierarchyTestMethodScopedExtensionContextNestedTests.java | {
"start": 3657,
"end": 4483
} | class ____ {
@Autowired
String bar;
@Autowired
ApplicationContext context;
@Test
void nestedTest() {
assertThat(this.context).as("local ApplicationContext").isNotNull();
assertThat(this.context.getParent()).as("parent ApplicationContext").isNotNull();
// The foo field in the outer instance and the bar field in the inner
// instance should both have been injected from the test ApplicationContext
// for the inner instance.
assertThat(foo).as("foo")
.isEqualTo(this.context.getBean("foo", String.class))
.isEqualTo(QUX + 1);
assertThat(this.bar).isEqualTo(BAZ + 1);
}
@Nested
@NestedTestConfiguration(OVERRIDE)
@ContextHierarchy({
@ContextConfiguration(classes = ParentConfig.class),
@ContextConfiguration(classes = Child2Config.class)
})
| NestedInheritedCfgTests |
java | google__dagger | javatests/dagger/functional/tck/CarShop.java | {
"start": 891,
"end": 967
} | interface ____ {
@SuppressWarnings("dependency-cycle")
Car make();
}
| CarShop |
java | dropwizard__dropwizard | dropwizard-logging/src/main/java/io/dropwizard/logging/common/AppenderFactory.java | {
"start": 884,
"end": 1074
} | class ____.</li>
* </ol>
*
* @see ConsoleAppenderFactory
* @see FileAppenderFactory
* @see SyslogAppenderFactory
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
public | path |
java | apache__camel | components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddbstream/client/impl/Ddb2StreamClientStandardImpl.java | {
"start": 1950,
"end": 5292
} | class ____ implements Ddb2StreamInternalClient {
private static final Logger LOG = LoggerFactory.getLogger(Ddb2StreamClientStandardImpl.class);
private Ddb2StreamConfiguration configuration;
/**
* Constructor that uses the config file.
*/
public Ddb2StreamClientStandardImpl(Ddb2StreamConfiguration configuration) {
LOG.trace("Creating an AWS DynamoDB Streams manager using static credentials.");
this.configuration = configuration;
}
/**
* Getting the DynamoDB Streams AWS client that is used.
*
* @return Amazon DynamoDB Streams Client.
*/
@Override
public DynamoDbStreamsClient getDynamoDBStreamClient() {
DynamoDbStreamsClient client = null;
DynamoDbStreamsClientBuilder clientBuilder = DynamoDbStreamsClient.builder();
ProxyConfiguration.Builder proxyConfig = null;
ApacheHttpClient.Builder httpClientBuilder = null;
boolean isClientConfigFound = false;
if (ObjectHelper.isNotEmpty(configuration.getProxyHost()) && ObjectHelper.isNotEmpty(configuration.getProxyPort())) {
proxyConfig = ProxyConfiguration.builder();
URI proxyEndpoint = URI.create(configuration.getProxyProtocol() + "://" + configuration.getProxyHost() + ":"
+ configuration.getProxyPort());
proxyConfig.endpoint(proxyEndpoint);
httpClientBuilder = ApacheHttpClient.builder().proxyConfiguration(proxyConfig.build());
isClientConfigFound = true;
}
if (configuration.getAccessKey() != null && configuration.getSecretKey() != null) {
AwsBasicCredentials cred = AwsBasicCredentials.create(configuration.getAccessKey(), configuration.getSecretKey());
if (isClientConfigFound) {
clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder)
.credentialsProvider(StaticCredentialsProvider.create(cred));
} else {
clientBuilder = clientBuilder.credentialsProvider(StaticCredentialsProvider.create(cred));
}
} else {
if (!isClientConfigFound) {
clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder);
}
}
if (ObjectHelper.isNotEmpty(configuration.getRegion())) {
clientBuilder = clientBuilder.region(Region.of(configuration.getRegion()));
}
if (configuration.isOverrideEndpoint()) {
clientBuilder.endpointOverride(URI.create(configuration.getUriEndpointOverride()));
}
if (configuration.isTrustAllCertificates()) {
if (httpClientBuilder == null) {
httpClientBuilder = ApacheHttpClient.builder();
}
SdkHttpClient ahc = httpClientBuilder.buildWithDefaults(AttributeMap
.builder()
.put(
SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES,
Boolean.TRUE)
.build());
// set created http client to use instead of builder
clientBuilder.httpClient(ahc);
clientBuilder.httpClientBuilder(null);
}
client = clientBuilder.build();
return client;
}
}
| Ddb2StreamClientStandardImpl |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/UserGroupInformation.java | {
"start": 5888,
"end": 7145
} | class ____ {
final MetricsRegistry registry = new MetricsRegistry("UgiMetrics");
@Metric("Rate of successful kerberos logins and latency (milliseconds)")
MutableRate loginSuccess;
@Metric("Rate of failed kerberos logins and latency (milliseconds)")
MutableRate loginFailure;
@Metric("GetGroups") MutableRate getGroups;
MutableQuantiles[] getGroupsQuantiles;
@Metric("Renewal failures since startup")
private MutableGaugeLong renewalFailuresTotal;
@Metric("Renewal failures since last successful login")
private MutableGaugeInt renewalFailures;
static UgiMetrics create() {
return DefaultMetricsSystem.instance().register(new UgiMetrics());
}
static void reattach() {
metrics = UgiMetrics.create();
}
void addGetGroups(long latency) {
getGroups.add(latency);
if (getGroupsQuantiles != null) {
for (MutableQuantiles q : getGroupsQuantiles) {
q.add(latency);
}
}
}
MutableGaugeInt getRenewalFailures() {
return renewalFailures;
}
}
/**
* A login module that looks at the Kerberos, Unix, or Windows principal and
* adds the corresponding UserName.
*/
@InterfaceAudience.Private
public static | UgiMetrics |
java | google__guava | android/guava/src/com/google/common/collect/Comparators.java | {
"start": 1499,
"end": 1698
} | class ____
* intended to "fill the gap" and provide those features of {@code Ordering} not already provided by
* the JDK.
*
* @since 21.0
* @author Louis Wasserman
*/
@GwtCompatible
public final | is |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/writer/IndentationCorrectingWriter.java | {
"start": 1466,
"end": 3234
} | class ____ extends Writer {
/**
* Set to true to enable output of written characters on the console.
*/
private static final boolean DEBUG = false;
private static final String LINE_SEPARATOR = System.lineSeparator( );
private static final boolean IS_WINDOWS = System.getProperty( "os.name" ).startsWith( "Windows" );
private State currentState = State.START_OF_LINE;
private final StateContext context;
IndentationCorrectingWriter(Writer out) {
super( out );
this.context = new StateContext( out );
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
context.reset( cbuf, off );
for ( int i = off; i < len; i++ ) {
char c = cbuf[i];
State newState = currentState.handleCharacter( c, context );
if ( newState != currentState ) {
currentState.onExit( context, newState );
newState.onEntry( context );
currentState = newState;
}
context.currentIndex++;
}
currentState.onBufferFinished( context );
}
@Override
public void flush() throws IOException {
context.writer.flush();
}
@Override
public void close() throws IOException {
currentState.onExit( context, null );
context.writer.close();
}
private static boolean isWindows() {
return IS_WINDOWS;
}
private static char[] getIndentation(int indentationLevel) {
char[] indentation = new char[indentationLevel * 4];
Arrays.fill( indentation, ' ' );
return indentation;
}
/**
* A state of parsing a given character buffer.
*/
private | IndentationCorrectingWriter |
java | apache__flink | flink-state-backends/flink-statebackend-forst/src/main/java/org/apache/flink/state/forst/ForStConfigurableOptions.java | {
"start": 2680,
"end": 2934
} | class ____ the configuration options for the ForStStateBackend.
*
* <p>Currently, Options of ForSt would be configured by values here, and a user-defined {@link
* ForStOptionsFactory} may override the configurations here.
*/
@Experimental
public | contains |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/TraditionalSwitchExpressionTest.java | {
"start": 1134,
"end": 1583
} | class ____ {
int f(int i) {
// BUG: Diagnostic contains: Prefer -> switches for switch expressions
return switch (i) {
default:
yield -1;
};
}
}
""")
.doTest();
}
@Test
public void negativeStatement() {
testHelper
.addSourceLines(
"Test.java",
"""
| Test |
java | FasterXML__jackson-core | src/main/java/tools/jackson/core/JacksonException.java | {
"start": 207,
"end": 394
} | class ____ all Jackson-produced checked exceptions.
*<p>
* Note that in Jackson 2.x this exception extended {@link java.io.IOException}
* but in 3.x {@link RuntimeException}
*/
public | for |
java | quarkusio__quarkus | core/runtime/src/main/java/io/quarkus/runtime/configuration/HashSetFactory.java | {
"start": 183,
"end": 1296
} | class ____<T> implements IntFunction<HashSet<T>> {
private static final HashSetFactory<?> INSTANCE = new HashSetFactory<>();
private HashSetFactory() {
}
public HashSet<T> apply(final int value) {
return new HashSet<>(getInitialCapacityFromExpectedSize(value));
}
/**
* As the default loadFactor is of 0.75, we need to calculate the initial capacity from the expected size to avoid
* resizing the collection when we populate the collection with all the initial elements. We use a calculation
* similar to what is done in {@link java.util.HashMap#putAll(Map)}.
*
* @param expectedSize the expected size of the collection
* @return the initial capacity of the collection
*/
private int getInitialCapacityFromExpectedSize(int expectedSize) {
if (expectedSize < 3) {
return expectedSize + 1;
}
return (int) ((float) expectedSize / 0.75f + 1.0f);
}
@SuppressWarnings("unchecked")
public static <T> HashSetFactory<T> getInstance() {
return (HashSetFactory<T>) INSTANCE;
}
}
| HashSetFactory |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_3159/Issue3159Mapper.java | {
"start": 975,
"end": 1247
} | class ____ {
private final Collection<Element> elements;
public Source(Collection<Element> elements) {
this.elements = elements;
}
public Collection<Element> getElements() {
return elements;
}
}
| Source |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/api/records/ServiceStatus.java | {
"start": 4067,
"end": 4671
} | class ____ {\n")
.append(" diagnostics: ").append(toIndentedString(diagnostics))
.append("\n")
.append(" state: ").append(toIndentedString(state)).append("\n")
.append(" code: ").append(toIndentedString(code)).append("\n")
.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| ServiceStatus |
java | apache__camel | test-infra/camel-test-infra-core/src/test/java/org/apache/camel/test/infra/core/DefaultContextLifeCycleManager.java | {
"start": 1112,
"end": 2866
} | class ____ implements ContextLifeCycleManager {
public static final int DEFAULT_SHUTDOWN_TIMEOUT = 10;
private static final Logger LOG = LoggerFactory.getLogger(DefaultContextLifeCycleManager.class);
private int shutdownTimeout = DEFAULT_SHUTDOWN_TIMEOUT;
private boolean reset = true;
/**
* Creates a new instance of this class
*/
public DefaultContextLifeCycleManager() {
}
/**
* Creates a new instance of this class
*
* @param shutdownTimeout the shutdown timeout
* @param reset whether to reset any {@link MockEndpoint} after each test execution
*/
public DefaultContextLifeCycleManager(int shutdownTimeout, boolean reset) {
this.shutdownTimeout = shutdownTimeout;
this.reset = reset;
}
@Override
public void afterAll(CamelContext context) {
if (context != null) {
context.shutdown();
} else {
LOG.error(
"Cannot run the JUnit's afterAll because the context is null: a problem may have prevented the context from starting");
}
}
@Override
public void beforeAll(CamelContext context) {
if (context != null) {
context.getShutdownStrategy().setTimeout(shutdownTimeout);
} else {
LOG.error(
"Cannot run the JUnit's beforeAll because the context is null: a problem may have prevented the context from starting");
}
}
@Override
public void afterEach(CamelContext context) {
if (reset) {
MockEndpoint.resetMocks(context);
}
}
@Override
public void beforeEach(CamelContext context) {
context.start();
}
}
| DefaultContextLifeCycleManager |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/StoredProcedureAttributeSource.java | {
"start": 1281,
"end": 1575
} | class ____ {@link StoredProcedureAttributes}.
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Christoph Strobl
* @author Mark Paluch
* @author Diego Diez
* @author Jeff Sheets
* @author Gabriel Basilio
* @author Greg Turnquist
* @author Thorben Janssen
* @since 1.6
*/
| for |
java | alibaba__fastjson | src/main/java/com/alibaba/fastjson/asm/ClassReader.java | {
"start": 2322,
"end": 10219
} | class ____ information starts just after the constant pool
header = index;
}
public void accept(final TypeCollector classVisitor) {
char[] c = new char[maxStringLength]; // buffer used to read strings
int i, j; // loop variables
int u, v; // indexes in b
int anns = 0;
//read annotations
if (readAnnotations) {
u = getAttributes();
for (i = readUnsignedShort(u); i > 0; --i) {
String attrName = readUTF8(u + 2, c);
if ("RuntimeVisibleAnnotations".equals(attrName)) {
anns = u + 8;
break;
}
u += 6 + readInt(u + 4);
}
}
// visits the header
u = header;
int len = readUnsignedShort(u + 6);
u += 8;
for (i = 0; i < len; ++i) {
u += 2;
}
v = u;
i = readUnsignedShort(v);
v += 2;
for (; i > 0; --i) {
j = readUnsignedShort(v + 6);
v += 8;
for (; j > 0; --j) {
v += 6 + readInt(v + 2);
}
}
i = readUnsignedShort(v);
v += 2;
for (; i > 0; --i) {
j = readUnsignedShort(v + 6);
v += 8;
for (; j > 0; --j) {
v += 6 + readInt(v + 2);
}
}
i = readUnsignedShort(v);
v += 2;
for (; i > 0; --i) {
v += 6 + readInt(v + 2);
}
if (anns != 0) {
for (i = readUnsignedShort(anns), v = anns + 2; i > 0; --i) {
String name = readUTF8(v, c);
classVisitor.visitAnnotation(name);
}
}
// visits the fields
i = readUnsignedShort(u);
u += 2;
for (; i > 0; --i) {
j = readUnsignedShort(u + 6);
u += 8;
for (; j > 0; --j) {
u += 6 + readInt(u + 2);
}
}
// visits the methods
i = readUnsignedShort(u);
u += 2;
for (; i > 0; --i) {
// inlined in original ASM source, now a method call
u = readMethod(classVisitor, c, u);
}
}
private int getAttributes() {
// skips the header
int u = header + 8 + readUnsignedShort(header + 6) * 2;
// skips fields and methods
for (int i = readUnsignedShort(u); i > 0; --i) {
for (int j = readUnsignedShort(u + 8); j > 0; --j) {
u += 6 + readInt(u + 12);
}
u += 8;
}
u += 2;
for (int i = readUnsignedShort(u); i > 0; --i) {
for (int j = readUnsignedShort(u + 8); j > 0; --j) {
u += 6 + readInt(u + 12);
}
u += 8;
}
// the attribute_info structure starts just after the methods
return u + 2;
}
private int readMethod(TypeCollector classVisitor, char[] c, int u) {
int v;
int w;
int j;
String attrName;
int k;
int access = readUnsignedShort(u);
String name = readUTF8(u + 2, c);
String desc = readUTF8(u + 4, c);
v = 0;
w = 0;
// looks for Code and Exceptions attributes
j = readUnsignedShort(u + 6);
u += 8;
for (; j > 0; --j) {
attrName = readUTF8(u, c);
int attrSize = readInt(u + 2);
u += 6;
// tests are sorted in decreasing frequency order
// (based on frequencies observed on typical classes)
if (attrName.equals("Code")) {
v = u;
}
u += attrSize;
}
// reads declared exceptions
if (w == 0) {
} else {
w += 2;
for (j = 0; j < readUnsignedShort(w); ++j) {
w += 2;
}
}
// visits the method's code, if any
MethodCollector mv = classVisitor.visitMethod(access, name, desc);
if (mv != null && v != 0) {
int codeLength = readInt(v + 4);
v += 8;
int codeStart = v;
int codeEnd = v + codeLength;
v = codeEnd;
j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
v += 8;
}
// parses the local variable, line number tables, and code
// attributes
int varTable = 0;
int varTypeTable = 0;
j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
attrName = readUTF8(v, c);
if (attrName.equals("LocalVariableTable")) {
varTable = v + 6;
} else if (attrName.equals("LocalVariableTypeTable")) {
varTypeTable = v + 6;
}
v += 6 + readInt(v + 2);
}
v = codeStart;
// visits the local variable tables
if (varTable != 0) {
if (varTypeTable != 0) {
k = readUnsignedShort(varTypeTable) * 3;
w = varTypeTable + 2;
int[] typeTable = new int[k];
while (k > 0) {
typeTable[--k] = w + 6; // signature
typeTable[--k] = readUnsignedShort(w + 8); // index
typeTable[--k] = readUnsignedShort(w); // start
w += 10;
}
}
k = readUnsignedShort(varTable);
w = varTable + 2;
for (; k > 0; --k) {
int index = readUnsignedShort(w + 8);
mv.visitLocalVariable(readUTF8(w + 4, c), index);
w += 10;
}
}
}
return u;
}
private int readUnsignedShort(final int index) {
byte[] b = this.b;
return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF);
}
private int readInt(final int index) {
byte[] b = this.b;
return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16)
| ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF);
}
private String readUTF8(int index, final char[] buf) {
int item = readUnsignedShort(index);
String s = strings[item];
if (s != null) {
return s;
}
index = items[item];
return strings[item] = readUTF(index + 2, readUnsignedShort(index), buf);
}
private String readUTF(int index, final int utfLen, final char[] buf) {
int endIndex = index + utfLen;
byte[] b = this.b;
int strLen = 0;
int c;
int st = 0;
char cc = 0;
while (index < endIndex) {
c = b[index++];
switch (st) {
case 0:
c = c & 0xFF;
if (c < 0x80) { // 0xxxxxxx
buf[strLen++] = (char) c;
} else if (c < 0xE0 && c > 0xBF) { // 110x xxxx 10xx xxxx
cc = (char) (c & 0x1F);
st = 1;
} else { // 1110 xxxx 10xx xxxx 10xx xxxx
cc = (char) (c & 0x0F);
st = 2;
}
break;
case 1: // byte 2 of 2-byte char or byte 3 of 3-byte char
buf[strLen++] = (char) ((cc << 6) | (c & 0x3F));
st = 0;
break;
case 2: // byte 2 of 3-byte char
cc = (char) ((cc << 6) | (c & 0x3F));
st = 1;
break;
}
}
return new String(buf, 0, strLen);
}
}
| header |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalCaseThen.java | {
"start": 185,
"end": 523
} | class ____ extends TestCase {
public void test_eval_then() throws Exception {
assertEquals(111, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "case ? when 0 then 111 else 222 end", 0));
assertEquals(222, SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "case ? when 0 then 111 else 222 end", 1));
}
}
| EvalCaseThen |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/jackson2/FactorGrantedAuthorityMixin.java | {
"start": 1002,
"end": 1855
} | class ____ in serialize/deserialize
* {@link org.springframework.security.core.authority.SimpleGrantedAuthority}.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
*
* @author Rob Winch
* @since 7.0
* @see CoreJackson2Module
* @see SecurityJackson2Modules
* @deprecated as of 7.0 in favor of
* {@code org.springframework.security.jackson.FactorGrantedAuthorityMixin} based on
* Jackson 3
*
*/
@SuppressWarnings("removal")
@Deprecated(forRemoval = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract | helps |
java | apache__camel | components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fix/BindySimpleKeyValuePairFixTest.java | {
"start": 2607,
"end": 4165
} | class ____ extends RouteBuilder {
@Override
public void configure() {
DataFormat bindy = new BindyKeyValuePairDataFormat(FixOrder.class);
from("direct:fix")
.unmarshal(bindy)
.process(new Processor() {
@Override
public void process(Exchange exchange) {
FixOrder order = exchange.getIn().getBody(FixOrder.class);
Object body = exchange.getIn().getBody();
if (order.getProduct().equals("butter")) {
order.setQuantity("2");
body = order;
} else if (order.getProduct().equals("milk")) {
order.setQuantity("4");
body = Collections.singletonMap(order.getClass().getName(), order);
} else if (order.getProduct().equals("bread")) {
order.setQuantity("6");
body = Collections.singletonList(Collections.singletonMap(order.getClass().getName(), order));
}
exchange.getIn().setBody(body);
}
})
.marshal(bindy)
.to("mock:result");
}
}
@Message(keyValuePairSeparator = "=", pairSeparator = " ", type = "FIX", version = "4.1")
public static | ContextConfig |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/telemetry/PlanTelemetry.java | {
"start": 739,
"end": 2067
} | class ____ {
private final EsqlFunctionRegistry functionRegistry;
private final Map<String, Integer> commands = new HashMap<>();
private final Map<String, Integer> functions = new HashMap<>();
public PlanTelemetry(EsqlFunctionRegistry functionRegistry) {
this.functionRegistry = functionRegistry;
}
private void add(Map<String, Integer> map, String key) {
map.compute(key.toUpperCase(Locale.ROOT), (k, count) -> count == null ? 1 : count + 1);
}
public void command(TelemetryAware command) {
Check.notNull(command.telemetryLabel(), "TelemetryAware [{}] has no telemetry label", command);
add(commands, command.telemetryLabel());
}
public void function(String name) {
var functionName = functionRegistry.resolveAlias(name);
if (functionRegistry.functionExists(functionName)) {
// The metrics have been collected initially with their uppercase spelling
add(functions, functionName);
}
}
public void function(Class<? extends Function> clazz) {
add(functions, functionRegistry.snapshotRegistry().functionName(clazz));
}
public Map<String, Integer> commands() {
return commands;
}
public Map<String, Integer> functions() {
return functions;
}
}
| PlanTelemetry |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/request/target/NotificationTarget.java | {
"start": 560,
"end": 868
} | class ____ used to display downloaded Bitmap inside an ImageView of a Notification through
* RemoteViews.
*
* <p>Note - For cancellation to work correctly, you must pass in the same instance of this class
* for every subsequent load.
*/
// Public API.
@SuppressWarnings({"WeakerAccess", "unused"})
public | is |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/env/repeatable/AbstractClassWithTestProperty.java | {
"start": 766,
"end": 993
} | class ____ declares an inlined property via
* {@link TestPropertySource @TestPropertySource}.
*
* @author Anatoliy Korovin
* @author Sam Brannen
* @since 5.2
*/
@TestPropertySource(properties = "key1 = parent")
abstract | which |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptivebatch/AdaptiveExecutionHandlerFactory.java | {
"start": 1211,
"end": 1396
} | class ____ creating instances of {@link AdaptiveExecutionHandler}. This factory provides
* a method to create an appropriate handler based on the type of the execution plan.
*/
public | for |
java | spring-projects__spring-boot | module/spring-boot-data-couchbase-test/src/dockerTest/java/org/springframework/boot/data/couchbase/test/autoconfigure/DataCouchbaseTestReactiveIntegrationTests.java | {
"start": 1809,
"end": 2760
} | class ____ {
private static final String BUCKET_NAME = "cbbucket";
@Container
@ServiceConnection
static final CouchbaseContainer couchbase = TestImage.container(CouchbaseContainer.class)
.withEnabledServices(CouchbaseService.KV, CouchbaseService.INDEX, CouchbaseService.QUERY)
.withBucket(new BucketDefinition(BUCKET_NAME));
@Autowired
private ReactiveCouchbaseTemplate couchbaseTemplate;
@Autowired
private ExampleReactiveRepository exampleReactiveRepository;
@Test
void testRepository() {
ExampleDocument document = new ExampleDocument();
document.setText("Look, new @DataCouchbaseTest!");
document = this.exampleReactiveRepository.save(document).block(Duration.ofSeconds(30));
assertThat(document).isNotNull();
assertThat(document.getId()).isNotNull();
assertThat(this.couchbaseTemplate.getBucketName()).isEqualTo(BUCKET_NAME);
this.exampleReactiveRepository.deleteAll();
}
}
| DataCouchbaseTestReactiveIntegrationTests |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/ssl/pem/LoadedPemSslStore.java | {
"start": 1273,
"end": 3996
} | class ____ implements PemSslStore {
private final PemSslStoreDetails details;
private final ResourceLoader resourceLoader;
private final Supplier<CertificatesHolder> certificatesSupplier;
private final Supplier<PrivateKeyHolder> privateKeySupplier;
LoadedPemSslStore(PemSslStoreDetails details, ResourceLoader resourceLoader) {
Assert.notNull(details, "'details' must not be null");
Assert.notNull(resourceLoader, "'resourceLoader' must not be null");
this.details = details;
this.resourceLoader = resourceLoader;
this.certificatesSupplier = supplier(() -> loadCertificates(details, resourceLoader));
this.privateKeySupplier = supplier(() -> loadPrivateKey(details, resourceLoader));
}
private static <T> Supplier<T> supplier(ThrowingSupplier<T> supplier) {
return SingletonSupplier.of(supplier.throwing(LoadedPemSslStore::asUncheckedIOException));
}
private static UncheckedIOException asUncheckedIOException(String message, Exception cause) {
return new UncheckedIOException(message, (IOException) cause);
}
private static CertificatesHolder loadCertificates(PemSslStoreDetails details, ResourceLoader resourceLoader)
throws IOException {
PemContent pemContent = PemContent.load(details.certificates(), resourceLoader);
if (pemContent == null) {
return new CertificatesHolder(null);
}
return new CertificatesHolder(pemContent.getCertificates());
}
private static PrivateKeyHolder loadPrivateKey(PemSslStoreDetails details, ResourceLoader resourceLoader)
throws IOException {
PemContent pemContent = PemContent.load(details.privateKey(), resourceLoader);
return new PrivateKeyHolder(
(pemContent != null) ? pemContent.getPrivateKey(details.privateKeyPassword()) : null);
}
@Override
public @Nullable String type() {
return this.details.type();
}
@Override
public @Nullable String alias() {
return this.details.alias();
}
@Override
public @Nullable String password() {
return this.details.password();
}
@Override
public @Nullable List<X509Certificate> certificates() {
return this.certificatesSupplier.get().certificates();
}
@Override
public @Nullable PrivateKey privateKey() {
return this.privateKeySupplier.get().privateKey();
}
@Override
public PemSslStore withAlias(@Nullable String alias) {
return new LoadedPemSslStore(this.details.withAlias(alias), this.resourceLoader);
}
@Override
public PemSslStore withPassword(@Nullable String password) {
return new LoadedPemSslStore(this.details.withPassword(password), this.resourceLoader);
}
private record PrivateKeyHolder(@Nullable PrivateKey privateKey) {
}
private record CertificatesHolder(@Nullable List<X509Certificate> certificates) {
}
}
| LoadedPemSslStore |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/features/ResetFeatureStateRequest.java | {
"start": 901,
"end": 1555
} | class ____ extends MasterNodeRequest<ResetFeatureStateRequest> {
public static ResetFeatureStateRequest fromStream(StreamInput in) throws IOException {
return new ResetFeatureStateRequest(in);
}
public ResetFeatureStateRequest(TimeValue masterNodeTimeout) {
super(masterNodeTimeout);
}
private ResetFeatureStateRequest(StreamInput in) throws IOException {
super(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
@Override
public ActionRequestValidationException validate() {
return null;
}
}
| ResetFeatureStateRequest |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/verbose/CreateIterableMapping.java | {
"start": 295,
"end": 480
} | interface ____ {
CreateIterableMapping INSTANCE = Mappers.getMapper( CreateIterableMapping.class );
List<TargetElement> map(List<SourceElement> source);
| CreateIterableMapping |
java | apache__maven | compat/maven-settings-builder/src/main/java/org/apache/maven/settings/crypto/DefaultSettingsDecryptionRequest.java | {
"start": 1191,
"end": 2993
} | class ____ implements SettingsDecryptionRequest {
private List<Server> servers;
private List<Proxy> proxies;
/**
* Creates an empty request.
*/
public DefaultSettingsDecryptionRequest() {
// does nothing
}
/**
* Creates a new request to decrypt the specified settings.
*
* @param settings The settings to decrypt, must not be {@code null}.
*/
public DefaultSettingsDecryptionRequest(Settings settings) {
setServers(settings.getServers());
setProxies(settings.getProxies());
}
/**
* Creates a new request to decrypt the specified server.
*
* @param server The server to decrypt, must not be {@code null}.
*/
public DefaultSettingsDecryptionRequest(Server server) {
this.servers = new ArrayList<>(Arrays.asList(server));
}
/**
* Creates a new request to decrypt the specified proxy.
*
* @param proxy The proxy to decrypt, must not be {@code null}.
*/
public DefaultSettingsDecryptionRequest(Proxy proxy) {
this.proxies = new ArrayList<>(Arrays.asList(proxy));
}
@Override
public List<Server> getServers() {
if (servers == null) {
servers = new ArrayList<>();
}
return servers;
}
@Override
public DefaultSettingsDecryptionRequest setServers(List<Server> servers) {
this.servers = servers;
return this;
}
@Override
public List<Proxy> getProxies() {
if (proxies == null) {
proxies = new ArrayList<>();
}
return proxies;
}
@Override
public DefaultSettingsDecryptionRequest setProxies(List<Proxy> proxies) {
this.proxies = proxies;
return this;
}
}
| DefaultSettingsDecryptionRequest |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/ResourceRequestPreMappingsTest.java | {
"start": 1553,
"end": 18060
} | class ____ {
private static final ResourceProfile smallFineGrainedResourceProfile =
ResourceProfile.newBuilder().setManagedMemoryMB(10).build();
private static final ResourceProfile bigGrainedResourceProfile =
ResourceProfile.newBuilder().setManagedMemoryMB(20).build();
@Test
void testIncludeInvalidProfileOfRequestOrResource() {
// For invalid resource.
ResourceProfile[] profiles =
new ResourceProfile[] {ResourceProfile.UNKNOWN, ResourceProfile.ZERO};
for (ResourceProfile profile : profiles) {
assertThatThrownBy(
() ->
ResourceRequestPreMappings.createFrom(
Collections.emptyList(), newTestingSlots(profile)))
.isInstanceOf(IllegalStateException.class);
}
// For invalid request.
profiles = new ResourceProfile[] {ResourceProfile.ANY, ResourceProfile.ZERO};
for (ResourceProfile profile : profiles) {
assertThatThrownBy(
() ->
ResourceRequestPreMappings.createFrom(
newPendingRequests(profile), Collections.emptyList()))
.isInstanceOf(IllegalStateException.class);
}
}
@Test
void testBuildWhenUnavailableTotalResourcesOrEmptyRequestsResources() {
// Testing for unavailable total resource
ResourceRequestPreMappings preMappings =
ResourceRequestPreMappings.createFrom(
newPendingRequests(ResourceProfile.UNKNOWN), Collections.emptyList());
assertThat(preMappings.isMatchingFulfilled()).isFalse();
assertThat(preMappings.getBaseRequiredResourcePreMappings()).isEmpty();
// Testing for empty slots or requests
preMappings =
ResourceRequestPreMappings.createFrom(
Collections.emptyList(), Collections.emptyList());
assertNotMatchable(preMappings);
}
@Test
void testBuildWhenMissingResourceToMatchFineGrainedRequest() {
// Testing for missing available fine-grained resources when only fine-grained request
ResourceRequestPreMappings preMappings =
ResourceRequestPreMappings.createFrom(
newPendingRequests(
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile,
bigGrainedResourceProfile),
newTestingSlots(
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile));
assertNotMatchable(preMappings);
// Testing for missing available fine-grained resources when fine-grained and unknown
// requests.
preMappings =
ResourceRequestPreMappings.createFrom(
newPendingRequests(
ResourceProfile.UNKNOWN,
smallFineGrainedResourceProfile,
bigGrainedResourceProfile),
newTestingSlots(
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile));
assertNotMatchable(preMappings);
}
@Test
void testBuildSuccessfullyThatFinedGrainedMatchedExactly() {
ResourceRequestPreMappings preMappings =
ResourceRequestPreMappings.createFrom(
newPendingRequests(
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile,
bigGrainedResourceProfile),
newTestingSlots(
bigGrainedResourceProfile,
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile));
assertThat(preMappings.isMatchingFulfilled()).isTrue();
assertThat(preMappings.getBaseRequiredResourcePreMappings())
.hasSize(2)
.contains(
new AbstractMap.SimpleEntry<>(
smallFineGrainedResourceProfile,
new HashMap<>() {
{
put(smallFineGrainedResourceProfile, 2);
}
}),
new AbstractMap.SimpleEntry<>(
bigGrainedResourceProfile,
new HashMap<>() {
{
put(bigGrainedResourceProfile, 1);
}
}));
assertThat(preMappings.getRemainingFlexibleResources())
.contains(new AbstractMap.SimpleEntry<>(smallFineGrainedResourceProfile, 1));
}
@Test
void testBuildSuccessfullyThatFinedGrainedToMatchedUnknownRequests() {
// Testing for available all resources and no UNKNOWN required resource.
ResourceRequestPreMappings preMappings =
ResourceRequestPreMappings.createFrom(
newPendingRequests(
ResourceProfile.UNKNOWN,
ResourceProfile.UNKNOWN,
smallFineGrainedResourceProfile,
bigGrainedResourceProfile),
newTestingSlots(
bigGrainedResourceProfile,
bigGrainedResourceProfile,
bigGrainedResourceProfile,
ResourceProfile.ANY,
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile));
assertThat(preMappings.isMatchingFulfilled()).isTrue();
assertThat(preMappings.getBaseRequiredResourcePreMappings())
.hasSize(3)
.contains(
new AbstractMap.SimpleEntry<>(
smallFineGrainedResourceProfile,
new HashMap<>() {
{
put(smallFineGrainedResourceProfile, 1);
}
}),
new AbstractMap.SimpleEntry<>(
bigGrainedResourceProfile,
new HashMap<>() {
{
put(bigGrainedResourceProfile, 1);
}
}));
Map<ResourceProfile, Integer> unknownBaseMapping =
preMappings.getBaseRequiredResourcePreMappings().get(ResourceProfile.UNKNOWN);
assertThat(unknownBaseMapping.values().stream().reduce(0, Integer::sum)).isEqualTo(2);
assertThat(
preMappings.getRemainingFlexibleResources().values().stream()
.reduce(0, Integer::sum))
.isEqualTo(2);
}
@Test
void testBuildSuccessfullyThatAnyToMatchedUnknownAndFineGrainedRequests() {
// Testing for available all resources and no UNKNOWN required resource.
ResourceRequestPreMappings preMappings =
ResourceRequestPreMappings.createFrom(
newPendingRequests(
ResourceProfile.UNKNOWN,
ResourceProfile.UNKNOWN,
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile,
bigGrainedResourceProfile,
bigGrainedResourceProfile),
newTestingSlots(
bigGrainedResourceProfile,
smallFineGrainedResourceProfile,
ResourceProfile.ANY,
ResourceProfile.ANY,
ResourceProfile.ANY,
ResourceProfile.ANY));
assertThat(preMappings.isMatchingFulfilled()).isTrue();
assertThat(preMappings.getBaseRequiredResourcePreMappings())
.hasSize(3)
.contains(
new AbstractMap.SimpleEntry<>(
smallFineGrainedResourceProfile,
new HashMap<>() {
{
put(smallFineGrainedResourceProfile, 1);
put(ResourceProfile.ANY, 1);
}
}),
new AbstractMap.SimpleEntry<>(
bigGrainedResourceProfile,
new HashMap<>() {
{
put(bigGrainedResourceProfile, 1);
put(ResourceProfile.ANY, 1);
}
}),
new AbstractMap.SimpleEntry<>(
ResourceProfile.UNKNOWN,
new HashMap<>() {
{
put(ResourceProfile.ANY, 2);
}
}));
assertThat(
preMappings.getRemainingFlexibleResources().values().stream()
.reduce(0, Integer::sum))
.isZero();
}
@Test
void testHasAvailableProfile() {
ResourceRequestPreMappings mappings =
ResourceRequestPreMappings.createFrom(
newPendingRequests(ResourceProfile.UNKNOWN, ResourceProfile.UNKNOWN),
newTestingSlots(
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile));
// Testing available resource in flexible resources
assertThat(
mappings.hasAvailableProfile(
smallFineGrainedResourceProfile, smallFineGrainedResourceProfile))
.isTrue();
assertThat(
mappings.hasAvailableProfile(
smallFineGrainedResourceProfile, bigGrainedResourceProfile))
.isFalse();
// Testing available resource in base mapping resources
assertThat(
mappings.hasAvailableProfile(
ResourceProfile.UNKNOWN, smallFineGrainedResourceProfile))
.isTrue();
assertThat(mappings.hasAvailableProfile(ResourceProfile.UNKNOWN, bigGrainedResourceProfile))
.isFalse();
}
@Test
void testDecrease() {
// Testing decrease resource in base mapping
ResourceRequestPreMappings mappings =
ResourceRequestPreMappings.createFrom(
newPendingRequests(ResourceProfile.UNKNOWN, ResourceProfile.UNKNOWN),
newTestingSlots(
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile));
// Testing decrease resource in base mapping resources successfully
mappings.decrease(ResourceProfile.UNKNOWN, smallFineGrainedResourceProfile);
assertThat(
mappings.getAvailableResourceCntOfBasePreMappings(
ResourceProfile.UNKNOWN, smallFineGrainedResourceProfile))
.isOne();
// Testing decrease resource in base mapping resources failed
assertThatThrownBy(
() ->
mappings.decrease(
smallFineGrainedResourceProfile,
smallFineGrainedResourceProfile))
.isInstanceOf(IllegalStateException.class);
// Testing decrease resource in flexible resources
ResourceRequestPreMappings mappings2 =
ResourceRequestPreMappings.createFrom(
true,
new HashMap<>() {
{
put(
ResourceProfile.UNKNOWN,
new HashMap<>() {
{
put(smallFineGrainedResourceProfile, 2);
}
});
}
},
new HashMap<>() {
{
put(smallFineGrainedResourceProfile, 1);
put(bigGrainedResourceProfile, 2);
}
});
// Testing decrease resource in flexible resources successfully
mappings2.decrease(ResourceProfile.UNKNOWN, bigGrainedResourceProfile);
assertThat(
mappings2.getAvailableResourceCntOfRemainingFlexibleMapping(
bigGrainedResourceProfile))
.isOne();
assertThat(
mappings2.getAvailableResourceCntOfBasePreMappings(
ResourceProfile.UNKNOWN, smallFineGrainedResourceProfile))
.isOne();
assertThat(
mappings2.getAvailableResourceCntOfRemainingFlexibleMapping(
smallFineGrainedResourceProfile))
.isEqualTo(2);
// Testing decrease resource in flexible resources failed
mappings2.decrease(ResourceProfile.UNKNOWN, smallFineGrainedResourceProfile);
assertThatThrownBy(
() ->
mappings2.decrease(
ResourceProfile.UNKNOWN, smallFineGrainedResourceProfile))
.isInstanceOf(IllegalStateException.class);
}
private List<PendingRequest> newPendingRequests(ResourceProfile... requiredProfiles) {
ArrayList<PendingRequest> pendingRequests = new ArrayList<>();
if (requiredProfiles == null || requiredProfiles.length == 0) {
return pendingRequests;
}
for (ResourceProfile requiredProfile : requiredProfiles) {
pendingRequests.add(
PendingRequest.createNormalRequest(
new SlotRequestId(),
Preconditions.checkNotNull(requiredProfile),
DefaultLoadingWeight.EMPTY,
Collections.emptyList()));
}
return pendingRequests;
}
private List<TestingSlot> newTestingSlots(ResourceProfile... slotProfiles) {
ArrayList<TestingSlot> slots = new ArrayList<>();
if (slotProfiles == null || slotProfiles.length == 0) {
return slots;
}
for (ResourceProfile slotProfile : slotProfiles) {
slots.add(new TestingSlot(Preconditions.checkNotNull(slotProfile)));
}
return slots;
}
private void assertNotMatchable(ResourceRequestPreMappings preMappings) {
assertThat(preMappings.isMatchingFulfilled()).isFalse();
assertThat(preMappings.getBaseRequiredResourcePreMappings()).isEmpty();
}
}
| ResourceRequestPreMappingsTest |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/security/oauthbearer/OAuthBearerValidatorCallbackHandlerTest.java | {
"start": 2041,
"end": 8546
} | class ____ extends OAuthBearerTest {
@Test
public void testBasic() throws Exception {
String expectedAudience = "a";
List<String> allAudiences = Arrays.asList(expectedAudience, "b", "c");
AccessTokenBuilder builder = new AccessTokenBuilder()
.audience(expectedAudience)
.jwk(createRsaJwk())
.alg(AlgorithmIdentifiers.RSA_USING_SHA256);
String accessToken = builder.build();
Map<String, ?> configs = getSaslConfigs(SASL_OAUTHBEARER_EXPECTED_AUDIENCE, allAudiences);
CloseableVerificationKeyResolver verificationKeyResolver = createVerificationKeyResolver(builder);
JwtValidator jwtValidator = createJwtValidator(verificationKeyResolver);
OAuthBearerValidatorCallbackHandler handler = new OAuthBearerValidatorCallbackHandler();
handler.configure(
configs,
OAUTHBEARER_MECHANISM,
getJaasConfigEntries(),
verificationKeyResolver,
jwtValidator
);
try {
OAuthBearerValidatorCallback callback = new OAuthBearerValidatorCallback(accessToken);
handler.handle(new Callback[]{callback});
assertNotNull(callback.token());
OAuthBearerToken token = callback.token();
assertEquals(accessToken, token.value());
assertEquals(builder.subject(), token.principalName());
assertEquals(builder.expirationSeconds() * 1000, token.lifetimeMs());
assertEquals(builder.issuedAtSeconds() * 1000, token.startTimeMs());
} finally {
handler.close();
}
}
@Test
public void testInvalidAccessToken() throws Exception {
// There aren't different error messages for the validation step, so these are all the
// same :(
String substring = "invalid_token";
assertInvalidAccessTokenFails("this isn't valid", substring);
assertInvalidAccessTokenFails("this.isn't.valid", substring);
assertInvalidAccessTokenFails(createJwt("this", "isn't", "valid"), substring);
assertInvalidAccessTokenFails(createJwt("{}", "{}", "{}"), substring);
}
@Test
public void testHandlerConfigureThrowsException() throws IOException {
KafkaException configureError = new KafkaException("configure() error");
AccessTokenBuilder builder = new AccessTokenBuilder()
.alg(AlgorithmIdentifiers.RSA_USING_SHA256);
CloseableVerificationKeyResolver verificationKeyResolver = createVerificationKeyResolver(builder);
JwtValidator jwtValidator = new JwtValidator() {
@Override
public void configure(Map<String, ?> configs, String saslMechanism, List<AppConfigurationEntry> jaasConfigEntries) {
throw configureError;
}
@Override
public OAuthBearerToken validate(String accessToken) throws JwtValidatorException {
return null;
}
};
OAuthBearerValidatorCallbackHandler handler = new OAuthBearerValidatorCallbackHandler();
// An error initializing the JwtValidator should cause OAuthBearerValidatorCallbackHandler.init() to fail.
KafkaException error = assertThrows(
KafkaException.class,
() -> handler.configure(
getSaslConfigs(),
OAUTHBEARER_MECHANISM,
getJaasConfigEntries(),
verificationKeyResolver,
jwtValidator
)
);
assertEquals(configureError, error);
}
@Test
public void testHandlerCloseDoesNotThrowException() throws IOException {
AccessTokenBuilder builder = new AccessTokenBuilder()
.alg(AlgorithmIdentifiers.RSA_USING_SHA256);
CloseableVerificationKeyResolver verificationKeyResolver = createVerificationKeyResolver(builder);
JwtValidator jwtValidator = new JwtValidator() {
@Override
public void close() throws IOException {
throw new IOException("close() error");
}
@Override
public OAuthBearerToken validate(String accessToken) throws JwtValidatorException {
return null;
}
};
OAuthBearerValidatorCallbackHandler handler = new OAuthBearerValidatorCallbackHandler();
handler.configure(
getSaslConfigs(),
OAUTHBEARER_MECHANISM,
getJaasConfigEntries(),
verificationKeyResolver,
jwtValidator
);
// An error closings the JwtValidator should *not* cause OAuthBearerValidatorCallbackHandler.close() to fail.
assertDoesNotThrow(handler::close);
}
private void assertInvalidAccessTokenFails(String accessToken, String expectedMessageSubstring) throws Exception {
AccessTokenBuilder builder = new AccessTokenBuilder()
.alg(AlgorithmIdentifiers.RSA_USING_SHA256);
Map<String, ?> configs = getSaslConfigs();
CloseableVerificationKeyResolver verificationKeyResolver = createVerificationKeyResolver(builder);
JwtValidator jwtValidator = createJwtValidator(verificationKeyResolver);
OAuthBearerValidatorCallbackHandler handler = new OAuthBearerValidatorCallbackHandler();
handler.configure(
configs,
OAUTHBEARER_MECHANISM,
getJaasConfigEntries(),
verificationKeyResolver,
jwtValidator
);
try {
OAuthBearerValidatorCallback callback = new OAuthBearerValidatorCallback(accessToken);
handler.handle(new Callback[] {callback});
assertNull(callback.token());
String actualMessage = callback.errorStatus();
assertNotNull(actualMessage);
assertTrue(actualMessage.contains(expectedMessageSubstring), String.format("The error message \"%s\" didn't contain the expected substring \"%s\"", actualMessage, expectedMessageSubstring));
} finally {
handler.close();
}
}
private JwtValidator createJwtValidator(CloseableVerificationKeyResolver verificationKeyResolver) {
return new DefaultJwtValidator(verificationKeyResolver);
}
private CloseableVerificationKeyResolver createVerificationKeyResolver(AccessTokenBuilder builder) {
return (jws, nestingContext) -> builder.jwk().getPublicKey();
}
}
| OAuthBearerValidatorCallbackHandlerTest |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/interceptor/CustomizableTraceInterceptor.java | {
"start": 4108,
"end": 15216
} | class ____.
*/
public static final String PLACEHOLDER_ARGUMENT_TYPES = "$[argumentTypes]";
/**
* The {@code $[arguments]} placeholder.
* Replaced with a comma separated list of the argument values for the
* method invocation. Relies on the {@code toString()} method of
* each argument type.
*/
public static final String PLACEHOLDER_ARGUMENTS = "$[arguments]";
/**
* The {@code $[exception]} placeholder.
* Replaced with the {@code String} representation of any
* {@code Throwable} raised during method invocation.
*/
public static final String PLACEHOLDER_EXCEPTION = "$[exception]";
/**
* The {@code $[invocationTime]} placeholder.
* Replaced with the time taken by the invocation (in milliseconds).
*/
public static final String PLACEHOLDER_INVOCATION_TIME = "$[invocationTime]";
/**
* The default message used for writing method entry messages.
*/
private static final String DEFAULT_ENTER_MESSAGE = "Entering method '" +
PLACEHOLDER_METHOD_NAME + "' of class [" + PLACEHOLDER_TARGET_CLASS_NAME + "]";
/**
* The default message used for writing method exit messages.
*/
private static final String DEFAULT_EXIT_MESSAGE = "Exiting method '" +
PLACEHOLDER_METHOD_NAME + "' of class [" + PLACEHOLDER_TARGET_CLASS_NAME + "]";
/**
* The default message used for writing exception messages.
*/
private static final String DEFAULT_EXCEPTION_MESSAGE = "Exception thrown in method '" +
PLACEHOLDER_METHOD_NAME + "' of class [" + PLACEHOLDER_TARGET_CLASS_NAME + "]";
/**
* The {@code Pattern} used to match placeholders.
*/
private static final Pattern PATTERN = Pattern.compile("\\$\\[\\p{Alpha}+]");
/**
* The {@code Set} of allowed placeholders.
*/
static final Set<String> ALLOWED_PLACEHOLDERS = Set.of(
PLACEHOLDER_METHOD_NAME,
PLACEHOLDER_TARGET_CLASS_NAME,
PLACEHOLDER_TARGET_CLASS_SHORT_NAME,
PLACEHOLDER_RETURN_VALUE,
PLACEHOLDER_ARGUMENT_TYPES,
PLACEHOLDER_ARGUMENTS,
PLACEHOLDER_EXCEPTION,
PLACEHOLDER_INVOCATION_TIME);
/**
* The message for method entry.
*/
private String enterMessage = DEFAULT_ENTER_MESSAGE;
/**
* The message for method exit.
*/
private String exitMessage = DEFAULT_EXIT_MESSAGE;
/**
* The message for exceptions during method execution.
*/
private String exceptionMessage = DEFAULT_EXCEPTION_MESSAGE;
/**
* Set the template used for method entry log messages.
* This template can contain any of the following placeholders:
* <ul>
* <li>{@code $[targetClassName]}</li>
* <li>{@code $[targetClassShortName]}</li>
* <li>{@code $[argumentTypes]}</li>
* <li>{@code $[arguments]}</li>
* </ul>
*/
public void setEnterMessage(String enterMessage) throws IllegalArgumentException {
Assert.hasText(enterMessage, "enterMessage must not be empty");
checkForInvalidPlaceholders(enterMessage);
Assert.doesNotContain(enterMessage, PLACEHOLDER_RETURN_VALUE,
"enterMessage cannot contain placeholder " + PLACEHOLDER_RETURN_VALUE);
Assert.doesNotContain(enterMessage, PLACEHOLDER_EXCEPTION,
"enterMessage cannot contain placeholder " + PLACEHOLDER_EXCEPTION);
Assert.doesNotContain(enterMessage, PLACEHOLDER_INVOCATION_TIME,
"enterMessage cannot contain placeholder " + PLACEHOLDER_INVOCATION_TIME);
this.enterMessage = enterMessage;
}
/**
* Set the template used for method exit log messages.
* This template can contain any of the following placeholders:
* <ul>
* <li>{@code $[targetClassName]}</li>
* <li>{@code $[targetClassShortName]}</li>
* <li>{@code $[argumentTypes]}</li>
* <li>{@code $[arguments]}</li>
* <li>{@code $[returnValue]}</li>
* <li>{@code $[invocationTime]}</li>
* </ul>
*/
public void setExitMessage(String exitMessage) {
Assert.hasText(exitMessage, "exitMessage must not be empty");
checkForInvalidPlaceholders(exitMessage);
Assert.doesNotContain(exitMessage, PLACEHOLDER_EXCEPTION,
"exitMessage cannot contain placeholder" + PLACEHOLDER_EXCEPTION);
this.exitMessage = exitMessage;
}
/**
* Set the template used for method exception log messages.
* This template can contain any of the following placeholders:
* <ul>
* <li>{@code $[targetClassName]}</li>
* <li>{@code $[targetClassShortName]}</li>
* <li>{@code $[argumentTypes]}</li>
* <li>{@code $[arguments]}</li>
* <li>{@code $[exception]}</li>
* </ul>
*/
public void setExceptionMessage(String exceptionMessage) {
Assert.hasText(exceptionMessage, "exceptionMessage must not be empty");
checkForInvalidPlaceholders(exceptionMessage);
Assert.doesNotContain(exceptionMessage, PLACEHOLDER_RETURN_VALUE,
"exceptionMessage cannot contain placeholder " + PLACEHOLDER_RETURN_VALUE);
this.exceptionMessage = exceptionMessage;
}
/**
* Writes a log message before the invocation based on the value of {@code enterMessage}.
* If the invocation succeeds, then a log message is written on exit based on the value
* {@code exitMessage}. If an exception occurs during invocation, then a message is
* written based on the value of {@code exceptionMessage}.
* @see #setEnterMessage
* @see #setExitMessage
* @see #setExceptionMessage
*/
@Override
protected @Nullable Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable {
String name = ClassUtils.getQualifiedMethodName(invocation.getMethod());
StopWatch stopWatch = new StopWatch(name);
Object returnValue = null;
boolean exitThroughException = false;
try {
stopWatch.start(name);
writeToLog(logger,
replacePlaceholders(this.enterMessage, invocation, null, null, -1));
returnValue = invocation.proceed();
return returnValue;
}
catch (Throwable ex) {
if (stopWatch.isRunning()) {
stopWatch.stop();
}
exitThroughException = true;
writeToLog(logger, replacePlaceholders(
this.exceptionMessage, invocation, null, ex, stopWatch.getTotalTimeMillis()), ex);
throw ex;
}
finally {
if (!exitThroughException) {
if (stopWatch.isRunning()) {
stopWatch.stop();
}
writeToLog(logger, replacePlaceholders(
this.exitMessage, invocation, returnValue, null, stopWatch.getTotalTimeMillis()));
}
}
}
/**
* Replace the placeholders in the given message with the supplied values,
* or values derived from those supplied.
* @param message the message template containing the placeholders to be replaced
* @param methodInvocation the {@code MethodInvocation} being logged.
* Used to derive values for all placeholders except {@code $[exception]}
* and {@code $[returnValue]}.
* @param returnValue any value returned by the invocation.
* Used to replace the {@code $[returnValue]} placeholder. May be {@code null}.
* @param throwable any {@code Throwable} raised during the invocation.
* The value of {@code Throwable.toString()} is replaced for the
* {@code $[exception]} placeholder. May be {@code null}.
* @param invocationTime the value to write in place of the
* {@code $[invocationTime]} placeholder
* @return the formatted output to write to the log
*/
protected String replacePlaceholders(String message, MethodInvocation methodInvocation,
@Nullable Object returnValue, @Nullable Throwable throwable, long invocationTime) {
Object target = methodInvocation.getThis();
Assert.state(target != null, "Target must not be null");
StringBuilder output = new StringBuilder();
Matcher matcher = PATTERN.matcher(message);
while (matcher.find()) {
String match = matcher.group();
switch (match) {
case PLACEHOLDER_METHOD_NAME -> matcher.appendReplacement(output,
Matcher.quoteReplacement(methodInvocation.getMethod().getName()));
case PLACEHOLDER_TARGET_CLASS_NAME -> {
String className = getClassForLogging(target).getName();
matcher.appendReplacement(output, Matcher.quoteReplacement(className));
}
case PLACEHOLDER_TARGET_CLASS_SHORT_NAME -> {
String shortName = ClassUtils.getShortName(getClassForLogging(target));
matcher.appendReplacement(output, Matcher.quoteReplacement(shortName));
}
case PLACEHOLDER_ARGUMENTS -> matcher.appendReplacement(output,
Matcher.quoteReplacement(StringUtils.arrayToCommaDelimitedString(methodInvocation.getArguments())));
case PLACEHOLDER_ARGUMENT_TYPES -> appendArgumentTypes(methodInvocation, matcher, output);
case PLACEHOLDER_RETURN_VALUE -> appendReturnValue(methodInvocation, matcher, output, returnValue);
case PLACEHOLDER_EXCEPTION -> {
if (throwable != null) {
matcher.appendReplacement(output, Matcher.quoteReplacement(throwable.toString()));
}
}
case PLACEHOLDER_INVOCATION_TIME -> matcher.appendReplacement(output, Long.toString(invocationTime));
default -> {
// Should not happen since placeholders are checked earlier.
throw new IllegalArgumentException("Unknown placeholder [" + match + "]");
}
}
}
matcher.appendTail(output);
return output.toString();
}
/**
* Adds the {@code String} representation of the method return value
* to the supplied {@code StringBuilder}. Correctly handles
* {@code null} and {@code void} results.
* @param methodInvocation the {@code MethodInvocation} that returned the value
* @param matcher the {@code Matcher} containing the matched placeholder
* @param output the {@code StringBuilder} to write output to
* @param returnValue the value returned by the method invocation.
*/
private static void appendReturnValue(
MethodInvocation methodInvocation, Matcher matcher, StringBuilder output, @Nullable Object returnValue) {
if (methodInvocation.getMethod().getReturnType() == void.class) {
matcher.appendReplacement(output, "void");
}
else if (returnValue == null) {
matcher.appendReplacement(output, "null");
}
else {
matcher.appendReplacement(output, Matcher.quoteReplacement(returnValue.toString()));
}
}
/**
* Adds a comma-separated list of the short {@code Class} names of the
* method argument types to the output. For example, if a method has signature
* {@code put(java.lang.String, java.lang.Object)} then the value returned
* will be {@code String, Object}.
* @param methodInvocation the {@code MethodInvocation} being logged.
* Arguments will be retrieved from the corresponding {@code Method}.
* @param matcher the {@code Matcher} containing the state of the output
* @param output the {@code StringBuilder} containing the output
*/
private static void appendArgumentTypes(MethodInvocation methodInvocation, Matcher matcher, StringBuilder output) {
Class<?>[] argumentTypes = methodInvocation.getMethod().getParameterTypes();
String[] argumentTypeShortNames = new String[argumentTypes.length];
for (int i = 0; i < argumentTypeShortNames.length; i++) {
argumentTypeShortNames[i] = ClassUtils.getShortName(argumentTypes[i]);
}
matcher.appendReplacement(output,
Matcher.quoteReplacement(StringUtils.arrayToCommaDelimitedString(argumentTypeShortNames)));
}
/**
* Checks to see if the supplied {@code String} has any placeholders
* that are not specified as constants on this | names |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/instantiation/InstantiationWithGenericsExpressionTest.java | {
"start": 5585,
"end": 5882
} | class ____ {
private final Long gen;
private final String data;
public ConstructorDto(Long gen, String data) {
this.gen = gen;
this.data = data;
}
public Long getGen() {
return gen;
}
public String getData() {
return data;
}
}
@Imported
public static | ConstructorDto |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/error/uri/ShouldHaveAuthority.java | {
"start": 812,
"end": 1646
} | class ____ extends BasicErrorMessageFactory {
private static final String SHOULD_HAVE_AUTHORITY = "%nExpecting authority of%n <%s>%nto be:%n <%s>%nbut was:%n <%s>";
public static ErrorMessageFactory shouldHaveAuthority(URI actual, String expectedAuthority) {
return new ShouldHaveAuthority(actual, expectedAuthority);
}
private ShouldHaveAuthority(URI actual, String expectedAuthority) {
super(SHOULD_HAVE_AUTHORITY, actual, expectedAuthority, actual.getAuthority());
}
public static ErrorMessageFactory shouldHaveAuthority(URL actual, String expectedAuthority) {
return new ShouldHaveAuthority(actual, expectedAuthority);
}
private ShouldHaveAuthority(URL actual, String expectedAuthority) {
super(SHOULD_HAVE_AUTHORITY, actual, expectedAuthority, actual.getAuthority());
}
}
| ShouldHaveAuthority |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/join/RetryableAsyncLookupFunctionDelegatorTest.java | {
"start": 5703,
"end": 6874
} | class ____ extends AsyncLookupFunction {
private static final long serialVersionUID = 1L;
private final Random random = new Random();
private transient ExecutorService executor;
@Override
public void open(FunctionContext context) throws Exception {
super.open(context);
this.executor = Executors.newFixedThreadPool(2);
}
@Override
public CompletableFuture<Collection<RowData>> asyncLookup(RowData keyRow) {
return CompletableFuture.supplyAsync(
() -> {
try {
Thread.sleep(random.nextInt(5));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return data.get(keyRow);
},
executor);
}
@Override
public void close() throws Exception {
if (null != executor && !executor.isShutdown()) {
executor.shutdown();
}
super.close();
}
}
}
| TestingAsyncLookupFunction |
java | apache__logging-log4j2 | log4j-core-test/src/main/java/org/apache/logging/log4j/core/test/BasicConfigurationFactory.java | {
"start": 1294,
"end": 1807
} | class ____ extends ConfigurationFactory {
@Override
public Configuration getConfiguration(
final LoggerContext loggerContext, final String name, final URI configLocation) {
return new BasicConfiguration();
}
@Override
public String[] getSupportedTypes() {
return null;
}
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
return null;
}
public | BasicConfigurationFactory |
java | google__guava | android/guava-tests/benchmark/com/google/common/math/IntMathBenchmark.java | {
"start": 1320,
"end": 3363
} | class ____ {
private static final int[] exponent = new int[ARRAY_SIZE];
private static final int[] factorial = new int[ARRAY_SIZE];
private static final int[] binomial = new int[ARRAY_SIZE];
private static final int[] positive = new int[ARRAY_SIZE];
private static final int[] nonnegative = new int[ARRAY_SIZE];
private static final int[] ints = new int[ARRAY_SIZE];
@BeforeExperiment
void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
exponent[i] = randomExponent();
factorial[i] = RANDOM_SOURCE.nextInt(50);
binomial[i] = RANDOM_SOURCE.nextInt(factorial[i] + 1);
positive[i] = randomPositiveBigInteger(Integer.SIZE - 1).intValue();
nonnegative[i] = randomNonNegativeBigInteger(Integer.SIZE - 1).intValue();
ints[i] = RANDOM_SOURCE.nextInt();
}
}
@Benchmark
int pow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.pow(positive[j], exponent[j]);
}
return tmp;
}
@Benchmark
int mod(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.mod(ints[j], positive[j]);
}
return tmp;
}
@Benchmark
int gCD(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.gcd(nonnegative[j], positive[j]);
}
return tmp;
}
@Benchmark
int factorial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.factorial(factorial[j]);
}
return tmp;
}
@Benchmark
int binomial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.binomial(factorial[j], binomial[j]);
}
return tmp;
}
@Benchmark
int isPrime(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (IntMath.isPrime(positive[j])) {
tmp++;
}
}
return tmp;
}
}
| IntMathBenchmark |
java | apache__rocketmq | tieredstore/src/main/java/org/apache/rocketmq/tieredstore/file/FlatFileInterface.java | {
"start": 1245,
"end": 5428
} | interface ____ {
long getTopicId();
Lock getFileLock();
MessageQueue getMessageQueue();
boolean isFlatFileInit();
void initOffset(long offset);
boolean rollingFile(long interval);
/**
* Appends a message to the commit log file
*
* @param message thByteBuffere message to append
* @return append result
*/
AppendResult appendCommitLog(ByteBuffer message);
AppendResult appendCommitLog(SelectMappedBufferResult message);
/**
* Append message to consume queue file, but does not commit it immediately
*
* @param request the dispatch request
* @return append result
*/
AppendResult appendConsumeQueue(DispatchRequest request);
void release();
long getMinStoreTimestamp();
long getMaxStoreTimestamp();
long getFirstMessageOffset();
long getCommitLogMinOffset();
long getCommitLogMaxOffset();
long getCommitLogCommitOffset();
long getConsumeQueueMinOffset();
long getConsumeQueueMaxOffset();
long getConsumeQueueCommitOffset();
/**
* Persist commit log file and consume queue file
*/
CompletableFuture<Boolean> commitAsync();
/**
* Asynchronously retrieves the message at the specified consume queue offset
*
* @param consumeQueueOffset consume queue offset.
* @return the message inner object serialized content
*/
CompletableFuture<ByteBuffer> getMessageAsync(long consumeQueueOffset);
/**
* Get message from commitLog file at specified offset and length
*
* @param offset the offset
* @param length the length
* @return the message inner object serialized content
*/
CompletableFuture<ByteBuffer> getCommitLogAsync(long offset, int length);
/**
* Asynchronously retrieves the consume queue message at the specified queue offset
*
* @param consumeQueueOffset consume queue offset.
* @return the consumer queue unit serialized content
*/
CompletableFuture<ByteBuffer> getConsumeQueueAsync(long consumeQueueOffset);
/**
* Asynchronously reads the message body from the consume queue file at the specified offset and count
*
* @param consumeQueueOffset the message offset
* @param count the number of messages to read
* @return the consumer queue unit serialized content
*/
CompletableFuture<ByteBuffer> getConsumeQueueAsync(long consumeQueueOffset, int count);
/**
* Gets the start offset in the consume queue based on the timestamp and boundary type.
* The consume queues consist of ordered units, and their storage times are non-decreasing
* sequence. If the specified message exists, it returns the offset of either the first
* or last message, depending on the boundary type. If the specified message does not exist,
* it returns the offset of the next message as the pull offset. For example:
* ------------------------------------------------------------
* store time : 40, 50, 50, 50, 60, 60, 70
* queue offset : 10, 11, 12, 13, 14, 15, 16
* ------------------------------------------------------------
* query timestamp | boundary | result (reason)
* 35 | - | 10 (minimum offset)
* 45 | - | 11 (next offset)
* 50 | lower | 11
* 50 | upper | 13
* 60 | - | 14 (default to lower)
* 75 | - | 17 (maximum offset + 1)
* ------------------------------------------------------------
* @param timestamp The search time
* @param boundaryType 'lower' or 'upper' to determine the boundary
* @return Returns the offset of the message in the consume queue
*/
CompletableFuture<Long> getQueueOffsetByTimeAsync(long timestamp, BoundaryType boundaryType);
boolean isClosed();
/**
* Shutdown process
*/
void shutdown();
/**
* Destroys expired files
*/
void destroyExpiredFile(long timestamp);
/**
* Delete file
*/
void destroy();
}
| FlatFileInterface |
java | apache__flink | flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Session.java | {
"start": 964,
"end": 1399
} | class ____ creating a session window. The boundary of session windows are defined by
* intervals of inactivity, i.e., a session window is closes if no event appears for a defined gap
* period.
*
* <p>Java Example:
*
* <pre>{@code
* Session.withGap("10.minutes").on("rowtime").as("w")
* }</pre>
*
* <p>Scala Example:
*
* <pre>{@code
* Session withGap 10.minutes on 'rowtime as 'w
* }</pre>
*/
@PublicEvolving
public final | for |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/WindowsSecureContainerExecutor.java | {
"start": 2617,
"end": 2775
} | class ____ a secure container executor on Windows, similar to the
* LinuxContainerExecutor. As the NM does not run on a high privileged context,
* this | offers |
java | spring-projects__spring-boot | module/spring-boot-activemq/src/dockerTest/java/org/springframework/boot/activemq/testcontainers/ActiveMQClassicContainerConnectionDetailsFactoryIntegrationTests.java | {
"start": 2749,
"end": 2958
} | class ____ {
private final List<String> messages = new ArrayList<>();
@JmsListener(destination = "sample.queue")
void processMessage(String message) {
this.messages.add(message);
}
}
}
| TestListener |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/snapshots/SystemResourceSnapshotIT.java | {
"start": 61713,
"end": 63455
} | class ____ extends Plugin implements SystemIndexPlugin {
public static final String SYSTEM_DATASTREAM_NAME = ".another-test-system-data-stream";
@Override
public Collection<SystemDataStreamDescriptor> getSystemDataStreamDescriptors() {
try {
CompressedXContent mappings = new CompressedXContent("{\"properties\":{\"name\":{\"type\":\"keyword\"}}}");
return Collections.singletonList(
new SystemDataStreamDescriptor(
SYSTEM_DATASTREAM_NAME,
"another system data stream test",
SystemDataStreamDescriptor.Type.EXTERNAL,
ComposableIndexTemplate.builder()
.indexPatterns(List.of(SYSTEM_DATASTREAM_NAME)) // TODO is this correct?
.template(new Template(Settings.EMPTY, mappings, null))
.dataStreamTemplate(new ComposableIndexTemplate.DataStreamTemplate())
.build(),
Map.of(),
List.of("product"),
"product",
ExecutorNames.DEFAULT_SYSTEM_DATA_STREAM_THREAD_POOLS
)
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public String getFeatureName() {
return AnotherSystemDataStreamTestPlugin.class.getSimpleName();
}
@Override
public String getFeatureDescription() {
return "Another simple test plugin for data streams";
}
}
public static | AnotherSystemDataStreamTestPlugin |
java | playframework__playframework | documentation/manual/working/javaGuide/main/json/code/javaguide/json/JavaJsonActions.java | {
"start": 4153,
"end": 4645
} | class ____ extends MockJavaAction {
JsonRequestAsAnyClazzAction(JavaHandlerComponents javaHandlerComponents) {
super(javaHandlerComponents);
}
// #json-request-as-anyclazz
public Result sayHello(Http.Request request) {
Optional<Person> person = request.body().parseJson(Person.class);
return person.map(p -> ok("Hello, " + p.firstName)).orElse(badRequest("Expecting Json data"));
}
// #json-request-as-anyclazz
}
static | JsonRequestAsAnyClazzAction |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/h12/http1/DefaultHttp11ServerTransportListener.java | {
"start": 5521,
"end": 5989
} | class ____ extends UnaryServerCallListener {
AutoCompleteUnaryServerCallListener(
RpcInvocation invocation, Invoker<?> invoker, StreamObserver<Object> responseObserver) {
super(invocation, invoker, responseObserver);
}
@Override
public void onMessage(Object message) {
super.onMessage(message);
onComplete();
}
}
private static final | AutoCompleteUnaryServerCallListener |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.